gmock-matchers-containers_test.cc 109 KB

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