gmock-matchers-containers_test.cc 100 KB

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