gmock-matchers-containers_test.cc 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129
  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 some commonly used argument matchers.
  32. // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
  33. // possible loss of data and C4100, unreferenced local parameter
  34. #ifdef _MSC_VER
  35. #pragma warning(push)
  36. #pragma warning(disable : 4244)
  37. #pragma warning(disable : 4100)
  38. #endif
  39. #include "test/gmock-matchers_test.h"
  40. namespace testing {
  41. namespace gmock_matchers_test {
  42. namespace {
  43. std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {
  44. std::vector<std::unique_ptr<int>> pointers;
  45. for (int i : ints) pointers.emplace_back(new int(i));
  46. return pointers;
  47. }
  48. std::string OfType(const std::string& type_name) {
  49. #if GTEST_HAS_RTTI
  50. return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
  51. #else
  52. return "";
  53. #endif
  54. }
  55. TEST(ContainsTest, WorksWithMoveOnly) {
  56. ContainerHelper helper;
  57. EXPECT_CALL(helper, Call(Contains(Pointee(2))));
  58. helper.Call(MakeUniquePtrs({1, 2}));
  59. }
  60. INSTANTIATE_GTEST_MATCHER_TEST_P(ElementsAreTest);
  61. // Tests the variadic version of the ElementsAreMatcher
  62. TEST(ElementsAreTest, HugeMatcher) {
  63. vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
  64. EXPECT_THAT(test_vector,
  65. ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
  66. Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
  67. }
  68. // Tests the variadic version of the UnorderedElementsAreMatcher
  69. TEST(ElementsAreTest, HugeMatcherStr) {
  70. vector<std::string> test_vector{
  71. "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
  72. EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
  73. _, _, _, _, _, _));
  74. }
  75. // Tests the variadic version of the UnorderedElementsAreMatcher
  76. TEST(ElementsAreTest, HugeMatcherUnordered) {
  77. vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
  78. EXPECT_THAT(test_vector, UnorderedElementsAre(
  79. Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
  80. Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
  81. }
  82. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
  83. // matches the matcher.
  84. TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
  85. ASSERT_THAT(5, Ge(2)) << "This should succeed.";
  86. ASSERT_THAT("Foo", EndsWith("oo"));
  87. EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
  88. EXPECT_THAT("Hello", StartsWith("Hell"));
  89. }
  90. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
  91. // doesn't match the matcher.
  92. TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
  93. // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
  94. // which cannot reference auto variables.
  95. static unsigned short n; // NOLINT
  96. n = 5;
  97. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),
  98. "Value of: n\n"
  99. "Expected: is > 10\n"
  100. " Actual: 5" +
  101. OfType("unsigned short"));
  102. n = 0;
  103. EXPECT_NONFATAL_FAILURE(EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
  104. "Value of: n\n"
  105. "Expected: (is <= 7) and (is >= 5)\n"
  106. " Actual: 0" +
  107. OfType("unsigned short"));
  108. }
  109. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
  110. // has a reference type.
  111. TEST(MatcherAssertionTest, WorksForByRefArguments) {
  112. // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
  113. // reference auto variables.
  114. static int n;
  115. n = 0;
  116. EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
  117. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
  118. "Value of: n\n"
  119. "Expected: does not reference the variable @");
  120. // Tests the "Actual" part.
  121. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
  122. "Actual: 0" + OfType("int") + ", which is located @");
  123. }
  124. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
  125. // monomorphic.
  126. TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
  127. Matcher<const char*> starts_with_he = StartsWith("he");
  128. ASSERT_THAT("hello", starts_with_he);
  129. Matcher<const std::string&> ends_with_ok = EndsWith("ok");
  130. ASSERT_THAT("book", ends_with_ok);
  131. const std::string bad = "bad";
  132. EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
  133. "Value of: bad\n"
  134. "Expected: ends with \"ok\"\n"
  135. " Actual: \"bad\"");
  136. Matcher<int> is_greater_than_5 = Gt(5);
  137. EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
  138. "Value of: 5\n"
  139. "Expected: is > 5\n"
  140. " Actual: 5" +
  141. OfType("int"));
  142. }
  143. TEST(PointeeTest, RawPointer) {
  144. const Matcher<int*> m = Pointee(Ge(0));
  145. int n = 1;
  146. EXPECT_TRUE(m.Matches(&n));
  147. n = -1;
  148. EXPECT_FALSE(m.Matches(&n));
  149. EXPECT_FALSE(m.Matches(nullptr));
  150. }
  151. TEST(PointeeTest, RawPointerToConst) {
  152. const Matcher<const double*> m = Pointee(Ge(0));
  153. double x = 1;
  154. EXPECT_TRUE(m.Matches(&x));
  155. x = -1;
  156. EXPECT_FALSE(m.Matches(&x));
  157. EXPECT_FALSE(m.Matches(nullptr));
  158. }
  159. TEST(PointeeTest, ReferenceToConstRawPointer) {
  160. const Matcher<int* const&> m = Pointee(Ge(0));
  161. int n = 1;
  162. EXPECT_TRUE(m.Matches(&n));
  163. n = -1;
  164. EXPECT_FALSE(m.Matches(&n));
  165. EXPECT_FALSE(m.Matches(nullptr));
  166. }
  167. TEST(PointeeTest, ReferenceToNonConstRawPointer) {
  168. const Matcher<double*&> m = Pointee(Ge(0));
  169. double x = 1.0;
  170. double* p = &x;
  171. EXPECT_TRUE(m.Matches(p));
  172. x = -1;
  173. EXPECT_FALSE(m.Matches(p));
  174. p = nullptr;
  175. EXPECT_FALSE(m.Matches(p));
  176. }
  177. TEST(PointeeTest, SmartPointer) {
  178. const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
  179. std::unique_ptr<int> n(new int(1));
  180. EXPECT_TRUE(m.Matches(n));
  181. }
  182. TEST(PointeeTest, SmartPointerToConst) {
  183. const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));
  184. // There's no implicit conversion from unique_ptr<int> to const
  185. // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
  186. // matcher.
  187. std::unique_ptr<const int> n(new int(1));
  188. EXPECT_TRUE(m.Matches(n));
  189. }
  190. TEST(PointerTest, RawPointer) {
  191. int n = 1;
  192. const Matcher<int*> m = Pointer(Eq(&n));
  193. EXPECT_TRUE(m.Matches(&n));
  194. int* p = nullptr;
  195. EXPECT_FALSE(m.Matches(p));
  196. EXPECT_FALSE(m.Matches(nullptr));
  197. }
  198. TEST(PointerTest, RawPointerToConst) {
  199. int n = 1;
  200. const Matcher<const int*> m = Pointer(Eq(&n));
  201. EXPECT_TRUE(m.Matches(&n));
  202. int* p = nullptr;
  203. EXPECT_FALSE(m.Matches(p));
  204. EXPECT_FALSE(m.Matches(nullptr));
  205. }
  206. TEST(PointerTest, SmartPointer) {
  207. std::unique_ptr<int> n(new int(10));
  208. int* raw_n = n.get();
  209. const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
  210. EXPECT_TRUE(m.Matches(n));
  211. }
  212. TEST(PointerTest, SmartPointerToConst) {
  213. std::unique_ptr<const int> n(new int(10));
  214. const int* raw_n = n.get();
  215. const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n));
  216. // There's no implicit conversion from unique_ptr<int> to const
  217. // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
  218. // matcher.
  219. std::unique_ptr<const int> p(new int(10));
  220. EXPECT_FALSE(m.Matches(p));
  221. }
  222. // Minimal const-propagating pointer.
  223. template <typename T>
  224. class ConstPropagatingPtr {
  225. public:
  226. typedef T element_type;
  227. ConstPropagatingPtr() : val_() {}
  228. explicit ConstPropagatingPtr(T* t) : val_(t) {}
  229. ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
  230. T* get() { return val_; }
  231. T& operator*() { return *val_; }
  232. // Most smart pointers return non-const T* and T& from the next methods.
  233. const T* get() const { return val_; }
  234. const T& operator*() const { return *val_; }
  235. private:
  236. T* val_;
  237. };
  238. INSTANTIATE_GTEST_MATCHER_TEST_P(PointeeTest);
  239. TEST(PointeeTest, WorksWithConstPropagatingPointers) {
  240. const Matcher<ConstPropagatingPtr<int>> m = Pointee(Lt(5));
  241. int three = 3;
  242. const ConstPropagatingPtr<int> co(&three);
  243. ConstPropagatingPtr<int> o(&three);
  244. EXPECT_TRUE(m.Matches(o));
  245. EXPECT_TRUE(m.Matches(co));
  246. *o = 6;
  247. EXPECT_FALSE(m.Matches(o));
  248. EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
  249. }
  250. TEST(PointeeTest, NeverMatchesNull) {
  251. const Matcher<const char*> m = Pointee(_);
  252. EXPECT_FALSE(m.Matches(nullptr));
  253. }
  254. // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
  255. TEST(PointeeTest, MatchesAgainstAValue) {
  256. const Matcher<int*> m = Pointee(5);
  257. int n = 5;
  258. EXPECT_TRUE(m.Matches(&n));
  259. n = -1;
  260. EXPECT_FALSE(m.Matches(&n));
  261. EXPECT_FALSE(m.Matches(nullptr));
  262. }
  263. TEST(PointeeTest, CanDescribeSelf) {
  264. const Matcher<int*> m = Pointee(Gt(3));
  265. EXPECT_EQ("points to a value that is > 3", Describe(m));
  266. EXPECT_EQ("does not point to a value that is > 3", DescribeNegation(m));
  267. }
  268. TEST_P(PointeeTestP, CanExplainMatchResult) {
  269. const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
  270. EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
  271. const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
  272. long n = 3; // NOLINT
  273. EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
  274. Explain(m2, &n));
  275. }
  276. TEST(PointeeTest, AlwaysExplainsPointee) {
  277. const Matcher<int*> m = Pointee(0);
  278. int n = 42;
  279. EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
  280. }
  281. // An uncopyable class.
  282. class Uncopyable {
  283. public:
  284. Uncopyable() : value_(-1) {}
  285. explicit Uncopyable(int a_value) : value_(a_value) {}
  286. int value() const { return value_; }
  287. void set_value(int i) { value_ = i; }
  288. private:
  289. int value_;
  290. Uncopyable(const Uncopyable&) = delete;
  291. Uncopyable& operator=(const Uncopyable&) = delete;
  292. };
  293. // Returns true if and only if x.value() is positive.
  294. bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
  295. MATCHER_P(UncopyableIs, inner_matcher, "") {
  296. return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
  297. }
  298. // A user-defined struct for testing Field().
  299. struct AStruct {
  300. AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
  301. AStruct(const AStruct& rhs)
  302. : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
  303. int x; // A non-const field.
  304. const double y; // A const field.
  305. Uncopyable z; // An uncopyable field.
  306. const char* p; // A pointer field.
  307. };
  308. // A derived struct for testing Field().
  309. struct DerivedStruct : public AStruct {
  310. char ch;
  311. };
  312. INSTANTIATE_GTEST_MATCHER_TEST_P(FieldTest);
  313. // Tests that Field(&Foo::field, ...) works when field is non-const.
  314. TEST(FieldTest, WorksForNonConstField) {
  315. Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
  316. Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
  317. AStruct a;
  318. EXPECT_TRUE(m.Matches(a));
  319. EXPECT_TRUE(m_with_name.Matches(a));
  320. a.x = -1;
  321. EXPECT_FALSE(m.Matches(a));
  322. EXPECT_FALSE(m_with_name.Matches(a));
  323. }
  324. // Tests that Field(&Foo::field, ...) works when field is const.
  325. TEST(FieldTest, WorksForConstField) {
  326. AStruct a;
  327. Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
  328. Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
  329. EXPECT_TRUE(m.Matches(a));
  330. EXPECT_TRUE(m_with_name.Matches(a));
  331. m = Field(&AStruct::y, Le(0.0));
  332. m_with_name = Field("y", &AStruct::y, Le(0.0));
  333. EXPECT_FALSE(m.Matches(a));
  334. EXPECT_FALSE(m_with_name.Matches(a));
  335. }
  336. // Tests that Field(&Foo::field, ...) works when field is not copyable.
  337. TEST(FieldTest, WorksForUncopyableField) {
  338. AStruct a;
  339. Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
  340. EXPECT_TRUE(m.Matches(a));
  341. m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
  342. EXPECT_FALSE(m.Matches(a));
  343. }
  344. // Tests that Field(&Foo::field, ...) works when field is a pointer.
  345. TEST(FieldTest, WorksForPointerField) {
  346. // Matching against NULL.
  347. Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
  348. AStruct a;
  349. EXPECT_TRUE(m.Matches(a));
  350. a.p = "hi";
  351. EXPECT_FALSE(m.Matches(a));
  352. // Matching a pointer that is not NULL.
  353. m = Field(&AStruct::p, StartsWith("hi"));
  354. a.p = "hill";
  355. EXPECT_TRUE(m.Matches(a));
  356. a.p = "hole";
  357. EXPECT_FALSE(m.Matches(a));
  358. }
  359. // Tests that Field() works when the object is passed by reference.
  360. TEST(FieldTest, WorksForByRefArgument) {
  361. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  362. AStruct a;
  363. EXPECT_TRUE(m.Matches(a));
  364. a.x = -1;
  365. EXPECT_FALSE(m.Matches(a));
  366. }
  367. // Tests that Field(&Foo::field, ...) works when the argument's type
  368. // is a sub-type of Foo.
  369. TEST(FieldTest, WorksForArgumentOfSubType) {
  370. // Note that the matcher expects DerivedStruct but we say AStruct
  371. // inside Field().
  372. Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
  373. DerivedStruct d;
  374. EXPECT_TRUE(m.Matches(d));
  375. d.x = -1;
  376. EXPECT_FALSE(m.Matches(d));
  377. }
  378. // Tests that Field(&Foo::field, m) works when field's type and m's
  379. // argument type are compatible but not the same.
  380. TEST(FieldTest, WorksForCompatibleMatcherType) {
  381. // The field is an int, but the inner matcher expects a signed char.
  382. Matcher<const AStruct&> m = Field(&AStruct::x, Matcher<signed char>(Ge(0)));
  383. AStruct a;
  384. EXPECT_TRUE(m.Matches(a));
  385. a.x = -1;
  386. EXPECT_FALSE(m.Matches(a));
  387. }
  388. // Tests that Field() can describe itself.
  389. TEST(FieldTest, CanDescribeSelf) {
  390. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  391. EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
  392. EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
  393. }
  394. TEST(FieldTest, CanDescribeSelfWithFieldName) {
  395. Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
  396. EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
  397. EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
  398. DescribeNegation(m));
  399. }
  400. // Tests that Field() can explain the match result.
  401. TEST_P(FieldTestP, CanExplainMatchResult) {
  402. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  403. AStruct a;
  404. a.x = 1;
  405. EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
  406. m = Field(&AStruct::x, GreaterThan(0));
  407. EXPECT_EQ(
  408. "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
  409. Explain(m, a));
  410. }
  411. TEST_P(FieldTestP, CanExplainMatchResultWithFieldName) {
  412. Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
  413. AStruct a;
  414. a.x = 1;
  415. EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
  416. m = Field("field_name", &AStruct::x, GreaterThan(0));
  417. EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
  418. ", which is 1 more than 0",
  419. Explain(m, a));
  420. }
  421. INSTANTIATE_GTEST_MATCHER_TEST_P(FieldForPointerTest);
  422. // Tests that Field() works when the argument is a pointer to const.
  423. TEST(FieldForPointerTest, WorksForPointerToConst) {
  424. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  425. AStruct a;
  426. EXPECT_TRUE(m.Matches(&a));
  427. a.x = -1;
  428. EXPECT_FALSE(m.Matches(&a));
  429. }
  430. // Tests that Field() works when the argument is a pointer to non-const.
  431. TEST(FieldForPointerTest, WorksForPointerToNonConst) {
  432. Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
  433. AStruct a;
  434. EXPECT_TRUE(m.Matches(&a));
  435. a.x = -1;
  436. EXPECT_FALSE(m.Matches(&a));
  437. }
  438. // Tests that Field() works when the argument is a reference to a const pointer.
  439. TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
  440. Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
  441. AStruct a;
  442. EXPECT_TRUE(m.Matches(&a));
  443. a.x = -1;
  444. EXPECT_FALSE(m.Matches(&a));
  445. }
  446. // Tests that Field() does not match the NULL pointer.
  447. TEST(FieldForPointerTest, DoesNotMatchNull) {
  448. Matcher<const AStruct*> m = Field(&AStruct::x, _);
  449. EXPECT_FALSE(m.Matches(nullptr));
  450. }
  451. // Tests that Field(&Foo::field, ...) works when the argument's type
  452. // is a sub-type of const Foo*.
  453. TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
  454. // Note that the matcher expects DerivedStruct but we say AStruct
  455. // inside Field().
  456. Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
  457. DerivedStruct d;
  458. EXPECT_TRUE(m.Matches(&d));
  459. d.x = -1;
  460. EXPECT_FALSE(m.Matches(&d));
  461. }
  462. // Tests that Field() can describe itself when used to match a pointer.
  463. TEST(FieldForPointerTest, CanDescribeSelf) {
  464. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  465. EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
  466. EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
  467. }
  468. TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
  469. Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
  470. EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
  471. EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
  472. DescribeNegation(m));
  473. }
  474. // Tests that Field() can explain the result of matching a pointer.
  475. TEST_P(FieldForPointerTestP, CanExplainMatchResult) {
  476. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  477. AStruct a;
  478. a.x = 1;
  479. EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
  480. EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
  481. Explain(m, &a));
  482. m = Field(&AStruct::x, GreaterThan(0));
  483. EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
  484. ", which is 1 more than 0",
  485. Explain(m, &a));
  486. }
  487. TEST_P(FieldForPointerTestP, CanExplainMatchResultWithFieldName) {
  488. Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
  489. AStruct a;
  490. a.x = 1;
  491. EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
  492. EXPECT_EQ(
  493. "which points to an object whose field `field_name` is 1" + OfType("int"),
  494. Explain(m, &a));
  495. m = Field("field_name", &AStruct::x, GreaterThan(0));
  496. EXPECT_EQ("which points to an object whose field `field_name` is 1" +
  497. OfType("int") + ", which is 1 more than 0",
  498. Explain(m, &a));
  499. }
  500. // A user-defined class for testing Property().
  501. class AClass {
  502. public:
  503. AClass() : n_(0) {}
  504. // A getter that returns a non-reference.
  505. int n() const { return n_; }
  506. void set_n(int new_n) { n_ = new_n; }
  507. // A getter that returns a reference to const.
  508. const std::string& s() const { return s_; }
  509. const std::string& s_ref() const& { return s_; }
  510. void set_s(const std::string& new_s) { s_ = new_s; }
  511. // A getter that returns a reference to non-const.
  512. double& x() const { return x_; }
  513. private:
  514. int n_;
  515. std::string s_;
  516. static double x_;
  517. };
  518. double AClass::x_ = 0.0;
  519. // A derived class for testing Property().
  520. class DerivedClass : public AClass {
  521. public:
  522. int k() const { return k_; }
  523. private:
  524. int k_;
  525. };
  526. INSTANTIATE_GTEST_MATCHER_TEST_P(PropertyTest);
  527. // Tests that Property(&Foo::property, ...) works when property()
  528. // returns a non-reference.
  529. TEST(PropertyTest, WorksForNonReferenceProperty) {
  530. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  531. Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
  532. AClass a;
  533. a.set_n(1);
  534. EXPECT_TRUE(m.Matches(a));
  535. EXPECT_TRUE(m_with_name.Matches(a));
  536. a.set_n(-1);
  537. EXPECT_FALSE(m.Matches(a));
  538. EXPECT_FALSE(m_with_name.Matches(a));
  539. }
  540. // Tests that Property(&Foo::property, ...) works when property()
  541. // returns a reference to const.
  542. TEST(PropertyTest, WorksForReferenceToConstProperty) {
  543. Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
  544. Matcher<const AClass&> m_with_name =
  545. Property("s", &AClass::s, StartsWith("hi"));
  546. AClass a;
  547. a.set_s("hill");
  548. EXPECT_TRUE(m.Matches(a));
  549. EXPECT_TRUE(m_with_name.Matches(a));
  550. a.set_s("hole");
  551. EXPECT_FALSE(m.Matches(a));
  552. EXPECT_FALSE(m_with_name.Matches(a));
  553. }
  554. // Tests that Property(&Foo::property, ...) works when property() is
  555. // ref-qualified.
  556. TEST(PropertyTest, WorksForRefQualifiedProperty) {
  557. Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
  558. Matcher<const AClass&> m_with_name =
  559. Property("s", &AClass::s_ref, StartsWith("hi"));
  560. AClass a;
  561. a.set_s("hill");
  562. EXPECT_TRUE(m.Matches(a));
  563. EXPECT_TRUE(m_with_name.Matches(a));
  564. a.set_s("hole");
  565. EXPECT_FALSE(m.Matches(a));
  566. EXPECT_FALSE(m_with_name.Matches(a));
  567. }
  568. // Tests that Property(&Foo::property, ...) works when property()
  569. // returns a reference to non-const.
  570. TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
  571. double x = 0.0;
  572. AClass a;
  573. Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
  574. EXPECT_FALSE(m.Matches(a));
  575. m = Property(&AClass::x, Not(Ref(x)));
  576. EXPECT_TRUE(m.Matches(a));
  577. }
  578. // Tests that Property(&Foo::property, ...) works when the argument is
  579. // passed by value.
  580. TEST(PropertyTest, WorksForByValueArgument) {
  581. Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
  582. AClass a;
  583. a.set_s("hill");
  584. EXPECT_TRUE(m.Matches(a));
  585. a.set_s("hole");
  586. EXPECT_FALSE(m.Matches(a));
  587. }
  588. // Tests that Property(&Foo::property, ...) works when the argument's
  589. // type is a sub-type of Foo.
  590. TEST(PropertyTest, WorksForArgumentOfSubType) {
  591. // The matcher expects a DerivedClass, but inside the Property() we
  592. // say AClass.
  593. Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
  594. DerivedClass d;
  595. d.set_n(1);
  596. EXPECT_TRUE(m.Matches(d));
  597. d.set_n(-1);
  598. EXPECT_FALSE(m.Matches(d));
  599. }
  600. // Tests that Property(&Foo::property, m) works when property()'s type
  601. // and m's argument type are compatible but different.
  602. TEST(PropertyTest, WorksForCompatibleMatcherType) {
  603. // n() returns an int but the inner matcher expects a signed char.
  604. Matcher<const AClass&> m = Property(&AClass::n, Matcher<signed char>(Ge(0)));
  605. Matcher<const AClass&> m_with_name =
  606. Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
  607. AClass a;
  608. EXPECT_TRUE(m.Matches(a));
  609. EXPECT_TRUE(m_with_name.Matches(a));
  610. a.set_n(-1);
  611. EXPECT_FALSE(m.Matches(a));
  612. EXPECT_FALSE(m_with_name.Matches(a));
  613. }
  614. // Tests that Property() can describe itself.
  615. TEST(PropertyTest, CanDescribeSelf) {
  616. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  617. EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
  618. EXPECT_EQ("is an object whose given property isn't >= 0",
  619. DescribeNegation(m));
  620. }
  621. TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
  622. Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
  623. EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
  624. EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
  625. DescribeNegation(m));
  626. }
  627. // Tests that Property() can explain the match result.
  628. TEST_P(PropertyTestP, CanExplainMatchResult) {
  629. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  630. AClass a;
  631. a.set_n(1);
  632. EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
  633. m = Property(&AClass::n, GreaterThan(0));
  634. EXPECT_EQ(
  635. "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
  636. Explain(m, a));
  637. }
  638. TEST_P(PropertyTestP, CanExplainMatchResultWithPropertyName) {
  639. Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
  640. AClass a;
  641. a.set_n(1);
  642. EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
  643. m = Property("fancy_name", &AClass::n, GreaterThan(0));
  644. EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
  645. ", which is 1 more than 0",
  646. Explain(m, a));
  647. }
  648. INSTANTIATE_GTEST_MATCHER_TEST_P(PropertyForPointerTest);
  649. // Tests that Property() works when the argument is a pointer to const.
  650. TEST(PropertyForPointerTest, WorksForPointerToConst) {
  651. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  652. AClass a;
  653. a.set_n(1);
  654. EXPECT_TRUE(m.Matches(&a));
  655. a.set_n(-1);
  656. EXPECT_FALSE(m.Matches(&a));
  657. }
  658. // Tests that Property() works when the argument is a pointer to non-const.
  659. TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
  660. Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
  661. AClass a;
  662. a.set_s("hill");
  663. EXPECT_TRUE(m.Matches(&a));
  664. a.set_s("hole");
  665. EXPECT_FALSE(m.Matches(&a));
  666. }
  667. // Tests that Property() works when the argument is a reference to a
  668. // const pointer.
  669. TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
  670. Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
  671. AClass a;
  672. a.set_s("hill");
  673. EXPECT_TRUE(m.Matches(&a));
  674. a.set_s("hole");
  675. EXPECT_FALSE(m.Matches(&a));
  676. }
  677. // Tests that Property() does not match the NULL pointer.
  678. TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
  679. Matcher<const AClass*> m = Property(&AClass::x, _);
  680. EXPECT_FALSE(m.Matches(nullptr));
  681. }
  682. // Tests that Property(&Foo::property, ...) works when the argument's
  683. // type is a sub-type of const Foo*.
  684. TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
  685. // The matcher expects a DerivedClass, but inside the Property() we
  686. // say AClass.
  687. Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
  688. DerivedClass d;
  689. d.set_n(1);
  690. EXPECT_TRUE(m.Matches(&d));
  691. d.set_n(-1);
  692. EXPECT_FALSE(m.Matches(&d));
  693. }
  694. // Tests that Property() can describe itself when used to match a pointer.
  695. TEST(PropertyForPointerTest, CanDescribeSelf) {
  696. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  697. EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
  698. EXPECT_EQ("is an object whose given property isn't >= 0",
  699. DescribeNegation(m));
  700. }
  701. TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
  702. Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
  703. EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
  704. EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
  705. DescribeNegation(m));
  706. }
  707. // Tests that Property() can explain the result of matching a pointer.
  708. TEST_P(PropertyForPointerTestP, CanExplainMatchResult) {
  709. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  710. AClass a;
  711. a.set_n(1);
  712. EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
  713. EXPECT_EQ(
  714. "which points to an object whose given property is 1" + OfType("int"),
  715. Explain(m, &a));
  716. m = Property(&AClass::n, GreaterThan(0));
  717. EXPECT_EQ("which points to an object whose given property is 1" +
  718. OfType("int") + ", which is 1 more than 0",
  719. Explain(m, &a));
  720. }
  721. TEST_P(PropertyForPointerTestP, CanExplainMatchResultWithPropertyName) {
  722. Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
  723. AClass a;
  724. a.set_n(1);
  725. EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
  726. EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
  727. OfType("int"),
  728. Explain(m, &a));
  729. m = Property("fancy_name", &AClass::n, GreaterThan(0));
  730. EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
  731. OfType("int") + ", which is 1 more than 0",
  732. Explain(m, &a));
  733. }
  734. // Tests ResultOf.
  735. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  736. // function pointer.
  737. std::string IntToStringFunction(int input) {
  738. return input == 1 ? "foo" : "bar";
  739. }
  740. INSTANTIATE_GTEST_MATCHER_TEST_P(ResultOfTest);
  741. TEST(ResultOfTest, WorksForFunctionPointers) {
  742. Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
  743. EXPECT_TRUE(matcher.Matches(1));
  744. EXPECT_FALSE(matcher.Matches(2));
  745. }
  746. // Tests that ResultOf() can describe itself.
  747. TEST(ResultOfTest, CanDescribeItself) {
  748. Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
  749. EXPECT_EQ(
  750. "is mapped by the given callable to a value that "
  751. "is equal to \"foo\"",
  752. Describe(matcher));
  753. EXPECT_EQ(
  754. "is mapped by the given callable to a value that "
  755. "isn't equal to \"foo\"",
  756. DescribeNegation(matcher));
  757. }
  758. // Tests that ResultOf() can describe itself when provided a result description.
  759. TEST(ResultOfTest, CanDescribeItselfWithResultDescription) {
  760. Matcher<int> matcher =
  761. ResultOf("string conversion", &IntToStringFunction, StrEq("foo"));
  762. EXPECT_EQ("whose string conversion is equal to \"foo\"", Describe(matcher));
  763. EXPECT_EQ("whose string conversion isn't equal to \"foo\"",
  764. DescribeNegation(matcher));
  765. }
  766. // Tests that ResultOf() can explain the match result.
  767. int IntFunction(int input) { return input == 42 ? 80 : 90; }
  768. TEST_P(ResultOfTestP, CanExplainMatchResult) {
  769. Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
  770. EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
  771. Explain(matcher, 36));
  772. matcher = ResultOf(&IntFunction, GreaterThan(85));
  773. EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
  774. ", which is 5 more than 85",
  775. Explain(matcher, 36));
  776. }
  777. TEST_P(ResultOfTestP, CanExplainMatchResultWithResultDescription) {
  778. Matcher<int> matcher = ResultOf("magic int conversion", &IntFunction, Ge(85));
  779. EXPECT_EQ("whose magic int conversion is 90" + OfType("int"),
  780. Explain(matcher, 36));
  781. matcher = ResultOf("magic int conversion", &IntFunction, GreaterThan(85));
  782. EXPECT_EQ("whose magic int conversion is 90" + OfType("int") +
  783. ", which is 5 more than 85",
  784. Explain(matcher, 36));
  785. }
  786. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  787. // returns a non-reference.
  788. TEST(ResultOfTest, WorksForNonReferenceResults) {
  789. Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
  790. EXPECT_TRUE(matcher.Matches(42));
  791. EXPECT_FALSE(matcher.Matches(36));
  792. }
  793. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  794. // returns a reference to non-const.
  795. double& DoubleFunction(double& input) { return input; } // NOLINT
  796. Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
  797. return obj;
  798. }
  799. TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
  800. double x = 3.14;
  801. double x2 = x;
  802. Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
  803. EXPECT_TRUE(matcher.Matches(x));
  804. EXPECT_FALSE(matcher.Matches(x2));
  805. // Test that ResultOf works with uncopyable objects
  806. Uncopyable obj(0);
  807. Uncopyable obj2(0);
  808. Matcher<Uncopyable&> matcher2 = ResultOf(&RefUncopyableFunction, Ref(obj));
  809. EXPECT_TRUE(matcher2.Matches(obj));
  810. EXPECT_FALSE(matcher2.Matches(obj2));
  811. }
  812. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  813. // returns a reference to const.
  814. const std::string& StringFunction(const std::string& input) { return input; }
  815. TEST(ResultOfTest, WorksForReferenceToConstResults) {
  816. std::string s = "foo";
  817. std::string s2 = s;
  818. Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
  819. EXPECT_TRUE(matcher.Matches(s));
  820. EXPECT_FALSE(matcher.Matches(s2));
  821. }
  822. // Tests that ResultOf(f, m) works when f(x) and m's
  823. // argument types are compatible but different.
  824. TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
  825. // IntFunction() returns int but the inner matcher expects a signed char.
  826. Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
  827. EXPECT_TRUE(matcher.Matches(36));
  828. EXPECT_FALSE(matcher.Matches(42));
  829. }
  830. // Tests that the program aborts when ResultOf is passed
  831. // a NULL function pointer.
  832. TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
  833. EXPECT_DEATH_IF_SUPPORTED(
  834. ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
  835. Eq(std::string("foo"))),
  836. "NULL function pointer is passed into ResultOf\\(\\)\\.");
  837. }
  838. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  839. // function reference.
  840. TEST(ResultOfTest, WorksForFunctionReferences) {
  841. Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
  842. EXPECT_TRUE(matcher.Matches(1));
  843. EXPECT_FALSE(matcher.Matches(2));
  844. }
  845. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  846. // function object.
  847. struct Functor {
  848. std::string operator()(int input) const { return IntToStringFunction(input); }
  849. };
  850. TEST(ResultOfTest, WorksForFunctors) {
  851. Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
  852. EXPECT_TRUE(matcher.Matches(1));
  853. EXPECT_FALSE(matcher.Matches(2));
  854. }
  855. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  856. // functor with more than one operator() defined. ResultOf() must work
  857. // for each defined operator().
  858. struct PolymorphicFunctor {
  859. typedef int result_type;
  860. int operator()(int n) { return n; }
  861. int operator()(const char* s) { return static_cast<int>(strlen(s)); }
  862. std::string operator()(int* p) { return p ? "good ptr" : "null"; }
  863. };
  864. TEST(ResultOfTest, WorksForPolymorphicFunctors) {
  865. Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
  866. EXPECT_TRUE(matcher_int.Matches(10));
  867. EXPECT_FALSE(matcher_int.Matches(2));
  868. Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
  869. EXPECT_TRUE(matcher_string.Matches("long string"));
  870. EXPECT_FALSE(matcher_string.Matches("shrt"));
  871. }
  872. TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
  873. Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
  874. int n = 0;
  875. EXPECT_TRUE(matcher.Matches(&n));
  876. EXPECT_FALSE(matcher.Matches(nullptr));
  877. }
  878. TEST(ResultOfTest, WorksForLambdas) {
  879. Matcher<int> matcher = ResultOf(
  880. [](int str_len) {
  881. return std::string(static_cast<size_t>(str_len), 'x');
  882. },
  883. "xxx");
  884. EXPECT_TRUE(matcher.Matches(3));
  885. EXPECT_FALSE(matcher.Matches(1));
  886. }
  887. TEST(ResultOfTest, WorksForNonCopyableArguments) {
  888. Matcher<std::unique_ptr<int>> matcher = ResultOf(
  889. [](const std::unique_ptr<int>& str_len) {
  890. return std::string(static_cast<size_t>(*str_len), 'x');
  891. },
  892. "xxx");
  893. EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
  894. EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
  895. }
  896. const int* ReferencingFunction(const int& n) { return &n; }
  897. struct ReferencingFunctor {
  898. typedef const int* result_type;
  899. result_type operator()(const int& n) { return &n; }
  900. };
  901. TEST(ResultOfTest, WorksForReferencingCallables) {
  902. const int n = 1;
  903. const int n2 = 1;
  904. Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
  905. EXPECT_TRUE(matcher2.Matches(n));
  906. EXPECT_FALSE(matcher2.Matches(n2));
  907. Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
  908. EXPECT_TRUE(matcher3.Matches(n));
  909. EXPECT_FALSE(matcher3.Matches(n2));
  910. }
  911. TEST(SizeIsTest, ImplementsSizeIs) {
  912. vector<int> container;
  913. EXPECT_THAT(container, SizeIs(0));
  914. EXPECT_THAT(container, Not(SizeIs(1)));
  915. container.push_back(0);
  916. EXPECT_THAT(container, Not(SizeIs(0)));
  917. EXPECT_THAT(container, SizeIs(1));
  918. container.push_back(0);
  919. EXPECT_THAT(container, Not(SizeIs(0)));
  920. EXPECT_THAT(container, SizeIs(2));
  921. }
  922. TEST(SizeIsTest, WorksWithMap) {
  923. map<std::string, int> container;
  924. EXPECT_THAT(container, SizeIs(0));
  925. EXPECT_THAT(container, Not(SizeIs(1)));
  926. container.insert(make_pair("foo", 1));
  927. EXPECT_THAT(container, Not(SizeIs(0)));
  928. EXPECT_THAT(container, SizeIs(1));
  929. container.insert(make_pair("bar", 2));
  930. EXPECT_THAT(container, Not(SizeIs(0)));
  931. EXPECT_THAT(container, SizeIs(2));
  932. }
  933. TEST(SizeIsTest, WorksWithReferences) {
  934. vector<int> container;
  935. Matcher<const vector<int>&> m = SizeIs(1);
  936. EXPECT_THAT(container, Not(m));
  937. container.push_back(0);
  938. EXPECT_THAT(container, m);
  939. }
  940. TEST(SizeIsTest, WorksWithMoveOnly) {
  941. ContainerHelper helper;
  942. EXPECT_CALL(helper, Call(SizeIs(3)));
  943. helper.Call(MakeUniquePtrs({1, 2, 3}));
  944. }
  945. // SizeIs should work for any type that provides a size() member function.
  946. // For example, a size_type member type should not need to be provided.
  947. struct MinimalistCustomType {
  948. int size() const { return 1; }
  949. };
  950. TEST(SizeIsTest, WorksWithMinimalistCustomType) {
  951. MinimalistCustomType container;
  952. EXPECT_THAT(container, SizeIs(1));
  953. EXPECT_THAT(container, Not(SizeIs(0)));
  954. }
  955. TEST(SizeIsTest, CanDescribeSelf) {
  956. Matcher<vector<int>> m = SizeIs(2);
  957. EXPECT_EQ("has a size that is equal to 2", Describe(m));
  958. EXPECT_EQ("has a size that isn't equal to 2", DescribeNegation(m));
  959. }
  960. TEST(SizeIsTest, ExplainsResult) {
  961. Matcher<vector<int>> m1 = SizeIs(2);
  962. Matcher<vector<int>> m2 = SizeIs(Lt(2u));
  963. Matcher<vector<int>> m3 = SizeIs(AnyOf(0, 3));
  964. Matcher<vector<int>> m4 = SizeIs(Gt(1u));
  965. vector<int> container;
  966. EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
  967. EXPECT_EQ("whose size 0 matches", Explain(m2, container));
  968. EXPECT_EQ("whose size 0 matches", Explain(m3, container));
  969. EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
  970. container.push_back(0);
  971. container.push_back(0);
  972. EXPECT_EQ("whose size 2 matches", Explain(m1, container));
  973. EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
  974. EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
  975. EXPECT_EQ("whose size 2 matches", Explain(m4, container));
  976. }
  977. TEST(WhenSortedByTest, WorksForEmptyContainer) {
  978. const vector<int> numbers;
  979. EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
  980. EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
  981. }
  982. TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
  983. vector<unsigned> numbers;
  984. numbers.push_back(3);
  985. numbers.push_back(1);
  986. numbers.push_back(2);
  987. numbers.push_back(2);
  988. EXPECT_THAT(numbers,
  989. WhenSortedBy(greater<unsigned>(), ElementsAre(3, 2, 2, 1)));
  990. EXPECT_THAT(numbers,
  991. Not(WhenSortedBy(greater<unsigned>(), ElementsAre(1, 2, 2, 3))));
  992. }
  993. TEST(WhenSortedByTest, WorksForNonVectorContainer) {
  994. list<std::string> words;
  995. words.push_back("say");
  996. words.push_back("hello");
  997. words.push_back("world");
  998. EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
  999. ElementsAre("hello", "say", "world")));
  1000. EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
  1001. ElementsAre("say", "hello", "world"))));
  1002. }
  1003. TEST(WhenSortedByTest, WorksForNativeArray) {
  1004. const int numbers[] = {1, 3, 2, 4};
  1005. const int sorted_numbers[] = {1, 2, 3, 4};
  1006. EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
  1007. EXPECT_THAT(numbers,
  1008. WhenSortedBy(less<int>(), ElementsAreArray(sorted_numbers)));
  1009. EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
  1010. }
  1011. TEST(WhenSortedByTest, CanDescribeSelf) {
  1012. const Matcher<vector<int>> m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
  1013. EXPECT_EQ(
  1014. "(when sorted) has 2 elements where\n"
  1015. "element #0 is equal to 1,\n"
  1016. "element #1 is equal to 2",
  1017. Describe(m));
  1018. EXPECT_EQ(
  1019. "(when sorted) doesn't have 2 elements, or\n"
  1020. "element #0 isn't equal to 1, or\n"
  1021. "element #1 isn't equal to 2",
  1022. DescribeNegation(m));
  1023. }
  1024. TEST(WhenSortedByTest, ExplainsMatchResult) {
  1025. const int a[] = {2, 1};
  1026. EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
  1027. Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
  1028. EXPECT_EQ("which is { 1, 2 } when sorted",
  1029. Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
  1030. }
  1031. // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
  1032. // need to test it as exhaustively as we test the latter.
  1033. TEST(WhenSortedTest, WorksForEmptyContainer) {
  1034. const vector<int> numbers;
  1035. EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
  1036. EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
  1037. }
  1038. TEST(WhenSortedTest, WorksForNonEmptyContainer) {
  1039. list<std::string> words;
  1040. words.push_back("3");
  1041. words.push_back("1");
  1042. words.push_back("2");
  1043. words.push_back("2");
  1044. EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
  1045. EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
  1046. }
  1047. TEST(WhenSortedTest, WorksForMapTypes) {
  1048. map<std::string, int> word_counts;
  1049. word_counts["and"] = 1;
  1050. word_counts["the"] = 1;
  1051. word_counts["buffalo"] = 2;
  1052. EXPECT_THAT(word_counts,
  1053. WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
  1054. Pair("the", 1))));
  1055. EXPECT_THAT(word_counts,
  1056. Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
  1057. Pair("buffalo", 2)))));
  1058. }
  1059. TEST(WhenSortedTest, WorksForMultiMapTypes) {
  1060. multimap<int, int> ifib;
  1061. ifib.insert(make_pair(8, 6));
  1062. ifib.insert(make_pair(2, 3));
  1063. ifib.insert(make_pair(1, 1));
  1064. ifib.insert(make_pair(3, 4));
  1065. ifib.insert(make_pair(1, 2));
  1066. ifib.insert(make_pair(5, 5));
  1067. EXPECT_THAT(ifib,
  1068. WhenSorted(ElementsAre(Pair(1, 1), Pair(1, 2), Pair(2, 3),
  1069. Pair(3, 4), Pair(5, 5), Pair(8, 6))));
  1070. EXPECT_THAT(ifib,
  1071. Not(WhenSorted(ElementsAre(Pair(8, 6), Pair(2, 3), Pair(1, 1),
  1072. Pair(3, 4), Pair(1, 2), Pair(5, 5)))));
  1073. }
  1074. TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
  1075. std::deque<int> d;
  1076. d.push_back(2);
  1077. d.push_back(1);
  1078. EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
  1079. EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
  1080. }
  1081. TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
  1082. std::deque<int> d;
  1083. d.push_back(2);
  1084. d.push_back(1);
  1085. Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
  1086. EXPECT_THAT(d, WhenSorted(vector_match));
  1087. Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
  1088. EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
  1089. }
  1090. // Deliberately bare pseudo-container.
  1091. // Offers only begin() and end() accessors, yielding InputIterator.
  1092. template <typename T>
  1093. class Streamlike {
  1094. private:
  1095. class ConstIter;
  1096. public:
  1097. typedef ConstIter const_iterator;
  1098. typedef T value_type;
  1099. template <typename InIter>
  1100. Streamlike(InIter first, InIter last) : remainder_(first, last) {}
  1101. const_iterator begin() const {
  1102. return const_iterator(this, remainder_.begin());
  1103. }
  1104. const_iterator end() const { return const_iterator(this, remainder_.end()); }
  1105. private:
  1106. class ConstIter {
  1107. public:
  1108. using iterator_category = std::input_iterator_tag;
  1109. using value_type = T;
  1110. using difference_type = ptrdiff_t;
  1111. using pointer = const value_type*;
  1112. using reference = const value_type&;
  1113. ConstIter(const Streamlike* s, typename std::list<value_type>::iterator pos)
  1114. : s_(s), pos_(pos) {}
  1115. const value_type& operator*() const { return *pos_; }
  1116. const value_type* operator->() const { return &*pos_; }
  1117. ConstIter& operator++() {
  1118. s_->remainder_.erase(pos_++);
  1119. return *this;
  1120. }
  1121. // *iter++ is required to work (see std::istreambuf_iterator).
  1122. // (void)iter++ is also required to work.
  1123. class PostIncrProxy {
  1124. public:
  1125. explicit PostIncrProxy(const value_type& value) : value_(value) {}
  1126. value_type operator*() const { return value_; }
  1127. private:
  1128. value_type value_;
  1129. };
  1130. PostIncrProxy operator++(int) {
  1131. PostIncrProxy proxy(**this);
  1132. ++(*this);
  1133. return proxy;
  1134. }
  1135. friend bool operator==(const ConstIter& a, const ConstIter& b) {
  1136. return a.s_ == b.s_ && a.pos_ == b.pos_;
  1137. }
  1138. friend bool operator!=(const ConstIter& a, const ConstIter& b) {
  1139. return !(a == b);
  1140. }
  1141. private:
  1142. const Streamlike* s_;
  1143. typename std::list<value_type>::iterator pos_;
  1144. };
  1145. friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
  1146. os << "[";
  1147. typedef typename std::list<value_type>::const_iterator Iter;
  1148. const char* sep = "";
  1149. for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
  1150. os << sep << *it;
  1151. sep = ",";
  1152. }
  1153. os << "]";
  1154. return os;
  1155. }
  1156. mutable std::list<value_type> remainder_; // modified by iteration
  1157. };
  1158. TEST(StreamlikeTest, Iteration) {
  1159. const int a[5] = {2, 1, 4, 5, 3};
  1160. Streamlike<int> s(a, a + 5);
  1161. Streamlike<int>::const_iterator it = s.begin();
  1162. const int* ip = a;
  1163. while (it != s.end()) {
  1164. SCOPED_TRACE(ip - a);
  1165. EXPECT_EQ(*ip++, *it++);
  1166. }
  1167. }
  1168. INSTANTIATE_GTEST_MATCHER_TEST_P(BeginEndDistanceIsTest);
  1169. TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
  1170. std::forward_list<int> container;
  1171. EXPECT_THAT(container, BeginEndDistanceIs(0));
  1172. EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
  1173. container.push_front(0);
  1174. EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
  1175. EXPECT_THAT(container, BeginEndDistanceIs(1));
  1176. container.push_front(0);
  1177. EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
  1178. EXPECT_THAT(container, BeginEndDistanceIs(2));
  1179. }
  1180. TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
  1181. const int a[5] = {1, 2, 3, 4, 5};
  1182. Streamlike<int> s(a, a + 5);
  1183. EXPECT_THAT(s, BeginEndDistanceIs(5));
  1184. }
  1185. TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
  1186. Matcher<vector<int>> m = BeginEndDistanceIs(2);
  1187. EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
  1188. EXPECT_EQ("distance between begin() and end() isn't equal to 2",
  1189. DescribeNegation(m));
  1190. }
  1191. TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
  1192. ContainerHelper helper;
  1193. EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
  1194. helper.Call(MakeUniquePtrs({1, 2}));
  1195. }
  1196. TEST_P(BeginEndDistanceIsTestP, ExplainsResult) {
  1197. Matcher<vector<int>> m1 = BeginEndDistanceIs(2);
  1198. Matcher<vector<int>> m2 = BeginEndDistanceIs(Lt(2));
  1199. Matcher<vector<int>> m3 = BeginEndDistanceIs(AnyOf(0, 3));
  1200. Matcher<vector<int>> m4 = BeginEndDistanceIs(GreaterThan(1));
  1201. vector<int> container;
  1202. EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
  1203. Explain(m1, container));
  1204. EXPECT_EQ("whose distance between begin() and end() 0 matches",
  1205. Explain(m2, container));
  1206. EXPECT_EQ("whose distance between begin() and end() 0 matches",
  1207. Explain(m3, container));
  1208. EXPECT_EQ(
  1209. "whose distance between begin() and end() 0 doesn't match, which is 1 "
  1210. "less than 1",
  1211. Explain(m4, container));
  1212. container.push_back(0);
  1213. container.push_back(0);
  1214. EXPECT_EQ("whose distance between begin() and end() 2 matches",
  1215. Explain(m1, container));
  1216. EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
  1217. Explain(m2, container));
  1218. EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
  1219. Explain(m3, container));
  1220. EXPECT_EQ(
  1221. "whose distance between begin() and end() 2 matches, which is 1 more "
  1222. "than 1",
  1223. Explain(m4, container));
  1224. }
  1225. TEST(WhenSortedTest, WorksForStreamlike) {
  1226. // Streamlike 'container' provides only minimal iterator support.
  1227. // Its iterators are tagged with input_iterator_tag.
  1228. const int a[5] = {2, 1, 4, 5, 3};
  1229. Streamlike<int> s(std::begin(a), std::end(a));
  1230. EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
  1231. EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
  1232. }
  1233. TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
  1234. const int a[] = {2, 1, 4, 5, 3};
  1235. Streamlike<int> s(std::begin(a), std::end(a));
  1236. Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
  1237. EXPECT_THAT(s, WhenSorted(vector_match));
  1238. EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
  1239. }
  1240. TEST(IsSupersetOfTest, WorksForNativeArray) {
  1241. const int subset[] = {1, 4};
  1242. const int superset[] = {1, 2, 4};
  1243. const int disjoint[] = {1, 0, 3};
  1244. EXPECT_THAT(subset, IsSupersetOf(subset));
  1245. EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
  1246. EXPECT_THAT(superset, IsSupersetOf(subset));
  1247. EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
  1248. EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
  1249. }
  1250. TEST(IsSupersetOfTest, WorksWithDuplicates) {
  1251. const int not_enough[] = {1, 2};
  1252. const int enough[] = {1, 1, 2};
  1253. const int expected[] = {1, 1};
  1254. EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
  1255. EXPECT_THAT(enough, IsSupersetOf(expected));
  1256. }
  1257. TEST(IsSupersetOfTest, WorksForEmpty) {
  1258. vector<int> numbers;
  1259. vector<int> expected;
  1260. EXPECT_THAT(numbers, IsSupersetOf(expected));
  1261. expected.push_back(1);
  1262. EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
  1263. expected.clear();
  1264. numbers.push_back(1);
  1265. numbers.push_back(2);
  1266. EXPECT_THAT(numbers, IsSupersetOf(expected));
  1267. expected.push_back(1);
  1268. EXPECT_THAT(numbers, IsSupersetOf(expected));
  1269. expected.push_back(2);
  1270. EXPECT_THAT(numbers, IsSupersetOf(expected));
  1271. expected.push_back(3);
  1272. EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
  1273. }
  1274. TEST(IsSupersetOfTest, WorksForStreamlike) {
  1275. const int a[5] = {1, 2, 3, 4, 5};
  1276. Streamlike<int> s(std::begin(a), std::end(a));
  1277. vector<int> expected;
  1278. expected.push_back(1);
  1279. expected.push_back(2);
  1280. expected.push_back(5);
  1281. EXPECT_THAT(s, IsSupersetOf(expected));
  1282. expected.push_back(0);
  1283. EXPECT_THAT(s, Not(IsSupersetOf(expected)));
  1284. }
  1285. TEST(IsSupersetOfTest, TakesStlContainer) {
  1286. const int actual[] = {3, 1, 2};
  1287. ::std::list<int> expected;
  1288. expected.push_back(1);
  1289. expected.push_back(3);
  1290. EXPECT_THAT(actual, IsSupersetOf(expected));
  1291. expected.push_back(4);
  1292. EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
  1293. }
  1294. TEST(IsSupersetOfTest, Describe) {
  1295. typedef std::vector<int> IntVec;
  1296. IntVec expected;
  1297. expected.push_back(111);
  1298. expected.push_back(222);
  1299. expected.push_back(333);
  1300. EXPECT_THAT(
  1301. Describe<IntVec>(IsSupersetOf(expected)),
  1302. Eq("a surjection from elements to requirements exists such that:\n"
  1303. " - an element is equal to 111\n"
  1304. " - an element is equal to 222\n"
  1305. " - an element is equal to 333"));
  1306. }
  1307. TEST(IsSupersetOfTest, DescribeNegation) {
  1308. typedef std::vector<int> IntVec;
  1309. IntVec expected;
  1310. expected.push_back(111);
  1311. expected.push_back(222);
  1312. expected.push_back(333);
  1313. EXPECT_THAT(
  1314. DescribeNegation<IntVec>(IsSupersetOf(expected)),
  1315. Eq("no surjection from elements to requirements exists such that:\n"
  1316. " - an element is equal to 111\n"
  1317. " - an element is equal to 222\n"
  1318. " - an element is equal to 333"));
  1319. }
  1320. TEST(IsSupersetOfTest, MatchAndExplain) {
  1321. std::vector<int> v;
  1322. v.push_back(2);
  1323. v.push_back(3);
  1324. std::vector<int> expected;
  1325. expected.push_back(1);
  1326. expected.push_back(2);
  1327. StringMatchResultListener listener;
  1328. ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
  1329. << listener.str();
  1330. EXPECT_THAT(listener.str(),
  1331. Eq("where the following matchers don't match any elements:\n"
  1332. "matcher #0: is equal to 1"));
  1333. v.push_back(1);
  1334. listener.Clear();
  1335. ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
  1336. << listener.str();
  1337. EXPECT_THAT(listener.str(), Eq("where:\n"
  1338. " - element #0 is matched by matcher #1,\n"
  1339. " - element #2 is matched by matcher #0"));
  1340. }
  1341. TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
  1342. const int numbers[] = {1, 3, 6, 2, 4, 5};
  1343. EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
  1344. EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
  1345. }
  1346. TEST(IsSupersetOfTest, WorksWithMoveOnly) {
  1347. ContainerHelper helper;
  1348. EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
  1349. helper.Call(MakeUniquePtrs({1, 2}));
  1350. EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
  1351. helper.Call(MakeUniquePtrs({2}));
  1352. }
  1353. TEST(IsSubsetOfTest, WorksForNativeArray) {
  1354. const int subset[] = {1, 4};
  1355. const int superset[] = {1, 2, 4};
  1356. const int disjoint[] = {1, 0, 3};
  1357. EXPECT_THAT(subset, IsSubsetOf(subset));
  1358. EXPECT_THAT(subset, IsSubsetOf(superset));
  1359. EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
  1360. EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
  1361. EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
  1362. }
  1363. TEST(IsSubsetOfTest, WorksWithDuplicates) {
  1364. const int not_enough[] = {1, 2};
  1365. const int enough[] = {1, 1, 2};
  1366. const int actual[] = {1, 1};
  1367. EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
  1368. EXPECT_THAT(actual, IsSubsetOf(enough));
  1369. }
  1370. TEST(IsSubsetOfTest, WorksForEmpty) {
  1371. vector<int> numbers;
  1372. vector<int> expected;
  1373. EXPECT_THAT(numbers, IsSubsetOf(expected));
  1374. expected.push_back(1);
  1375. EXPECT_THAT(numbers, IsSubsetOf(expected));
  1376. expected.clear();
  1377. numbers.push_back(1);
  1378. numbers.push_back(2);
  1379. EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
  1380. expected.push_back(1);
  1381. EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
  1382. expected.push_back(2);
  1383. EXPECT_THAT(numbers, IsSubsetOf(expected));
  1384. expected.push_back(3);
  1385. EXPECT_THAT(numbers, IsSubsetOf(expected));
  1386. }
  1387. TEST(IsSubsetOfTest, WorksForStreamlike) {
  1388. const int a[5] = {1, 2};
  1389. Streamlike<int> s(std::begin(a), std::end(a));
  1390. vector<int> expected;
  1391. expected.push_back(1);
  1392. EXPECT_THAT(s, Not(IsSubsetOf(expected)));
  1393. expected.push_back(2);
  1394. expected.push_back(5);
  1395. EXPECT_THAT(s, IsSubsetOf(expected));
  1396. }
  1397. TEST(IsSubsetOfTest, TakesStlContainer) {
  1398. const int actual[] = {3, 1, 2};
  1399. ::std::list<int> expected;
  1400. expected.push_back(1);
  1401. expected.push_back(3);
  1402. EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
  1403. expected.push_back(2);
  1404. expected.push_back(4);
  1405. EXPECT_THAT(actual, IsSubsetOf(expected));
  1406. }
  1407. TEST(IsSubsetOfTest, Describe) {
  1408. typedef std::vector<int> IntVec;
  1409. IntVec expected;
  1410. expected.push_back(111);
  1411. expected.push_back(222);
  1412. expected.push_back(333);
  1413. EXPECT_THAT(
  1414. Describe<IntVec>(IsSubsetOf(expected)),
  1415. Eq("an injection from elements to requirements exists such that:\n"
  1416. " - an element is equal to 111\n"
  1417. " - an element is equal to 222\n"
  1418. " - an element is equal to 333"));
  1419. }
  1420. TEST(IsSubsetOfTest, DescribeNegation) {
  1421. typedef std::vector<int> IntVec;
  1422. IntVec expected;
  1423. expected.push_back(111);
  1424. expected.push_back(222);
  1425. expected.push_back(333);
  1426. EXPECT_THAT(
  1427. DescribeNegation<IntVec>(IsSubsetOf(expected)),
  1428. Eq("no injection from elements to requirements exists such that:\n"
  1429. " - an element is equal to 111\n"
  1430. " - an element is equal to 222\n"
  1431. " - an element is equal to 333"));
  1432. }
  1433. TEST(IsSubsetOfTest, MatchAndExplain) {
  1434. std::vector<int> v;
  1435. v.push_back(2);
  1436. v.push_back(3);
  1437. std::vector<int> expected;
  1438. expected.push_back(1);
  1439. expected.push_back(2);
  1440. StringMatchResultListener listener;
  1441. ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
  1442. << listener.str();
  1443. EXPECT_THAT(listener.str(),
  1444. Eq("where the following elements don't match any matchers:\n"
  1445. "element #1: 3"));
  1446. expected.push_back(3);
  1447. listener.Clear();
  1448. ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
  1449. << listener.str();
  1450. EXPECT_THAT(listener.str(), Eq("where:\n"
  1451. " - element #0 is matched by matcher #1,\n"
  1452. " - element #1 is matched by matcher #2"));
  1453. }
  1454. TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
  1455. const int numbers[] = {1, 2, 3};
  1456. EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
  1457. EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
  1458. }
  1459. TEST(IsSubsetOfTest, WorksWithMoveOnly) {
  1460. ContainerHelper helper;
  1461. EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
  1462. helper.Call(MakeUniquePtrs({1}));
  1463. EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
  1464. helper.Call(MakeUniquePtrs({2}));
  1465. }
  1466. // Tests using ElementsAre() and ElementsAreArray() with stream-like
  1467. // "containers".
  1468. TEST(ElemensAreStreamTest, WorksForStreamlike) {
  1469. const int a[5] = {1, 2, 3, 4, 5};
  1470. Streamlike<int> s(std::begin(a), std::end(a));
  1471. EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
  1472. EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
  1473. }
  1474. TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
  1475. const int a[5] = {1, 2, 3, 4, 5};
  1476. Streamlike<int> s(std::begin(a), std::end(a));
  1477. vector<int> expected;
  1478. expected.push_back(1);
  1479. expected.push_back(2);
  1480. expected.push_back(3);
  1481. expected.push_back(4);
  1482. expected.push_back(5);
  1483. EXPECT_THAT(s, ElementsAreArray(expected));
  1484. expected[3] = 0;
  1485. EXPECT_THAT(s, Not(ElementsAreArray(expected)));
  1486. }
  1487. TEST(ElementsAreTest, WorksWithUncopyable) {
  1488. Uncopyable objs[2];
  1489. objs[0].set_value(-3);
  1490. objs[1].set_value(1);
  1491. EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
  1492. }
  1493. TEST(ElementsAreTest, WorksWithMoveOnly) {
  1494. ContainerHelper helper;
  1495. EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
  1496. helper.Call(MakeUniquePtrs({1, 2}));
  1497. EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
  1498. helper.Call(MakeUniquePtrs({3, 4}));
  1499. }
  1500. TEST(ElementsAreTest, TakesStlContainer) {
  1501. const int actual[] = {3, 1, 2};
  1502. ::std::list<int> expected;
  1503. expected.push_back(3);
  1504. expected.push_back(1);
  1505. expected.push_back(2);
  1506. EXPECT_THAT(actual, ElementsAreArray(expected));
  1507. expected.push_back(4);
  1508. EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
  1509. }
  1510. // Tests for UnorderedElementsAreArray()
  1511. TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
  1512. const int a[] = {0, 1, 2, 3, 4};
  1513. std::vector<int> s(std::begin(a), std::end(a));
  1514. do {
  1515. StringMatchResultListener listener;
  1516. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), s, &listener))
  1517. << listener.str();
  1518. } while (std::next_permutation(s.begin(), s.end()));
  1519. }
  1520. TEST(UnorderedElementsAreArrayTest, VectorBool) {
  1521. const bool a[] = {0, 1, 0, 1, 1};
  1522. const bool b[] = {1, 0, 1, 1, 0};
  1523. std::vector<bool> expected(std::begin(a), std::end(a));
  1524. std::vector<bool> actual(std::begin(b), std::end(b));
  1525. StringMatchResultListener listener;
  1526. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), actual,
  1527. &listener))
  1528. << listener.str();
  1529. }
  1530. TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
  1531. // Streamlike 'container' provides only minimal iterator support.
  1532. // Its iterators are tagged with input_iterator_tag, and it has no
  1533. // size() or empty() methods.
  1534. const int a[5] = {2, 1, 4, 5, 3};
  1535. Streamlike<int> s(std::begin(a), std::end(a));
  1536. ::std::vector<int> expected;
  1537. expected.push_back(1);
  1538. expected.push_back(2);
  1539. expected.push_back(3);
  1540. expected.push_back(4);
  1541. expected.push_back(5);
  1542. EXPECT_THAT(s, UnorderedElementsAreArray(expected));
  1543. expected.push_back(6);
  1544. EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
  1545. }
  1546. TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
  1547. const int actual[] = {3, 1, 2};
  1548. ::std::list<int> expected;
  1549. expected.push_back(1);
  1550. expected.push_back(2);
  1551. expected.push_back(3);
  1552. EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
  1553. expected.push_back(4);
  1554. EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
  1555. }
  1556. TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
  1557. const int a[5] = {2, 1, 4, 5, 3};
  1558. EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
  1559. EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
  1560. }
  1561. TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
  1562. const std::string a[5] = {"a", "b", "c", "d", "e"};
  1563. EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
  1564. EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
  1565. }
  1566. TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
  1567. const int a[5] = {2, 1, 4, 5, 3};
  1568. EXPECT_THAT(a,
  1569. UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
  1570. EXPECT_THAT(
  1571. a, Not(UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
  1572. }
  1573. TEST(UnorderedElementsAreArrayTest,
  1574. TakesInitializerListOfDifferentTypedMatchers) {
  1575. const int a[5] = {2, 1, 4, 5, 3};
  1576. // The compiler cannot infer the type of the initializer list if its
  1577. // elements have different types. We must explicitly specify the
  1578. // unified element type in this case.
  1579. EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int>>(
  1580. {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
  1581. EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int>>(
  1582. {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
  1583. }
  1584. TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
  1585. ContainerHelper helper;
  1586. EXPECT_CALL(helper,
  1587. Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
  1588. helper.Call(MakeUniquePtrs({2, 1}));
  1589. }
  1590. class UnorderedElementsAreTest : public testing::Test {
  1591. protected:
  1592. typedef std::vector<int> IntVec;
  1593. };
  1594. TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
  1595. Uncopyable objs[2];
  1596. objs[0].set_value(-3);
  1597. objs[1].set_value(1);
  1598. EXPECT_THAT(objs,
  1599. UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
  1600. }
  1601. TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
  1602. const int a[] = {1, 2, 3};
  1603. std::vector<int> s(std::begin(a), std::end(a));
  1604. do {
  1605. StringMatchResultListener listener;
  1606. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), s, &listener))
  1607. << listener.str();
  1608. } while (std::next_permutation(s.begin(), s.end()));
  1609. }
  1610. TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
  1611. const int a[] = {1, 2, 3};
  1612. std::vector<int> s(std::begin(a), std::end(a));
  1613. std::vector<Matcher<int>> mv;
  1614. mv.push_back(1);
  1615. mv.push_back(2);
  1616. mv.push_back(2);
  1617. // The element with value '3' matches nothing: fail fast.
  1618. StringMatchResultListener listener;
  1619. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
  1620. << listener.str();
  1621. }
  1622. TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
  1623. // Streamlike 'container' provides only minimal iterator support.
  1624. // Its iterators are tagged with input_iterator_tag, and it has no
  1625. // size() or empty() methods.
  1626. const int a[5] = {2, 1, 4, 5, 3};
  1627. Streamlike<int> s(std::begin(a), std::end(a));
  1628. EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
  1629. EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
  1630. }
  1631. TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
  1632. ContainerHelper helper;
  1633. EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
  1634. helper.Call(MakeUniquePtrs({2, 1}));
  1635. }
  1636. // One naive implementation of the matcher runs in O(N!) time, which is too
  1637. // slow for many real-world inputs. This test shows that our matcher can match
  1638. // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
  1639. // iterations and obviously effectively incomputable.
  1640. // [ RUN ] UnorderedElementsAreTest.Performance
  1641. // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
  1642. TEST_F(UnorderedElementsAreTest, Performance) {
  1643. std::vector<int> s;
  1644. std::vector<Matcher<int>> mv;
  1645. for (int i = 0; i < 100; ++i) {
  1646. s.push_back(i);
  1647. mv.push_back(_);
  1648. }
  1649. mv[50] = Eq(0);
  1650. StringMatchResultListener listener;
  1651. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
  1652. << listener.str();
  1653. }
  1654. // Another variant of 'Performance' with similar expectations.
  1655. // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
  1656. // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
  1657. TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
  1658. std::vector<int> s;
  1659. std::vector<Matcher<int>> mv;
  1660. for (int i = 0; i < 100; ++i) {
  1661. s.push_back(i);
  1662. if (i & 1) {
  1663. mv.push_back(_);
  1664. } else {
  1665. mv.push_back(i);
  1666. }
  1667. }
  1668. StringMatchResultListener listener;
  1669. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
  1670. << listener.str();
  1671. }
  1672. TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
  1673. std::vector<int> v;
  1674. v.push_back(4);
  1675. StringMatchResultListener listener;
  1676. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
  1677. << listener.str();
  1678. EXPECT_THAT(listener.str(), Eq("which has 1 element"));
  1679. }
  1680. TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
  1681. std::vector<int> v;
  1682. StringMatchResultListener listener;
  1683. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
  1684. << listener.str();
  1685. EXPECT_THAT(listener.str(), Eq(""));
  1686. }
  1687. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
  1688. std::vector<int> v;
  1689. v.push_back(1);
  1690. v.push_back(1);
  1691. StringMatchResultListener listener;
  1692. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))
  1693. << listener.str();
  1694. EXPECT_THAT(listener.str(),
  1695. Eq("where the following matchers don't match any elements:\n"
  1696. "matcher #1: is equal to 2"));
  1697. }
  1698. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
  1699. std::vector<int> v;
  1700. v.push_back(1);
  1701. v.push_back(2);
  1702. StringMatchResultListener listener;
  1703. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), v, &listener))
  1704. << listener.str();
  1705. EXPECT_THAT(listener.str(),
  1706. Eq("where the following elements don't match any matchers:\n"
  1707. "element #1: 2"));
  1708. }
  1709. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
  1710. std::vector<int> v;
  1711. v.push_back(2);
  1712. v.push_back(3);
  1713. StringMatchResultListener listener;
  1714. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))
  1715. << listener.str();
  1716. EXPECT_THAT(listener.str(),
  1717. Eq("where"
  1718. " the following matchers don't match any elements:\n"
  1719. "matcher #0: is equal to 1\n"
  1720. "and"
  1721. " where"
  1722. " the following elements don't match any matchers:\n"
  1723. "element #1: 3"));
  1724. }
  1725. // Test helper for formatting element, matcher index pairs in expectations.
  1726. static std::string EMString(int element, int matcher) {
  1727. stringstream ss;
  1728. ss << "(element #" << element << ", matcher #" << matcher << ")";
  1729. return ss.str();
  1730. }
  1731. TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
  1732. // A situation where all elements and matchers have a match
  1733. // associated with them, but the max matching is not perfect.
  1734. std::vector<std::string> v;
  1735. v.push_back("a");
  1736. v.push_back("b");
  1737. v.push_back("c");
  1738. StringMatchResultListener listener;
  1739. EXPECT_FALSE(ExplainMatchResult(
  1740. UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
  1741. << listener.str();
  1742. std::string prefix =
  1743. "where no permutation of the elements can satisfy all matchers, "
  1744. "and the closest match is 2 of 3 matchers with the "
  1745. "pairings:\n";
  1746. // We have to be a bit loose here, because there are 4 valid max matches.
  1747. EXPECT_THAT(
  1748. listener.str(),
  1749. AnyOf(
  1750. prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(1, 2) + "\n}",
  1751. prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(1, 2) + "\n}",
  1752. prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(2, 2) + "\n}",
  1753. prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(2, 2) +
  1754. "\n}"));
  1755. }
  1756. TEST_F(UnorderedElementsAreTest, Describe) {
  1757. EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), Eq("is empty"));
  1758. EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(345)),
  1759. Eq("has 1 element and that element is equal to 345"));
  1760. EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
  1761. Eq("has 3 elements and there exists some permutation "
  1762. "of elements such that:\n"
  1763. " - element #0 is equal to 111, and\n"
  1764. " - element #1 is equal to 222, and\n"
  1765. " - element #2 is equal to 333"));
  1766. }
  1767. TEST_F(UnorderedElementsAreTest, DescribeNegation) {
  1768. EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
  1769. Eq("isn't empty"));
  1770. EXPECT_THAT(
  1771. DescribeNegation<IntVec>(UnorderedElementsAre(345)),
  1772. Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
  1773. EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
  1774. Eq("doesn't have 3 elements, or there exists no permutation "
  1775. "of elements such that:\n"
  1776. " - element #0 is equal to 123, and\n"
  1777. " - element #1 is equal to 234, and\n"
  1778. " - element #2 is equal to 345"));
  1779. }
  1780. // Tests Each().
  1781. INSTANTIATE_GTEST_MATCHER_TEST_P(EachTest);
  1782. TEST_P(EachTestP, ExplainsMatchResultCorrectly) {
  1783. set<int> a; // empty
  1784. Matcher<set<int>> m = Each(2);
  1785. EXPECT_EQ("", Explain(m, a));
  1786. Matcher<const int(&)[1]> n = Each(1); // NOLINT
  1787. const int b[1] = {1};
  1788. EXPECT_EQ("", Explain(n, b));
  1789. n = Each(3);
  1790. EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
  1791. a.insert(1);
  1792. a.insert(2);
  1793. a.insert(3);
  1794. m = Each(GreaterThan(0));
  1795. EXPECT_EQ("", Explain(m, a));
  1796. m = Each(GreaterThan(10));
  1797. EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
  1798. Explain(m, a));
  1799. }
  1800. TEST(EachTest, DescribesItselfCorrectly) {
  1801. Matcher<vector<int>> m = Each(1);
  1802. EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
  1803. Matcher<vector<int>> m2 = Not(m);
  1804. EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
  1805. }
  1806. TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
  1807. vector<int> some_vector;
  1808. EXPECT_THAT(some_vector, Each(1));
  1809. some_vector.push_back(3);
  1810. EXPECT_THAT(some_vector, Not(Each(1)));
  1811. EXPECT_THAT(some_vector, Each(3));
  1812. some_vector.push_back(1);
  1813. some_vector.push_back(2);
  1814. EXPECT_THAT(some_vector, Not(Each(3)));
  1815. EXPECT_THAT(some_vector, Each(Lt(3.5)));
  1816. vector<std::string> another_vector;
  1817. another_vector.push_back("fee");
  1818. EXPECT_THAT(another_vector, Each(std::string("fee")));
  1819. another_vector.push_back("fie");
  1820. another_vector.push_back("foe");
  1821. another_vector.push_back("fum");
  1822. EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
  1823. }
  1824. TEST(EachTest, MatchesMapWhenAllElementsMatch) {
  1825. map<const char*, int> my_map;
  1826. const char* bar = "a string";
  1827. my_map[bar] = 2;
  1828. EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
  1829. map<std::string, int> another_map;
  1830. EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
  1831. another_map["fee"] = 1;
  1832. EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
  1833. another_map["fie"] = 2;
  1834. another_map["foe"] = 3;
  1835. another_map["fum"] = 4;
  1836. EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
  1837. EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
  1838. EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
  1839. }
  1840. TEST(EachTest, AcceptsMatcher) {
  1841. const int a[] = {1, 2, 3};
  1842. EXPECT_THAT(a, Each(Gt(0)));
  1843. EXPECT_THAT(a, Not(Each(Gt(1))));
  1844. }
  1845. TEST(EachTest, WorksForNativeArrayAsTuple) {
  1846. const int a[] = {1, 2};
  1847. const int* const pointer = a;
  1848. EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
  1849. EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
  1850. }
  1851. TEST(EachTest, WorksWithMoveOnly) {
  1852. ContainerHelper helper;
  1853. EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
  1854. helper.Call(MakeUniquePtrs({1, 2}));
  1855. }
  1856. // For testing Pointwise().
  1857. class IsHalfOfMatcher {
  1858. public:
  1859. template <typename T1, typename T2>
  1860. bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
  1861. MatchResultListener* listener) const {
  1862. if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
  1863. *listener << "where the second is " << std::get<1>(a_pair);
  1864. return true;
  1865. } else {
  1866. *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
  1867. return false;
  1868. }
  1869. }
  1870. void DescribeTo(ostream* os) const {
  1871. *os << "are a pair where the first is half of the second";
  1872. }
  1873. void DescribeNegationTo(ostream* os) const {
  1874. *os << "are a pair where the first isn't half of the second";
  1875. }
  1876. };
  1877. PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
  1878. return MakePolymorphicMatcher(IsHalfOfMatcher());
  1879. }
  1880. TEST(PointwiseTest, DescribesSelf) {
  1881. vector<int> rhs;
  1882. rhs.push_back(1);
  1883. rhs.push_back(2);
  1884. rhs.push_back(3);
  1885. const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
  1886. EXPECT_EQ(
  1887. "contains 3 values, where each value and its corresponding value "
  1888. "in { 1, 2, 3 } are a pair where the first is half of the second",
  1889. Describe(m));
  1890. EXPECT_EQ(
  1891. "doesn't contain exactly 3 values, or contains a value x at some "
  1892. "index i where x and the i-th value of { 1, 2, 3 } are a pair "
  1893. "where the first isn't half of the second",
  1894. DescribeNegation(m));
  1895. }
  1896. TEST(PointwiseTest, MakesCopyOfRhs) {
  1897. list<signed char> rhs;
  1898. rhs.push_back(2);
  1899. rhs.push_back(4);
  1900. int lhs[] = {1, 2};
  1901. const Matcher<const int(&)[2]> m = Pointwise(IsHalfOf(), rhs);
  1902. EXPECT_THAT(lhs, m);
  1903. // Changing rhs now shouldn't affect m, which made a copy of rhs.
  1904. rhs.push_back(6);
  1905. EXPECT_THAT(lhs, m);
  1906. }
  1907. TEST(PointwiseTest, WorksForLhsNativeArray) {
  1908. const int lhs[] = {1, 2, 3};
  1909. vector<int> rhs;
  1910. rhs.push_back(2);
  1911. rhs.push_back(4);
  1912. rhs.push_back(6);
  1913. EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
  1914. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
  1915. }
  1916. TEST(PointwiseTest, WorksForRhsNativeArray) {
  1917. const int rhs[] = {1, 2, 3};
  1918. vector<int> lhs;
  1919. lhs.push_back(2);
  1920. lhs.push_back(4);
  1921. lhs.push_back(6);
  1922. EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
  1923. EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
  1924. }
  1925. // Test is effective only with sanitizers.
  1926. TEST(PointwiseTest, WorksForVectorOfBool) {
  1927. vector<bool> rhs(3, false);
  1928. rhs[1] = true;
  1929. vector<bool> lhs = rhs;
  1930. EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
  1931. rhs[0] = true;
  1932. EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
  1933. }
  1934. TEST(PointwiseTest, WorksForRhsInitializerList) {
  1935. const vector<int> lhs{2, 4, 6};
  1936. EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
  1937. EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
  1938. }
  1939. TEST(PointwiseTest, RejectsWrongSize) {
  1940. const double lhs[2] = {1, 2};
  1941. const int rhs[1] = {0};
  1942. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
  1943. EXPECT_EQ("which contains 2 values", Explain(Pointwise(Gt(), rhs), lhs));
  1944. const int rhs2[3] = {0, 1, 2};
  1945. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
  1946. }
  1947. TEST(PointwiseTest, RejectsWrongContent) {
  1948. const double lhs[3] = {1, 2, 3};
  1949. const int rhs[3] = {2, 6, 4};
  1950. EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
  1951. EXPECT_EQ(
  1952. "where the value pair (2, 6) at index #1 don't match, "
  1953. "where the second/2 is 3",
  1954. Explain(Pointwise(IsHalfOf(), rhs), lhs));
  1955. }
  1956. TEST(PointwiseTest, AcceptsCorrectContent) {
  1957. const double lhs[3] = {1, 2, 3};
  1958. const int rhs[3] = {2, 4, 6};
  1959. EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
  1960. EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
  1961. }
  1962. TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
  1963. const double lhs[3] = {1, 2, 3};
  1964. const int rhs[3] = {2, 4, 6};
  1965. const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
  1966. EXPECT_THAT(lhs, Pointwise(m1, rhs));
  1967. EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
  1968. // This type works as a std::tuple<const double&, const int&> can be
  1969. // implicitly cast to std::tuple<double, int>.
  1970. const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
  1971. EXPECT_THAT(lhs, Pointwise(m2, rhs));
  1972. EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
  1973. }
  1974. MATCHER(PointeeEquals, "Points to an equal value") {
  1975. return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
  1976. ::testing::get<0>(arg), result_listener);
  1977. }
  1978. TEST(PointwiseTest, WorksWithMoveOnly) {
  1979. ContainerHelper helper;
  1980. EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
  1981. helper.Call(MakeUniquePtrs({1, 2}));
  1982. }
  1983. TEST(UnorderedPointwiseTest, DescribesSelf) {
  1984. vector<int> rhs;
  1985. rhs.push_back(1);
  1986. rhs.push_back(2);
  1987. rhs.push_back(3);
  1988. const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
  1989. EXPECT_EQ(
  1990. "has 3 elements and there exists some permutation of elements such "
  1991. "that:\n"
  1992. " - element #0 and 1 are a pair where the first is half of the second, "
  1993. "and\n"
  1994. " - element #1 and 2 are a pair where the first is half of the second, "
  1995. "and\n"
  1996. " - element #2 and 3 are a pair where the first is half of the second",
  1997. Describe(m));
  1998. EXPECT_EQ(
  1999. "doesn't have 3 elements, or there exists no permutation of elements "
  2000. "such that:\n"
  2001. " - element #0 and 1 are a pair where the first is half of the second, "
  2002. "and\n"
  2003. " - element #1 and 2 are a pair where the first is half of the second, "
  2004. "and\n"
  2005. " - element #2 and 3 are a pair where the first is half of the second",
  2006. DescribeNegation(m));
  2007. }
  2008. TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
  2009. list<signed char> rhs;
  2010. rhs.push_back(2);
  2011. rhs.push_back(4);
  2012. int lhs[] = {2, 1};
  2013. const Matcher<const int(&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
  2014. EXPECT_THAT(lhs, m);
  2015. // Changing rhs now shouldn't affect m, which made a copy of rhs.
  2016. rhs.push_back(6);
  2017. EXPECT_THAT(lhs, m);
  2018. }
  2019. TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
  2020. const int lhs[] = {1, 2, 3};
  2021. vector<int> rhs;
  2022. rhs.push_back(4);
  2023. rhs.push_back(6);
  2024. rhs.push_back(2);
  2025. EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
  2026. EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
  2027. }
  2028. TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
  2029. const int rhs[] = {1, 2, 3};
  2030. vector<int> lhs;
  2031. lhs.push_back(4);
  2032. lhs.push_back(2);
  2033. lhs.push_back(6);
  2034. EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
  2035. EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
  2036. }
  2037. TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
  2038. const vector<int> lhs{2, 4, 6};
  2039. EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
  2040. EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
  2041. }
  2042. TEST(UnorderedPointwiseTest, RejectsWrongSize) {
  2043. const double lhs[2] = {1, 2};
  2044. const int rhs[1] = {0};
  2045. EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
  2046. EXPECT_EQ("which has 2 elements",
  2047. Explain(UnorderedPointwise(Gt(), rhs), lhs));
  2048. const int rhs2[3] = {0, 1, 2};
  2049. EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
  2050. }
  2051. TEST(UnorderedPointwiseTest, RejectsWrongContent) {
  2052. const double lhs[3] = {1, 2, 3};
  2053. const int rhs[3] = {2, 6, 6};
  2054. EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
  2055. EXPECT_EQ(
  2056. "where the following elements don't match any matchers:\n"
  2057. "element #1: 2",
  2058. Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
  2059. }
  2060. TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
  2061. const double lhs[3] = {1, 2, 3};
  2062. const int rhs[3] = {2, 4, 6};
  2063. EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
  2064. }
  2065. TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
  2066. const double lhs[3] = {1, 2, 3};
  2067. const int rhs[3] = {6, 4, 2};
  2068. EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
  2069. }
  2070. TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
  2071. const double lhs[3] = {1, 2, 3};
  2072. const int rhs[3] = {4, 6, 2};
  2073. const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
  2074. EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
  2075. // This type works as a std::tuple<const double&, const int&> can be
  2076. // implicitly cast to std::tuple<double, int>.
  2077. const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
  2078. EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
  2079. }
  2080. TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
  2081. ContainerHelper helper;
  2082. EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
  2083. std::vector<int>{1, 2})));
  2084. helper.Call(MakeUniquePtrs({2, 1}));
  2085. }
  2086. TEST(PointeeTest, WorksOnMoveOnlyType) {
  2087. std::unique_ptr<int> p(new int(3));
  2088. EXPECT_THAT(p, Pointee(Eq(3)));
  2089. EXPECT_THAT(p, Not(Pointee(Eq(2))));
  2090. }
  2091. class PredicateFormatterFromMatcherTest : public ::testing::Test {
  2092. protected:
  2093. enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
  2094. // A matcher that can return different results when used multiple times on the
  2095. // same input. No real matcher should do this; but this lets us test that we
  2096. // detect such behavior and fail appropriately.
  2097. class MockMatcher : public MatcherInterface<Behavior> {
  2098. public:
  2099. bool MatchAndExplain(Behavior behavior,
  2100. MatchResultListener* listener) const override {
  2101. *listener << "[MatchAndExplain]";
  2102. switch (behavior) {
  2103. case kInitialSuccess:
  2104. // The first call to MatchAndExplain should use a "not interested"
  2105. // listener; so this is expected to return |true|. There should be no
  2106. // subsequent calls.
  2107. return !listener->IsInterested();
  2108. case kAlwaysFail:
  2109. return false;
  2110. case kFlaky:
  2111. // The first call to MatchAndExplain should use a "not interested"
  2112. // listener; so this will return |false|. Subsequent calls should have
  2113. // an "interested" listener; so this will return |true|, thus
  2114. // simulating a flaky matcher.
  2115. return listener->IsInterested();
  2116. }
  2117. GTEST_LOG_(FATAL) << "This should never be reached";
  2118. return false;
  2119. }
  2120. void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
  2121. void DescribeNegationTo(ostream* os) const override {
  2122. *os << "[DescribeNegationTo]";
  2123. }
  2124. };
  2125. AssertionResult RunPredicateFormatter(Behavior behavior) {
  2126. auto matcher = MakeMatcher(new MockMatcher);
  2127. PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
  2128. matcher);
  2129. return predicate_formatter("dummy-name", behavior);
  2130. }
  2131. };
  2132. TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
  2133. AssertionResult result = RunPredicateFormatter(kInitialSuccess);
  2134. EXPECT_TRUE(result); // Implicit cast to bool.
  2135. std::string expect;
  2136. EXPECT_EQ(expect, result.message());
  2137. }
  2138. TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
  2139. AssertionResult result = RunPredicateFormatter(kAlwaysFail);
  2140. EXPECT_FALSE(result); // Implicit cast to bool.
  2141. std::string expect =
  2142. "Value of: dummy-name\nExpected: [DescribeTo]\n"
  2143. " Actual: 1" +
  2144. OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
  2145. EXPECT_EQ(expect, result.message());
  2146. }
  2147. TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
  2148. AssertionResult result = RunPredicateFormatter(kFlaky);
  2149. EXPECT_FALSE(result); // Implicit cast to bool.
  2150. std::string expect =
  2151. "Value of: dummy-name\nExpected: [DescribeTo]\n"
  2152. " The matcher failed on the initial attempt; but passed when rerun to "
  2153. "generate the explanation.\n"
  2154. " Actual: 2" +
  2155. OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
  2156. EXPECT_EQ(expect, result.message());
  2157. }
  2158. // Tests for ElementsAre().
  2159. TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
  2160. Matcher<const vector<int>&> m = ElementsAre();
  2161. EXPECT_EQ("is empty", Describe(m));
  2162. }
  2163. TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
  2164. Matcher<vector<int>> m = ElementsAre(Gt(5));
  2165. EXPECT_EQ("has 1 element that is > 5", Describe(m));
  2166. }
  2167. TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
  2168. Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
  2169. EXPECT_EQ(
  2170. "has 2 elements where\n"
  2171. "element #0 is equal to \"one\",\n"
  2172. "element #1 is equal to \"two\"",
  2173. Describe(m));
  2174. }
  2175. TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
  2176. Matcher<vector<int>> m = ElementsAre();
  2177. EXPECT_EQ("isn't empty", DescribeNegation(m));
  2178. }
  2179. TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElement) {
  2180. Matcher<const list<int>&> m = ElementsAre(Gt(5));
  2181. EXPECT_EQ(
  2182. "doesn't have 1 element, or\n"
  2183. "element #0 isn't > 5",
  2184. DescribeNegation(m));
  2185. }
  2186. TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
  2187. Matcher<const list<std::string>&> m = ElementsAre("one", "two");
  2188. EXPECT_EQ(
  2189. "doesn't have 2 elements, or\n"
  2190. "element #0 isn't equal to \"one\", or\n"
  2191. "element #1 isn't equal to \"two\"",
  2192. DescribeNegation(m));
  2193. }
  2194. TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
  2195. Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
  2196. list<int> test_list;
  2197. test_list.push_back(1);
  2198. test_list.push_back(3);
  2199. EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything.
  2200. }
  2201. TEST_P(ElementsAreTestP, ExplainsNonTrivialMatch) {
  2202. Matcher<const vector<int>&> m =
  2203. ElementsAre(GreaterThan(1), 0, GreaterThan(2));
  2204. const int a[] = {10, 0, 100};
  2205. vector<int> test_vector(std::begin(a), std::end(a));
  2206. EXPECT_EQ(
  2207. "whose element #0 matches, which is 9 more than 1,\n"
  2208. "and whose element #2 matches, which is 98 more than 2",
  2209. Explain(m, test_vector));
  2210. }
  2211. TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
  2212. Matcher<const list<int>&> m = ElementsAre(1, 3);
  2213. list<int> test_list;
  2214. // No need to explain when the container is empty.
  2215. EXPECT_EQ("", Explain(m, test_list));
  2216. test_list.push_back(1);
  2217. EXPECT_EQ("which has 1 element", Explain(m, test_list));
  2218. }
  2219. TEST_P(ElementsAreTestP, CanExplainMismatchRightSize) {
  2220. Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
  2221. vector<int> v;
  2222. v.push_back(2);
  2223. v.push_back(1);
  2224. EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
  2225. v[0] = 1;
  2226. EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
  2227. Explain(m, v));
  2228. }
  2229. TEST(ElementsAreTest, MatchesOneElementVector) {
  2230. vector<std::string> test_vector;
  2231. test_vector.push_back("test string");
  2232. EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
  2233. }
  2234. TEST(ElementsAreTest, MatchesOneElementList) {
  2235. list<std::string> test_list;
  2236. test_list.push_back("test string");
  2237. EXPECT_THAT(test_list, ElementsAre("test string"));
  2238. }
  2239. TEST(ElementsAreTest, MatchesThreeElementVector) {
  2240. vector<std::string> test_vector;
  2241. test_vector.push_back("one");
  2242. test_vector.push_back("two");
  2243. test_vector.push_back("three");
  2244. EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
  2245. }
  2246. TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
  2247. vector<int> test_vector;
  2248. test_vector.push_back(4);
  2249. EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
  2250. }
  2251. TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
  2252. vector<int> test_vector;
  2253. test_vector.push_back(4);
  2254. EXPECT_THAT(test_vector, ElementsAre(_));
  2255. }
  2256. TEST(ElementsAreTest, MatchesOneElementValue) {
  2257. vector<int> test_vector;
  2258. test_vector.push_back(4);
  2259. EXPECT_THAT(test_vector, ElementsAre(4));
  2260. }
  2261. TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
  2262. vector<int> test_vector;
  2263. test_vector.push_back(1);
  2264. test_vector.push_back(2);
  2265. test_vector.push_back(3);
  2266. EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
  2267. }
  2268. TEST(ElementsAreTest, MatchesTenElementVector) {
  2269. const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  2270. vector<int> test_vector(std::begin(a), std::end(a));
  2271. EXPECT_THAT(test_vector,
  2272. // The element list can contain values and/or matchers
  2273. // of different types.
  2274. ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
  2275. }
  2276. TEST(ElementsAreTest, DoesNotMatchWrongSize) {
  2277. vector<std::string> test_vector;
  2278. test_vector.push_back("test string");
  2279. test_vector.push_back("test string");
  2280. Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
  2281. EXPECT_FALSE(m.Matches(test_vector));
  2282. }
  2283. TEST(ElementsAreTest, DoesNotMatchWrongValue) {
  2284. vector<std::string> test_vector;
  2285. test_vector.push_back("other string");
  2286. Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
  2287. EXPECT_FALSE(m.Matches(test_vector));
  2288. }
  2289. TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
  2290. vector<std::string> test_vector;
  2291. test_vector.push_back("one");
  2292. test_vector.push_back("three");
  2293. test_vector.push_back("two");
  2294. Matcher<vector<std::string>> m =
  2295. ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
  2296. EXPECT_FALSE(m.Matches(test_vector));
  2297. }
  2298. TEST(ElementsAreTest, WorksForNestedContainer) {
  2299. constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
  2300. vector<list<char>> nested;
  2301. for (const auto& s : strings) {
  2302. nested.emplace_back(s, s + strlen(s));
  2303. }
  2304. EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
  2305. ElementsAre('w', 'o', _, _, 'd')));
  2306. EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
  2307. ElementsAre('w', 'o', _, _, 'd'))));
  2308. }
  2309. TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
  2310. int a[] = {0, 1, 2};
  2311. vector<int> v(std::begin(a), std::end(a));
  2312. EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
  2313. EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
  2314. }
  2315. TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
  2316. int a[] = {0, 1, 2};
  2317. vector<int> v(std::begin(a), std::end(a));
  2318. EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
  2319. EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
  2320. }
  2321. TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
  2322. int array[] = {0, 1, 2};
  2323. EXPECT_THAT(array, ElementsAre(0, 1, _));
  2324. EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
  2325. EXPECT_THAT(array, Not(ElementsAre(0, _)));
  2326. }
  2327. class NativeArrayPassedAsPointerAndSize {
  2328. public:
  2329. NativeArrayPassedAsPointerAndSize() {}
  2330. MOCK_METHOD(void, Helper, (int* array, int size));
  2331. private:
  2332. NativeArrayPassedAsPointerAndSize(const NativeArrayPassedAsPointerAndSize&) =
  2333. delete;
  2334. NativeArrayPassedAsPointerAndSize& operator=(
  2335. const NativeArrayPassedAsPointerAndSize&) = delete;
  2336. };
  2337. TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
  2338. int array[] = {0, 1};
  2339. ::std::tuple<int*, size_t> array_as_tuple(array, 2);
  2340. EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
  2341. EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
  2342. NativeArrayPassedAsPointerAndSize helper;
  2343. EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
  2344. helper.Helper(array, 2);
  2345. }
  2346. TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
  2347. const char a2[][3] = {"hi", "lo"};
  2348. EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
  2349. ElementsAre('l', 'o', '\0')));
  2350. EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
  2351. EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
  2352. ElementsAre('l', 'o', '\0')));
  2353. }
  2354. TEST(ElementsAreTest, AcceptsStringLiteral) {
  2355. std::string array[] = {"hi", "one", "two"};
  2356. EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
  2357. EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
  2358. }
  2359. // Declared here with the size unknown. Defined AFTER the following test.
  2360. extern const char kHi[];
  2361. TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
  2362. // The size of kHi is not known in this test, but ElementsAre() should
  2363. // still accept it.
  2364. std::string array1[] = {"hi"};
  2365. EXPECT_THAT(array1, ElementsAre(kHi));
  2366. std::string array2[] = {"ho"};
  2367. EXPECT_THAT(array2, Not(ElementsAre(kHi)));
  2368. }
  2369. const char kHi[] = "hi";
  2370. TEST(ElementsAreTest, MakesCopyOfArguments) {
  2371. int x = 1;
  2372. int y = 2;
  2373. // This should make a copy of x and y.
  2374. ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
  2375. polymorphic_matcher = ElementsAre(x, y);
  2376. // Changing x and y now shouldn't affect the meaning of the above matcher.
  2377. x = y = 0;
  2378. const int array1[] = {1, 2};
  2379. EXPECT_THAT(array1, polymorphic_matcher);
  2380. const int array2[] = {0, 0};
  2381. EXPECT_THAT(array2, Not(polymorphic_matcher));
  2382. }
  2383. // Tests for ElementsAreArray(). Since ElementsAreArray() shares most
  2384. // of the implementation with ElementsAre(), we don't test it as
  2385. // thoroughly here.
  2386. TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
  2387. const int a[] = {1, 2, 3};
  2388. vector<int> test_vector(std::begin(a), std::end(a));
  2389. EXPECT_THAT(test_vector, ElementsAreArray(a));
  2390. test_vector[2] = 0;
  2391. EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
  2392. }
  2393. TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
  2394. std::array<const char*, 3> a = {{"one", "two", "three"}};
  2395. vector<std::string> test_vector(std::begin(a), std::end(a));
  2396. EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
  2397. const char** p = a.data();
  2398. test_vector[0] = "1";
  2399. EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
  2400. }
  2401. TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
  2402. const char* a[] = {"one", "two", "three"};
  2403. vector<std::string> test_vector(std::begin(a), std::end(a));
  2404. EXPECT_THAT(test_vector, ElementsAreArray(a));
  2405. test_vector[0] = "1";
  2406. EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
  2407. }
  2408. TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
  2409. const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
  2410. StrEq("three")};
  2411. vector<std::string> test_vector;
  2412. test_vector.push_back("one");
  2413. test_vector.push_back("two");
  2414. test_vector.push_back("three");
  2415. EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
  2416. test_vector.push_back("three");
  2417. EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
  2418. }
  2419. TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
  2420. const int a[] = {1, 2, 3};
  2421. vector<int> test_vector(std::begin(a), std::end(a));
  2422. const vector<int> expected(std::begin(a), std::end(a));
  2423. EXPECT_THAT(test_vector, ElementsAreArray(expected));
  2424. test_vector.push_back(4);
  2425. EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
  2426. }
  2427. TEST(ElementsAreArrayTest, TakesInitializerList) {
  2428. const int a[5] = {1, 2, 3, 4, 5};
  2429. EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
  2430. EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
  2431. EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
  2432. }
  2433. TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
  2434. const std::string a[5] = {"a", "b", "c", "d", "e"};
  2435. EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
  2436. EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
  2437. EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
  2438. }
  2439. TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
  2440. const int a[5] = {1, 2, 3, 4, 5};
  2441. EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
  2442. EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
  2443. }
  2444. TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
  2445. const int a[5] = {1, 2, 3, 4, 5};
  2446. // The compiler cannot infer the type of the initializer list if its
  2447. // elements have different types. We must explicitly specify the
  2448. // unified element type in this case.
  2449. EXPECT_THAT(
  2450. a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
  2451. EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
  2452. {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
  2453. }
  2454. TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
  2455. const int a[] = {1, 2, 3};
  2456. const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
  2457. vector<int> test_vector(std::begin(a), std::end(a));
  2458. const vector<Matcher<int>> expected(std::begin(kMatchers),
  2459. std::end(kMatchers));
  2460. EXPECT_THAT(test_vector, ElementsAreArray(expected));
  2461. test_vector.push_back(4);
  2462. EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
  2463. }
  2464. TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
  2465. const int a[] = {1, 2, 3};
  2466. const vector<int> test_vector(std::begin(a), std::end(a));
  2467. const vector<int> expected(std::begin(a), std::end(a));
  2468. EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
  2469. // Pointers are iterators, too.
  2470. EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
  2471. // The empty range of NULL pointers should also be okay.
  2472. int* const null_int = nullptr;
  2473. EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
  2474. EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
  2475. }
  2476. // Since ElementsAre() and ElementsAreArray() share much of the
  2477. // implementation, we only do a test for native arrays here.
  2478. TEST(ElementsAreArrayTest, WorksWithNativeArray) {
  2479. ::std::string a[] = {"hi", "ho"};
  2480. ::std::string b[] = {"hi", "ho"};
  2481. EXPECT_THAT(a, ElementsAreArray(b));
  2482. EXPECT_THAT(a, ElementsAreArray(b, 2));
  2483. EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
  2484. }
  2485. TEST(ElementsAreArrayTest, SourceLifeSpan) {
  2486. const int a[] = {1, 2, 3};
  2487. vector<int> test_vector(std::begin(a), std::end(a));
  2488. vector<int> expect(std::begin(a), std::end(a));
  2489. ElementsAreArrayMatcher<int> matcher_maker =
  2490. ElementsAreArray(expect.begin(), expect.end());
  2491. EXPECT_THAT(test_vector, matcher_maker);
  2492. // Changing in place the values that initialized matcher_maker should not
  2493. // affect matcher_maker anymore. It should have made its own copy of them.
  2494. for (int& i : expect) {
  2495. i += 10;
  2496. }
  2497. EXPECT_THAT(test_vector, matcher_maker);
  2498. test_vector.push_back(3);
  2499. EXPECT_THAT(test_vector, Not(matcher_maker));
  2500. }
  2501. // Tests Contains().
  2502. INSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTest);
  2503. TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
  2504. list<int> some_list;
  2505. some_list.push_back(3);
  2506. some_list.push_back(1);
  2507. some_list.push_back(2);
  2508. some_list.push_back(3);
  2509. EXPECT_THAT(some_list, Contains(1));
  2510. EXPECT_THAT(some_list, Contains(Gt(2.5)));
  2511. EXPECT_THAT(some_list, Contains(Eq(2.0f)));
  2512. list<std::string> another_list;
  2513. another_list.push_back("fee");
  2514. another_list.push_back("fie");
  2515. another_list.push_back("foe");
  2516. another_list.push_back("fum");
  2517. EXPECT_THAT(another_list, Contains(std::string("fee")));
  2518. }
  2519. TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
  2520. list<int> some_list;
  2521. some_list.push_back(3);
  2522. some_list.push_back(1);
  2523. EXPECT_THAT(some_list, Not(Contains(4)));
  2524. }
  2525. TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
  2526. set<int> some_set;
  2527. some_set.insert(3);
  2528. some_set.insert(1);
  2529. some_set.insert(2);
  2530. EXPECT_THAT(some_set, Contains(Eq(1.0)));
  2531. EXPECT_THAT(some_set, Contains(Eq(3.0f)));
  2532. EXPECT_THAT(some_set, Contains(2));
  2533. set<std::string> another_set;
  2534. another_set.insert("fee");
  2535. another_set.insert("fie");
  2536. another_set.insert("foe");
  2537. another_set.insert("fum");
  2538. EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
  2539. }
  2540. TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
  2541. set<int> some_set;
  2542. some_set.insert(3);
  2543. some_set.insert(1);
  2544. EXPECT_THAT(some_set, Not(Contains(4)));
  2545. set<std::string> c_string_set;
  2546. c_string_set.insert("hello");
  2547. EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
  2548. }
  2549. TEST_P(ContainsTestP, ExplainsMatchResultCorrectly) {
  2550. const int a[2] = {1, 2};
  2551. Matcher<const int(&)[2]> m = Contains(2);
  2552. EXPECT_EQ("whose element #1 matches", Explain(m, a));
  2553. m = Contains(3);
  2554. EXPECT_EQ("", Explain(m, a));
  2555. m = Contains(GreaterThan(0));
  2556. EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
  2557. m = Contains(GreaterThan(10));
  2558. EXPECT_EQ("", Explain(m, a));
  2559. }
  2560. TEST(ContainsTest, DescribesItselfCorrectly) {
  2561. Matcher<vector<int>> m = Contains(1);
  2562. EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
  2563. Matcher<vector<int>> m2 = Not(m);
  2564. EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
  2565. }
  2566. TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
  2567. map<std::string, int> my_map;
  2568. const char* bar = "a string";
  2569. my_map[bar] = 2;
  2570. EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
  2571. map<std::string, int> another_map;
  2572. another_map["fee"] = 1;
  2573. another_map["fie"] = 2;
  2574. another_map["foe"] = 3;
  2575. another_map["fum"] = 4;
  2576. EXPECT_THAT(another_map,
  2577. Contains(pair<const std::string, int>(std::string("fee"), 1)));
  2578. EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
  2579. }
  2580. TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
  2581. map<int, int> some_map;
  2582. some_map[1] = 11;
  2583. some_map[2] = 22;
  2584. EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
  2585. }
  2586. TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
  2587. const char* string_array[] = {"fee", "fie", "foe", "fum"};
  2588. EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
  2589. }
  2590. TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
  2591. int int_array[] = {1, 2, 3, 4};
  2592. EXPECT_THAT(int_array, Not(Contains(5)));
  2593. }
  2594. TEST(ContainsTest, AcceptsMatcher) {
  2595. const int a[] = {1, 2, 3};
  2596. EXPECT_THAT(a, Contains(Gt(2)));
  2597. EXPECT_THAT(a, Not(Contains(Gt(4))));
  2598. }
  2599. TEST(ContainsTest, WorksForNativeArrayAsTuple) {
  2600. const int a[] = {1, 2};
  2601. const int* const pointer = a;
  2602. EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
  2603. EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
  2604. }
  2605. TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
  2606. int a[][3] = {{1, 2, 3}, {4, 5, 6}};
  2607. EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
  2608. EXPECT_THAT(a, Contains(Contains(5)));
  2609. EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
  2610. EXPECT_THAT(a, Contains(Not(Contains(5))));
  2611. }
  2612. } // namespace
  2613. } // namespace gmock_matchers_test
  2614. } // namespace testing
  2615. #ifdef _MSC_VER
  2616. #pragma warning(pop)
  2617. #endif