gmock-matchers_test.cc 178 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652
  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. //
  30. // Author: wan@google.com (Zhanyong Wan)
  31. // Google Mock - a framework for writing C++ mock classes.
  32. //
  33. // This file tests some commonly used argument matchers.
  34. #include "gmock/gmock-matchers.h"
  35. #include "gmock/gmock-more-matchers.h"
  36. #include <string.h>
  37. #include <time.h>
  38. #include <deque>
  39. #include <functional>
  40. #include <iostream>
  41. #include <iterator>
  42. #include <limits>
  43. #include <list>
  44. #include <map>
  45. #include <set>
  46. #include <sstream>
  47. #include <string>
  48. #include <utility>
  49. #include <vector>
  50. #include "gmock/gmock.h"
  51. #include "gtest/gtest.h"
  52. #include "gtest/gtest-spi.h"
  53. #if GTEST_HAS_STD_FORWARD_LIST_
  54. # include <forward_list> // NOLINT
  55. #endif
  56. namespace testing {
  57. namespace internal {
  58. GTEST_API_ string JoinAsTuple(const Strings& fields);
  59. } // namespace internal
  60. namespace gmock_matchers_test {
  61. using std::greater;
  62. using std::less;
  63. using std::list;
  64. using std::make_pair;
  65. using std::map;
  66. using std::multimap;
  67. using std::multiset;
  68. using std::ostream;
  69. using std::pair;
  70. using std::set;
  71. using std::stringstream;
  72. using std::vector;
  73. using testing::A;
  74. using testing::AllArgs;
  75. using testing::AllOf;
  76. using testing::An;
  77. using testing::AnyOf;
  78. using testing::ByRef;
  79. using testing::ContainsRegex;
  80. using testing::DoubleEq;
  81. using testing::DoubleNear;
  82. using testing::EndsWith;
  83. using testing::Eq;
  84. using testing::ExplainMatchResult;
  85. using testing::Field;
  86. using testing::FloatEq;
  87. using testing::FloatNear;
  88. using testing::Ge;
  89. using testing::Gt;
  90. using testing::HasSubstr;
  91. using testing::IsEmpty;
  92. using testing::IsNull;
  93. using testing::Key;
  94. using testing::Le;
  95. using testing::Lt;
  96. using testing::MakeMatcher;
  97. using testing::MakePolymorphicMatcher;
  98. using testing::MatchResultListener;
  99. using testing::Matcher;
  100. using testing::MatcherCast;
  101. using testing::MatcherInterface;
  102. using testing::Matches;
  103. using testing::MatchesRegex;
  104. using testing::NanSensitiveDoubleEq;
  105. using testing::NanSensitiveDoubleNear;
  106. using testing::NanSensitiveFloatEq;
  107. using testing::NanSensitiveFloatNear;
  108. using testing::Ne;
  109. using testing::Not;
  110. using testing::NotNull;
  111. using testing::Pair;
  112. using testing::Pointee;
  113. using testing::Pointwise;
  114. using testing::PolymorphicMatcher;
  115. using testing::Property;
  116. using testing::Ref;
  117. using testing::ResultOf;
  118. using testing::SizeIs;
  119. using testing::StartsWith;
  120. using testing::StrCaseEq;
  121. using testing::StrCaseNe;
  122. using testing::StrEq;
  123. using testing::StrNe;
  124. using testing::StringMatchResultListener;
  125. using testing::Truly;
  126. using testing::TypedEq;
  127. using testing::UnorderedPointwise;
  128. using testing::Value;
  129. using testing::WhenSorted;
  130. using testing::WhenSortedBy;
  131. using testing::_;
  132. using testing::get;
  133. using testing::internal::DummyMatchResultListener;
  134. using testing::internal::ElementMatcherPair;
  135. using testing::internal::ElementMatcherPairs;
  136. using testing::internal::ExplainMatchFailureTupleTo;
  137. using testing::internal::FloatingEqMatcher;
  138. using testing::internal::FormatMatcherDescription;
  139. using testing::internal::IsReadableTypeName;
  140. using testing::internal::JoinAsTuple;
  141. using testing::internal::linked_ptr;
  142. using testing::internal::MatchMatrix;
  143. using testing::internal::RE;
  144. using testing::internal::scoped_ptr;
  145. using testing::internal::StreamMatchResultListener;
  146. using testing::internal::Strings;
  147. using testing::internal::linked_ptr;
  148. using testing::internal::scoped_ptr;
  149. using testing::internal::string;
  150. using testing::make_tuple;
  151. using testing::tuple;
  152. // For testing ExplainMatchResultTo().
  153. class GreaterThanMatcher : public MatcherInterface<int> {
  154. public:
  155. explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
  156. virtual void DescribeTo(ostream* os) const {
  157. *os << "is > " << rhs_;
  158. }
  159. virtual bool MatchAndExplain(int lhs,
  160. MatchResultListener* listener) const {
  161. const int diff = lhs - rhs_;
  162. if (diff > 0) {
  163. *listener << "which is " << diff << " more than " << rhs_;
  164. } else if (diff == 0) {
  165. *listener << "which is the same as " << rhs_;
  166. } else {
  167. *listener << "which is " << -diff << " less than " << rhs_;
  168. }
  169. return lhs > rhs_;
  170. }
  171. private:
  172. int rhs_;
  173. };
  174. Matcher<int> GreaterThan(int n) {
  175. return MakeMatcher(new GreaterThanMatcher(n));
  176. }
  177. string OfType(const string& type_name) {
  178. #if GTEST_HAS_RTTI
  179. return " (of type " + type_name + ")";
  180. #else
  181. return "";
  182. #endif
  183. }
  184. // Returns the description of the given matcher.
  185. template <typename T>
  186. string Describe(const Matcher<T>& m) {
  187. stringstream ss;
  188. m.DescribeTo(&ss);
  189. return ss.str();
  190. }
  191. // Returns the description of the negation of the given matcher.
  192. template <typename T>
  193. string DescribeNegation(const Matcher<T>& m) {
  194. stringstream ss;
  195. m.DescribeNegationTo(&ss);
  196. return ss.str();
  197. }
  198. // Returns the reason why x matches, or doesn't match, m.
  199. template <typename MatcherType, typename Value>
  200. string Explain(const MatcherType& m, const Value& x) {
  201. StringMatchResultListener listener;
  202. ExplainMatchResult(m, x, &listener);
  203. return listener.str();
  204. }
  205. TEST(MatchResultListenerTest, StreamingWorks) {
  206. StringMatchResultListener listener;
  207. listener << "hi" << 5;
  208. EXPECT_EQ("hi5", listener.str());
  209. listener.Clear();
  210. EXPECT_EQ("", listener.str());
  211. listener << 42;
  212. EXPECT_EQ("42", listener.str());
  213. // Streaming shouldn't crash when the underlying ostream is NULL.
  214. DummyMatchResultListener dummy;
  215. dummy << "hi" << 5;
  216. }
  217. TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
  218. EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
  219. EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
  220. EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
  221. }
  222. TEST(MatchResultListenerTest, IsInterestedWorks) {
  223. EXPECT_TRUE(StringMatchResultListener().IsInterested());
  224. EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
  225. EXPECT_FALSE(DummyMatchResultListener().IsInterested());
  226. EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
  227. }
  228. // Makes sure that the MatcherInterface<T> interface doesn't
  229. // change.
  230. class EvenMatcherImpl : public MatcherInterface<int> {
  231. public:
  232. virtual bool MatchAndExplain(int x,
  233. MatchResultListener* /* listener */) const {
  234. return x % 2 == 0;
  235. }
  236. virtual void DescribeTo(ostream* os) const {
  237. *os << "is an even number";
  238. }
  239. // We deliberately don't define DescribeNegationTo() and
  240. // ExplainMatchResultTo() here, to make sure the definition of these
  241. // two methods is optional.
  242. };
  243. // Makes sure that the MatcherInterface API doesn't change.
  244. TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
  245. EvenMatcherImpl m;
  246. }
  247. // Tests implementing a monomorphic matcher using MatchAndExplain().
  248. class NewEvenMatcherImpl : public MatcherInterface<int> {
  249. public:
  250. virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
  251. const bool match = x % 2 == 0;
  252. // Verifies that we can stream to a listener directly.
  253. *listener << "value % " << 2;
  254. if (listener->stream() != NULL) {
  255. // Verifies that we can stream to a listener's underlying stream
  256. // too.
  257. *listener->stream() << " == " << (x % 2);
  258. }
  259. return match;
  260. }
  261. virtual void DescribeTo(ostream* os) const {
  262. *os << "is an even number";
  263. }
  264. };
  265. TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
  266. Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
  267. EXPECT_TRUE(m.Matches(2));
  268. EXPECT_FALSE(m.Matches(3));
  269. EXPECT_EQ("value % 2 == 0", Explain(m, 2));
  270. EXPECT_EQ("value % 2 == 1", Explain(m, 3));
  271. }
  272. // Tests default-constructing a matcher.
  273. TEST(MatcherTest, CanBeDefaultConstructed) {
  274. Matcher<double> m;
  275. }
  276. // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
  277. TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
  278. const MatcherInterface<int>* impl = new EvenMatcherImpl;
  279. Matcher<int> m(impl);
  280. EXPECT_TRUE(m.Matches(4));
  281. EXPECT_FALSE(m.Matches(5));
  282. }
  283. // Tests that value can be used in place of Eq(value).
  284. TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
  285. Matcher<int> m1 = 5;
  286. EXPECT_TRUE(m1.Matches(5));
  287. EXPECT_FALSE(m1.Matches(6));
  288. }
  289. // Tests that NULL can be used in place of Eq(NULL).
  290. TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
  291. Matcher<int*> m1 = NULL;
  292. EXPECT_TRUE(m1.Matches(NULL));
  293. int n = 0;
  294. EXPECT_FALSE(m1.Matches(&n));
  295. }
  296. // Tests that matchers are copyable.
  297. TEST(MatcherTest, IsCopyable) {
  298. // Tests the copy constructor.
  299. Matcher<bool> m1 = Eq(false);
  300. EXPECT_TRUE(m1.Matches(false));
  301. EXPECT_FALSE(m1.Matches(true));
  302. // Tests the assignment operator.
  303. m1 = Eq(true);
  304. EXPECT_TRUE(m1.Matches(true));
  305. EXPECT_FALSE(m1.Matches(false));
  306. }
  307. // Tests that Matcher<T>::DescribeTo() calls
  308. // MatcherInterface<T>::DescribeTo().
  309. TEST(MatcherTest, CanDescribeItself) {
  310. EXPECT_EQ("is an even number",
  311. Describe(Matcher<int>(new EvenMatcherImpl)));
  312. }
  313. // Tests Matcher<T>::MatchAndExplain().
  314. TEST(MatcherTest, MatchAndExplain) {
  315. Matcher<int> m = GreaterThan(0);
  316. StringMatchResultListener listener1;
  317. EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
  318. EXPECT_EQ("which is 42 more than 0", listener1.str());
  319. StringMatchResultListener listener2;
  320. EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
  321. EXPECT_EQ("which is 9 less than 0", listener2.str());
  322. }
  323. // Tests that a C-string literal can be implicitly converted to a
  324. // Matcher<string> or Matcher<const string&>.
  325. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
  326. Matcher<string> m1 = "hi";
  327. EXPECT_TRUE(m1.Matches("hi"));
  328. EXPECT_FALSE(m1.Matches("hello"));
  329. Matcher<const string&> m2 = "hi";
  330. EXPECT_TRUE(m2.Matches("hi"));
  331. EXPECT_FALSE(m2.Matches("hello"));
  332. }
  333. // Tests that a string object can be implicitly converted to a
  334. // Matcher<string> or Matcher<const string&>.
  335. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
  336. Matcher<string> m1 = string("hi");
  337. EXPECT_TRUE(m1.Matches("hi"));
  338. EXPECT_FALSE(m1.Matches("hello"));
  339. Matcher<const string&> m2 = string("hi");
  340. EXPECT_TRUE(m2.Matches("hi"));
  341. EXPECT_FALSE(m2.Matches("hello"));
  342. }
  343. #if GTEST_HAS_STRING_PIECE_
  344. // Tests that a C-string literal can be implicitly converted to a
  345. // Matcher<StringPiece> or Matcher<const StringPiece&>.
  346. TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
  347. Matcher<StringPiece> m1 = "cats";
  348. EXPECT_TRUE(m1.Matches("cats"));
  349. EXPECT_FALSE(m1.Matches("dogs"));
  350. Matcher<const StringPiece&> m2 = "cats";
  351. EXPECT_TRUE(m2.Matches("cats"));
  352. EXPECT_FALSE(m2.Matches("dogs"));
  353. }
  354. // Tests that a string object can be implicitly converted to a
  355. // Matcher<StringPiece> or Matcher<const StringPiece&>.
  356. TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
  357. Matcher<StringPiece> m1 = string("cats");
  358. EXPECT_TRUE(m1.Matches("cats"));
  359. EXPECT_FALSE(m1.Matches("dogs"));
  360. Matcher<const StringPiece&> m2 = string("cats");
  361. EXPECT_TRUE(m2.Matches("cats"));
  362. EXPECT_FALSE(m2.Matches("dogs"));
  363. }
  364. // Tests that a StringPiece object can be implicitly converted to a
  365. // Matcher<StringPiece> or Matcher<const StringPiece&>.
  366. TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
  367. Matcher<StringPiece> m1 = StringPiece("cats");
  368. EXPECT_TRUE(m1.Matches("cats"));
  369. EXPECT_FALSE(m1.Matches("dogs"));
  370. Matcher<const StringPiece&> m2 = StringPiece("cats");
  371. EXPECT_TRUE(m2.Matches("cats"));
  372. EXPECT_FALSE(m2.Matches("dogs"));
  373. }
  374. #endif // GTEST_HAS_STRING_PIECE_
  375. // Tests that MakeMatcher() constructs a Matcher<T> from a
  376. // MatcherInterface* without requiring the user to explicitly
  377. // write the type.
  378. TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
  379. const MatcherInterface<int>* dummy_impl = NULL;
  380. Matcher<int> m = MakeMatcher(dummy_impl);
  381. }
  382. // Tests that MakePolymorphicMatcher() can construct a polymorphic
  383. // matcher from its implementation using the old API.
  384. const int g_bar = 1;
  385. class ReferencesBarOrIsZeroImpl {
  386. public:
  387. template <typename T>
  388. bool MatchAndExplain(const T& x,
  389. MatchResultListener* /* listener */) const {
  390. const void* p = &x;
  391. return p == &g_bar || x == 0;
  392. }
  393. void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
  394. void DescribeNegationTo(ostream* os) const {
  395. *os << "doesn't reference g_bar and is not zero";
  396. }
  397. };
  398. // This function verifies that MakePolymorphicMatcher() returns a
  399. // PolymorphicMatcher<T> where T is the argument's type.
  400. PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
  401. return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
  402. }
  403. TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
  404. // Using a polymorphic matcher to match a reference type.
  405. Matcher<const int&> m1 = ReferencesBarOrIsZero();
  406. EXPECT_TRUE(m1.Matches(0));
  407. // Verifies that the identity of a by-reference argument is preserved.
  408. EXPECT_TRUE(m1.Matches(g_bar));
  409. EXPECT_FALSE(m1.Matches(1));
  410. EXPECT_EQ("g_bar or zero", Describe(m1));
  411. // Using a polymorphic matcher to match a value type.
  412. Matcher<double> m2 = ReferencesBarOrIsZero();
  413. EXPECT_TRUE(m2.Matches(0.0));
  414. EXPECT_FALSE(m2.Matches(0.1));
  415. EXPECT_EQ("g_bar or zero", Describe(m2));
  416. }
  417. // Tests implementing a polymorphic matcher using MatchAndExplain().
  418. class PolymorphicIsEvenImpl {
  419. public:
  420. void DescribeTo(ostream* os) const { *os << "is even"; }
  421. void DescribeNegationTo(ostream* os) const {
  422. *os << "is odd";
  423. }
  424. template <typename T>
  425. bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
  426. // Verifies that we can stream to the listener directly.
  427. *listener << "% " << 2;
  428. if (listener->stream() != NULL) {
  429. // Verifies that we can stream to the listener's underlying stream
  430. // too.
  431. *listener->stream() << " == " << (x % 2);
  432. }
  433. return (x % 2) == 0;
  434. }
  435. };
  436. PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
  437. return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
  438. }
  439. TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
  440. // Using PolymorphicIsEven() as a Matcher<int>.
  441. const Matcher<int> m1 = PolymorphicIsEven();
  442. EXPECT_TRUE(m1.Matches(42));
  443. EXPECT_FALSE(m1.Matches(43));
  444. EXPECT_EQ("is even", Describe(m1));
  445. const Matcher<int> not_m1 = Not(m1);
  446. EXPECT_EQ("is odd", Describe(not_m1));
  447. EXPECT_EQ("% 2 == 0", Explain(m1, 42));
  448. // Using PolymorphicIsEven() as a Matcher<char>.
  449. const Matcher<char> m2 = PolymorphicIsEven();
  450. EXPECT_TRUE(m2.Matches('\x42'));
  451. EXPECT_FALSE(m2.Matches('\x43'));
  452. EXPECT_EQ("is even", Describe(m2));
  453. const Matcher<char> not_m2 = Not(m2);
  454. EXPECT_EQ("is odd", Describe(not_m2));
  455. EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
  456. }
  457. // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
  458. TEST(MatcherCastTest, FromPolymorphicMatcher) {
  459. Matcher<int> m = MatcherCast<int>(Eq(5));
  460. EXPECT_TRUE(m.Matches(5));
  461. EXPECT_FALSE(m.Matches(6));
  462. }
  463. // For testing casting matchers between compatible types.
  464. class IntValue {
  465. public:
  466. // An int can be statically (although not implicitly) cast to a
  467. // IntValue.
  468. explicit IntValue(int a_value) : value_(a_value) {}
  469. int value() const { return value_; }
  470. private:
  471. int value_;
  472. };
  473. // For testing casting matchers between compatible types.
  474. bool IsPositiveIntValue(const IntValue& foo) {
  475. return foo.value() > 0;
  476. }
  477. // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
  478. // can be statically converted to U.
  479. TEST(MatcherCastTest, FromCompatibleType) {
  480. Matcher<double> m1 = Eq(2.0);
  481. Matcher<int> m2 = MatcherCast<int>(m1);
  482. EXPECT_TRUE(m2.Matches(2));
  483. EXPECT_FALSE(m2.Matches(3));
  484. Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
  485. Matcher<int> m4 = MatcherCast<int>(m3);
  486. // In the following, the arguments 1 and 0 are statically converted
  487. // to IntValue objects, and then tested by the IsPositiveIntValue()
  488. // predicate.
  489. EXPECT_TRUE(m4.Matches(1));
  490. EXPECT_FALSE(m4.Matches(0));
  491. }
  492. // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
  493. TEST(MatcherCastTest, FromConstReferenceToNonReference) {
  494. Matcher<const int&> m1 = Eq(0);
  495. Matcher<int> m2 = MatcherCast<int>(m1);
  496. EXPECT_TRUE(m2.Matches(0));
  497. EXPECT_FALSE(m2.Matches(1));
  498. }
  499. // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
  500. TEST(MatcherCastTest, FromReferenceToNonReference) {
  501. Matcher<int&> m1 = Eq(0);
  502. Matcher<int> m2 = MatcherCast<int>(m1);
  503. EXPECT_TRUE(m2.Matches(0));
  504. EXPECT_FALSE(m2.Matches(1));
  505. }
  506. // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
  507. TEST(MatcherCastTest, FromNonReferenceToConstReference) {
  508. Matcher<int> m1 = Eq(0);
  509. Matcher<const int&> m2 = MatcherCast<const int&>(m1);
  510. EXPECT_TRUE(m2.Matches(0));
  511. EXPECT_FALSE(m2.Matches(1));
  512. }
  513. // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
  514. TEST(MatcherCastTest, FromNonReferenceToReference) {
  515. Matcher<int> m1 = Eq(0);
  516. Matcher<int&> m2 = MatcherCast<int&>(m1);
  517. int n = 0;
  518. EXPECT_TRUE(m2.Matches(n));
  519. n = 1;
  520. EXPECT_FALSE(m2.Matches(n));
  521. }
  522. // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
  523. TEST(MatcherCastTest, FromSameType) {
  524. Matcher<int> m1 = Eq(0);
  525. Matcher<int> m2 = MatcherCast<int>(m1);
  526. EXPECT_TRUE(m2.Matches(0));
  527. EXPECT_FALSE(m2.Matches(1));
  528. }
  529. // Implicitly convertible from any type.
  530. struct ConvertibleFromAny {
  531. ConvertibleFromAny(int a_value) : value(a_value) {}
  532. template <typename T>
  533. explicit ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
  534. ADD_FAILURE() << "Conversion constructor called";
  535. }
  536. int value;
  537. };
  538. bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
  539. return a.value == b.value;
  540. }
  541. ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
  542. return os << a.value;
  543. }
  544. TEST(MatcherCastTest, ConversionConstructorIsUsed) {
  545. Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
  546. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  547. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  548. }
  549. TEST(MatcherCastTest, FromConvertibleFromAny) {
  550. Matcher<ConvertibleFromAny> m =
  551. MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
  552. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  553. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  554. }
  555. struct IntReferenceWrapper {
  556. IntReferenceWrapper(const int& a_value) : value(&a_value) {}
  557. const int* value;
  558. };
  559. bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
  560. return a.value == b.value;
  561. }
  562. TEST(MatcherCastTest, ValueIsNotCopied) {
  563. int n = 42;
  564. Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
  565. // Verify that the matcher holds a reference to n, not to its temporary copy.
  566. EXPECT_TRUE(m.Matches(n));
  567. }
  568. class Base {
  569. public:
  570. virtual ~Base() {}
  571. Base() {}
  572. private:
  573. GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
  574. };
  575. class Derived : public Base {
  576. public:
  577. Derived() : Base() {}
  578. int i;
  579. };
  580. class OtherDerived : public Base {};
  581. // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
  582. TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
  583. Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
  584. EXPECT_TRUE(m2.Matches(' '));
  585. EXPECT_FALSE(m2.Matches('\n'));
  586. }
  587. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
  588. // T and U are arithmetic types and T can be losslessly converted to
  589. // U.
  590. TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
  591. Matcher<double> m1 = DoubleEq(1.0);
  592. Matcher<float> m2 = SafeMatcherCast<float>(m1);
  593. EXPECT_TRUE(m2.Matches(1.0f));
  594. EXPECT_FALSE(m2.Matches(2.0f));
  595. Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
  596. EXPECT_TRUE(m3.Matches('a'));
  597. EXPECT_FALSE(m3.Matches('b'));
  598. }
  599. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
  600. // are pointers or references to a derived and a base class, correspondingly.
  601. TEST(SafeMatcherCastTest, FromBaseClass) {
  602. Derived d, d2;
  603. Matcher<Base*> m1 = Eq(&d);
  604. Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
  605. EXPECT_TRUE(m2.Matches(&d));
  606. EXPECT_FALSE(m2.Matches(&d2));
  607. Matcher<Base&> m3 = Ref(d);
  608. Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
  609. EXPECT_TRUE(m4.Matches(d));
  610. EXPECT_FALSE(m4.Matches(d2));
  611. }
  612. // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
  613. TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
  614. int n = 0;
  615. Matcher<const int&> m1 = Ref(n);
  616. Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
  617. int n1 = 0;
  618. EXPECT_TRUE(m2.Matches(n));
  619. EXPECT_FALSE(m2.Matches(n1));
  620. }
  621. // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
  622. TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
  623. Matcher<int> m1 = Eq(0);
  624. Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
  625. EXPECT_TRUE(m2.Matches(0));
  626. EXPECT_FALSE(m2.Matches(1));
  627. }
  628. // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
  629. TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
  630. Matcher<int> m1 = Eq(0);
  631. Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
  632. int n = 0;
  633. EXPECT_TRUE(m2.Matches(n));
  634. n = 1;
  635. EXPECT_FALSE(m2.Matches(n));
  636. }
  637. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
  638. TEST(SafeMatcherCastTest, FromSameType) {
  639. Matcher<int> m1 = Eq(0);
  640. Matcher<int> m2 = SafeMatcherCast<int>(m1);
  641. EXPECT_TRUE(m2.Matches(0));
  642. EXPECT_FALSE(m2.Matches(1));
  643. }
  644. TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
  645. Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
  646. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  647. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  648. }
  649. TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
  650. Matcher<ConvertibleFromAny> m =
  651. SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
  652. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  653. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  654. }
  655. TEST(SafeMatcherCastTest, ValueIsNotCopied) {
  656. int n = 42;
  657. Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
  658. // Verify that the matcher holds a reference to n, not to its temporary copy.
  659. EXPECT_TRUE(m.Matches(n));
  660. }
  661. TEST(ExpectThat, TakesLiterals) {
  662. EXPECT_THAT(1, 1);
  663. EXPECT_THAT(1.0, 1.0);
  664. EXPECT_THAT(string(), "");
  665. }
  666. TEST(ExpectThat, TakesFunctions) {
  667. struct Helper {
  668. static void Func() {}
  669. };
  670. void (*func)() = Helper::Func;
  671. EXPECT_THAT(func, Helper::Func);
  672. EXPECT_THAT(func, &Helper::Func);
  673. }
  674. // Tests that A<T>() matches any value of type T.
  675. TEST(ATest, MatchesAnyValue) {
  676. // Tests a matcher for a value type.
  677. Matcher<double> m1 = A<double>();
  678. EXPECT_TRUE(m1.Matches(91.43));
  679. EXPECT_TRUE(m1.Matches(-15.32));
  680. // Tests a matcher for a reference type.
  681. int a = 2;
  682. int b = -6;
  683. Matcher<int&> m2 = A<int&>();
  684. EXPECT_TRUE(m2.Matches(a));
  685. EXPECT_TRUE(m2.Matches(b));
  686. }
  687. TEST(ATest, WorksForDerivedClass) {
  688. Base base;
  689. Derived derived;
  690. EXPECT_THAT(&base, A<Base*>());
  691. // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
  692. EXPECT_THAT(&derived, A<Base*>());
  693. EXPECT_THAT(&derived, A<Derived*>());
  694. }
  695. // Tests that A<T>() describes itself properly.
  696. TEST(ATest, CanDescribeSelf) {
  697. EXPECT_EQ("is anything", Describe(A<bool>()));
  698. }
  699. // Tests that An<T>() matches any value of type T.
  700. TEST(AnTest, MatchesAnyValue) {
  701. // Tests a matcher for a value type.
  702. Matcher<int> m1 = An<int>();
  703. EXPECT_TRUE(m1.Matches(9143));
  704. EXPECT_TRUE(m1.Matches(-1532));
  705. // Tests a matcher for a reference type.
  706. int a = 2;
  707. int b = -6;
  708. Matcher<int&> m2 = An<int&>();
  709. EXPECT_TRUE(m2.Matches(a));
  710. EXPECT_TRUE(m2.Matches(b));
  711. }
  712. // Tests that An<T>() describes itself properly.
  713. TEST(AnTest, CanDescribeSelf) {
  714. EXPECT_EQ("is anything", Describe(An<int>()));
  715. }
  716. // Tests that _ can be used as a matcher for any type and matches any
  717. // value of that type.
  718. TEST(UnderscoreTest, MatchesAnyValue) {
  719. // Uses _ as a matcher for a value type.
  720. Matcher<int> m1 = _;
  721. EXPECT_TRUE(m1.Matches(123));
  722. EXPECT_TRUE(m1.Matches(-242));
  723. // Uses _ as a matcher for a reference type.
  724. bool a = false;
  725. const bool b = true;
  726. Matcher<const bool&> m2 = _;
  727. EXPECT_TRUE(m2.Matches(a));
  728. EXPECT_TRUE(m2.Matches(b));
  729. }
  730. // Tests that _ describes itself properly.
  731. TEST(UnderscoreTest, CanDescribeSelf) {
  732. Matcher<int> m = _;
  733. EXPECT_EQ("is anything", Describe(m));
  734. }
  735. // Tests that Eq(x) matches any value equal to x.
  736. TEST(EqTest, MatchesEqualValue) {
  737. // 2 C-strings with same content but different addresses.
  738. const char a1[] = "hi";
  739. const char a2[] = "hi";
  740. Matcher<const char*> m1 = Eq(a1);
  741. EXPECT_TRUE(m1.Matches(a1));
  742. EXPECT_FALSE(m1.Matches(a2));
  743. }
  744. // Tests that Eq(v) describes itself properly.
  745. class Unprintable {
  746. public:
  747. Unprintable() : c_('a') {}
  748. private:
  749. char c_;
  750. };
  751. inline bool operator==(const Unprintable& /* lhs */,
  752. const Unprintable& /* rhs */) {
  753. return true;
  754. }
  755. TEST(EqTest, CanDescribeSelf) {
  756. Matcher<Unprintable> m = Eq(Unprintable());
  757. EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
  758. }
  759. // Tests that Eq(v) can be used to match any type that supports
  760. // comparing with type T, where T is v's type.
  761. TEST(EqTest, IsPolymorphic) {
  762. Matcher<int> m1 = Eq(1);
  763. EXPECT_TRUE(m1.Matches(1));
  764. EXPECT_FALSE(m1.Matches(2));
  765. Matcher<char> m2 = Eq(1);
  766. EXPECT_TRUE(m2.Matches('\1'));
  767. EXPECT_FALSE(m2.Matches('a'));
  768. }
  769. // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
  770. TEST(TypedEqTest, ChecksEqualityForGivenType) {
  771. Matcher<char> m1 = TypedEq<char>('a');
  772. EXPECT_TRUE(m1.Matches('a'));
  773. EXPECT_FALSE(m1.Matches('b'));
  774. Matcher<int> m2 = TypedEq<int>(6);
  775. EXPECT_TRUE(m2.Matches(6));
  776. EXPECT_FALSE(m2.Matches(7));
  777. }
  778. // Tests that TypedEq(v) describes itself properly.
  779. TEST(TypedEqTest, CanDescribeSelf) {
  780. EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
  781. }
  782. // Tests that TypedEq<T>(v) has type Matcher<T>.
  783. // Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
  784. // is a "bare" type (i.e. not in the form of const U or U&). If v's
  785. // type is not T, the compiler will generate a message about
  786. // "undefined referece".
  787. template <typename T>
  788. struct Type {
  789. static bool IsTypeOf(const T& /* v */) { return true; }
  790. template <typename T2>
  791. static void IsTypeOf(T2 v);
  792. };
  793. TEST(TypedEqTest, HasSpecifiedType) {
  794. // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
  795. Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
  796. Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
  797. }
  798. // Tests that Ge(v) matches anything >= v.
  799. TEST(GeTest, ImplementsGreaterThanOrEqual) {
  800. Matcher<int> m1 = Ge(0);
  801. EXPECT_TRUE(m1.Matches(1));
  802. EXPECT_TRUE(m1.Matches(0));
  803. EXPECT_FALSE(m1.Matches(-1));
  804. }
  805. // Tests that Ge(v) describes itself properly.
  806. TEST(GeTest, CanDescribeSelf) {
  807. Matcher<int> m = Ge(5);
  808. EXPECT_EQ("is >= 5", Describe(m));
  809. }
  810. // Tests that Gt(v) matches anything > v.
  811. TEST(GtTest, ImplementsGreaterThan) {
  812. Matcher<double> m1 = Gt(0);
  813. EXPECT_TRUE(m1.Matches(1.0));
  814. EXPECT_FALSE(m1.Matches(0.0));
  815. EXPECT_FALSE(m1.Matches(-1.0));
  816. }
  817. // Tests that Gt(v) describes itself properly.
  818. TEST(GtTest, CanDescribeSelf) {
  819. Matcher<int> m = Gt(5);
  820. EXPECT_EQ("is > 5", Describe(m));
  821. }
  822. // Tests that Le(v) matches anything <= v.
  823. TEST(LeTest, ImplementsLessThanOrEqual) {
  824. Matcher<char> m1 = Le('b');
  825. EXPECT_TRUE(m1.Matches('a'));
  826. EXPECT_TRUE(m1.Matches('b'));
  827. EXPECT_FALSE(m1.Matches('c'));
  828. }
  829. // Tests that Le(v) describes itself properly.
  830. TEST(LeTest, CanDescribeSelf) {
  831. Matcher<int> m = Le(5);
  832. EXPECT_EQ("is <= 5", Describe(m));
  833. }
  834. // Tests that Lt(v) matches anything < v.
  835. TEST(LtTest, ImplementsLessThan) {
  836. Matcher<const string&> m1 = Lt("Hello");
  837. EXPECT_TRUE(m1.Matches("Abc"));
  838. EXPECT_FALSE(m1.Matches("Hello"));
  839. EXPECT_FALSE(m1.Matches("Hello, world!"));
  840. }
  841. // Tests that Lt(v) describes itself properly.
  842. TEST(LtTest, CanDescribeSelf) {
  843. Matcher<int> m = Lt(5);
  844. EXPECT_EQ("is < 5", Describe(m));
  845. }
  846. // Tests that Ne(v) matches anything != v.
  847. TEST(NeTest, ImplementsNotEqual) {
  848. Matcher<int> m1 = Ne(0);
  849. EXPECT_TRUE(m1.Matches(1));
  850. EXPECT_TRUE(m1.Matches(-1));
  851. EXPECT_FALSE(m1.Matches(0));
  852. }
  853. // Tests that Ne(v) describes itself properly.
  854. TEST(NeTest, CanDescribeSelf) {
  855. Matcher<int> m = Ne(5);
  856. EXPECT_EQ("isn't equal to 5", Describe(m));
  857. }
  858. // Tests that IsNull() matches any NULL pointer of any type.
  859. TEST(IsNullTest, MatchesNullPointer) {
  860. Matcher<int*> m1 = IsNull();
  861. int* p1 = NULL;
  862. int n = 0;
  863. EXPECT_TRUE(m1.Matches(p1));
  864. EXPECT_FALSE(m1.Matches(&n));
  865. Matcher<const char*> m2 = IsNull();
  866. const char* p2 = NULL;
  867. EXPECT_TRUE(m2.Matches(p2));
  868. EXPECT_FALSE(m2.Matches("hi"));
  869. #if !GTEST_OS_SYMBIAN
  870. // Nokia's Symbian compiler generates:
  871. // gmock-matchers.h: ambiguous access to overloaded function
  872. // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
  873. // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
  874. // MatcherInterface<void *> *)'
  875. // gmock-matchers.h: (point of instantiation: 'testing::
  876. // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
  877. // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
  878. Matcher<void*> m3 = IsNull();
  879. void* p3 = NULL;
  880. EXPECT_TRUE(m3.Matches(p3));
  881. EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
  882. #endif
  883. }
  884. TEST(IsNullTest, LinkedPtr) {
  885. const Matcher<linked_ptr<int> > m = IsNull();
  886. const linked_ptr<int> null_p;
  887. const linked_ptr<int> non_null_p(new int);
  888. EXPECT_TRUE(m.Matches(null_p));
  889. EXPECT_FALSE(m.Matches(non_null_p));
  890. }
  891. TEST(IsNullTest, ReferenceToConstLinkedPtr) {
  892. const Matcher<const linked_ptr<double>&> m = IsNull();
  893. const linked_ptr<double> null_p;
  894. const linked_ptr<double> non_null_p(new double);
  895. EXPECT_TRUE(m.Matches(null_p));
  896. EXPECT_FALSE(m.Matches(non_null_p));
  897. }
  898. #if GTEST_HAS_STD_FUNCTION_
  899. TEST(IsNullTest, StdFunction) {
  900. const Matcher<std::function<void()>> m = IsNull();
  901. EXPECT_TRUE(m.Matches(std::function<void()>()));
  902. EXPECT_FALSE(m.Matches([]{}));
  903. }
  904. #endif // GTEST_HAS_STD_FUNCTION_
  905. // Tests that IsNull() describes itself properly.
  906. TEST(IsNullTest, CanDescribeSelf) {
  907. Matcher<int*> m = IsNull();
  908. EXPECT_EQ("is NULL", Describe(m));
  909. EXPECT_EQ("isn't NULL", DescribeNegation(m));
  910. }
  911. // Tests that NotNull() matches any non-NULL pointer of any type.
  912. TEST(NotNullTest, MatchesNonNullPointer) {
  913. Matcher<int*> m1 = NotNull();
  914. int* p1 = NULL;
  915. int n = 0;
  916. EXPECT_FALSE(m1.Matches(p1));
  917. EXPECT_TRUE(m1.Matches(&n));
  918. Matcher<const char*> m2 = NotNull();
  919. const char* p2 = NULL;
  920. EXPECT_FALSE(m2.Matches(p2));
  921. EXPECT_TRUE(m2.Matches("hi"));
  922. }
  923. TEST(NotNullTest, LinkedPtr) {
  924. const Matcher<linked_ptr<int> > m = NotNull();
  925. const linked_ptr<int> null_p;
  926. const linked_ptr<int> non_null_p(new int);
  927. EXPECT_FALSE(m.Matches(null_p));
  928. EXPECT_TRUE(m.Matches(non_null_p));
  929. }
  930. TEST(NotNullTest, ReferenceToConstLinkedPtr) {
  931. const Matcher<const linked_ptr<double>&> m = NotNull();
  932. const linked_ptr<double> null_p;
  933. const linked_ptr<double> non_null_p(new double);
  934. EXPECT_FALSE(m.Matches(null_p));
  935. EXPECT_TRUE(m.Matches(non_null_p));
  936. }
  937. #if GTEST_HAS_STD_FUNCTION_
  938. TEST(NotNullTest, StdFunction) {
  939. const Matcher<std::function<void()>> m = NotNull();
  940. EXPECT_TRUE(m.Matches([]{}));
  941. EXPECT_FALSE(m.Matches(std::function<void()>()));
  942. }
  943. #endif // GTEST_HAS_STD_FUNCTION_
  944. // Tests that NotNull() describes itself properly.
  945. TEST(NotNullTest, CanDescribeSelf) {
  946. Matcher<int*> m = NotNull();
  947. EXPECT_EQ("isn't NULL", Describe(m));
  948. }
  949. // Tests that Ref(variable) matches an argument that references
  950. // 'variable'.
  951. TEST(RefTest, MatchesSameVariable) {
  952. int a = 0;
  953. int b = 0;
  954. Matcher<int&> m = Ref(a);
  955. EXPECT_TRUE(m.Matches(a));
  956. EXPECT_FALSE(m.Matches(b));
  957. }
  958. // Tests that Ref(variable) describes itself properly.
  959. TEST(RefTest, CanDescribeSelf) {
  960. int n = 5;
  961. Matcher<int&> m = Ref(n);
  962. stringstream ss;
  963. ss << "references the variable @" << &n << " 5";
  964. EXPECT_EQ(string(ss.str()), Describe(m));
  965. }
  966. // Test that Ref(non_const_varialbe) can be used as a matcher for a
  967. // const reference.
  968. TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
  969. int a = 0;
  970. int b = 0;
  971. Matcher<const int&> m = Ref(a);
  972. EXPECT_TRUE(m.Matches(a));
  973. EXPECT_FALSE(m.Matches(b));
  974. }
  975. // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
  976. // used wherever Ref(base) can be used (Ref(derived) is a sub-type
  977. // of Ref(base), but not vice versa.
  978. TEST(RefTest, IsCovariant) {
  979. Base base, base2;
  980. Derived derived;
  981. Matcher<const Base&> m1 = Ref(base);
  982. EXPECT_TRUE(m1.Matches(base));
  983. EXPECT_FALSE(m1.Matches(base2));
  984. EXPECT_FALSE(m1.Matches(derived));
  985. m1 = Ref(derived);
  986. EXPECT_TRUE(m1.Matches(derived));
  987. EXPECT_FALSE(m1.Matches(base));
  988. EXPECT_FALSE(m1.Matches(base2));
  989. }
  990. TEST(RefTest, ExplainsResult) {
  991. int n = 0;
  992. EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
  993. StartsWith("which is located @"));
  994. int m = 0;
  995. EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
  996. StartsWith("which is located @"));
  997. }
  998. // Tests string comparison matchers.
  999. TEST(StrEqTest, MatchesEqualString) {
  1000. Matcher<const char*> m = StrEq(string("Hello"));
  1001. EXPECT_TRUE(m.Matches("Hello"));
  1002. EXPECT_FALSE(m.Matches("hello"));
  1003. EXPECT_FALSE(m.Matches(NULL));
  1004. Matcher<const string&> m2 = StrEq("Hello");
  1005. EXPECT_TRUE(m2.Matches("Hello"));
  1006. EXPECT_FALSE(m2.Matches("Hi"));
  1007. }
  1008. TEST(StrEqTest, CanDescribeSelf) {
  1009. Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
  1010. EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
  1011. Describe(m));
  1012. string str("01204500800");
  1013. str[3] = '\0';
  1014. Matcher<string> m2 = StrEq(str);
  1015. EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
  1016. str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
  1017. Matcher<string> m3 = StrEq(str);
  1018. EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
  1019. }
  1020. TEST(StrNeTest, MatchesUnequalString) {
  1021. Matcher<const char*> m = StrNe("Hello");
  1022. EXPECT_TRUE(m.Matches(""));
  1023. EXPECT_TRUE(m.Matches(NULL));
  1024. EXPECT_FALSE(m.Matches("Hello"));
  1025. Matcher<string> m2 = StrNe(string("Hello"));
  1026. EXPECT_TRUE(m2.Matches("hello"));
  1027. EXPECT_FALSE(m2.Matches("Hello"));
  1028. }
  1029. TEST(StrNeTest, CanDescribeSelf) {
  1030. Matcher<const char*> m = StrNe("Hi");
  1031. EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
  1032. }
  1033. TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
  1034. Matcher<const char*> m = StrCaseEq(string("Hello"));
  1035. EXPECT_TRUE(m.Matches("Hello"));
  1036. EXPECT_TRUE(m.Matches("hello"));
  1037. EXPECT_FALSE(m.Matches("Hi"));
  1038. EXPECT_FALSE(m.Matches(NULL));
  1039. Matcher<const string&> m2 = StrCaseEq("Hello");
  1040. EXPECT_TRUE(m2.Matches("hello"));
  1041. EXPECT_FALSE(m2.Matches("Hi"));
  1042. }
  1043. TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
  1044. string str1("oabocdooeoo");
  1045. string str2("OABOCDOOEOO");
  1046. Matcher<const string&> m0 = StrCaseEq(str1);
  1047. EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
  1048. str1[3] = str2[3] = '\0';
  1049. Matcher<const string&> m1 = StrCaseEq(str1);
  1050. EXPECT_TRUE(m1.Matches(str2));
  1051. str1[0] = str1[6] = str1[7] = str1[10] = '\0';
  1052. str2[0] = str2[6] = str2[7] = str2[10] = '\0';
  1053. Matcher<const string&> m2 = StrCaseEq(str1);
  1054. str1[9] = str2[9] = '\0';
  1055. EXPECT_FALSE(m2.Matches(str2));
  1056. Matcher<const string&> m3 = StrCaseEq(str1);
  1057. EXPECT_TRUE(m3.Matches(str2));
  1058. EXPECT_FALSE(m3.Matches(str2 + "x"));
  1059. str2.append(1, '\0');
  1060. EXPECT_FALSE(m3.Matches(str2));
  1061. EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
  1062. }
  1063. TEST(StrCaseEqTest, CanDescribeSelf) {
  1064. Matcher<string> m = StrCaseEq("Hi");
  1065. EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
  1066. }
  1067. TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
  1068. Matcher<const char*> m = StrCaseNe("Hello");
  1069. EXPECT_TRUE(m.Matches("Hi"));
  1070. EXPECT_TRUE(m.Matches(NULL));
  1071. EXPECT_FALSE(m.Matches("Hello"));
  1072. EXPECT_FALSE(m.Matches("hello"));
  1073. Matcher<string> m2 = StrCaseNe(string("Hello"));
  1074. EXPECT_TRUE(m2.Matches(""));
  1075. EXPECT_FALSE(m2.Matches("Hello"));
  1076. }
  1077. TEST(StrCaseNeTest, CanDescribeSelf) {
  1078. Matcher<const char*> m = StrCaseNe("Hi");
  1079. EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
  1080. }
  1081. // Tests that HasSubstr() works for matching string-typed values.
  1082. TEST(HasSubstrTest, WorksForStringClasses) {
  1083. const Matcher<string> m1 = HasSubstr("foo");
  1084. EXPECT_TRUE(m1.Matches(string("I love food.")));
  1085. EXPECT_FALSE(m1.Matches(string("tofo")));
  1086. const Matcher<const std::string&> m2 = HasSubstr("foo");
  1087. EXPECT_TRUE(m2.Matches(std::string("I love food.")));
  1088. EXPECT_FALSE(m2.Matches(std::string("tofo")));
  1089. }
  1090. // Tests that HasSubstr() works for matching C-string-typed values.
  1091. TEST(HasSubstrTest, WorksForCStrings) {
  1092. const Matcher<char*> m1 = HasSubstr("foo");
  1093. EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
  1094. EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
  1095. EXPECT_FALSE(m1.Matches(NULL));
  1096. const Matcher<const char*> m2 = HasSubstr("foo");
  1097. EXPECT_TRUE(m2.Matches("I love food."));
  1098. EXPECT_FALSE(m2.Matches("tofo"));
  1099. EXPECT_FALSE(m2.Matches(NULL));
  1100. }
  1101. // Tests that HasSubstr(s) describes itself properly.
  1102. TEST(HasSubstrTest, CanDescribeSelf) {
  1103. Matcher<string> m = HasSubstr("foo\n\"");
  1104. EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
  1105. }
  1106. TEST(KeyTest, CanDescribeSelf) {
  1107. Matcher<const pair<std::string, int>&> m = Key("foo");
  1108. EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
  1109. EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
  1110. }
  1111. TEST(KeyTest, ExplainsResult) {
  1112. Matcher<pair<int, bool> > m = Key(GreaterThan(10));
  1113. EXPECT_EQ("whose first field is a value which is 5 less than 10",
  1114. Explain(m, make_pair(5, true)));
  1115. EXPECT_EQ("whose first field is a value which is 5 more than 10",
  1116. Explain(m, make_pair(15, true)));
  1117. }
  1118. TEST(KeyTest, MatchesCorrectly) {
  1119. pair<int, std::string> p(25, "foo");
  1120. EXPECT_THAT(p, Key(25));
  1121. EXPECT_THAT(p, Not(Key(42)));
  1122. EXPECT_THAT(p, Key(Ge(20)));
  1123. EXPECT_THAT(p, Not(Key(Lt(25))));
  1124. }
  1125. TEST(KeyTest, SafelyCastsInnerMatcher) {
  1126. Matcher<int> is_positive = Gt(0);
  1127. Matcher<int> is_negative = Lt(0);
  1128. pair<char, bool> p('a', true);
  1129. EXPECT_THAT(p, Key(is_positive));
  1130. EXPECT_THAT(p, Not(Key(is_negative)));
  1131. }
  1132. TEST(KeyTest, InsideContainsUsingMap) {
  1133. map<int, char> container;
  1134. container.insert(make_pair(1, 'a'));
  1135. container.insert(make_pair(2, 'b'));
  1136. container.insert(make_pair(4, 'c'));
  1137. EXPECT_THAT(container, Contains(Key(1)));
  1138. EXPECT_THAT(container, Not(Contains(Key(3))));
  1139. }
  1140. TEST(KeyTest, InsideContainsUsingMultimap) {
  1141. multimap<int, char> container;
  1142. container.insert(make_pair(1, 'a'));
  1143. container.insert(make_pair(2, 'b'));
  1144. container.insert(make_pair(4, 'c'));
  1145. EXPECT_THAT(container, Not(Contains(Key(25))));
  1146. container.insert(make_pair(25, 'd'));
  1147. EXPECT_THAT(container, Contains(Key(25)));
  1148. container.insert(make_pair(25, 'e'));
  1149. EXPECT_THAT(container, Contains(Key(25)));
  1150. EXPECT_THAT(container, Contains(Key(1)));
  1151. EXPECT_THAT(container, Not(Contains(Key(3))));
  1152. }
  1153. TEST(PairTest, Typing) {
  1154. // Test verifies the following type conversions can be compiled.
  1155. Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
  1156. Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
  1157. Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
  1158. Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
  1159. Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
  1160. }
  1161. TEST(PairTest, CanDescribeSelf) {
  1162. Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
  1163. EXPECT_EQ("has a first field that is equal to \"foo\""
  1164. ", and has a second field that is equal to 42",
  1165. Describe(m1));
  1166. EXPECT_EQ("has a first field that isn't equal to \"foo\""
  1167. ", or has a second field that isn't equal to 42",
  1168. DescribeNegation(m1));
  1169. // Double and triple negation (1 or 2 times not and description of negation).
  1170. Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
  1171. EXPECT_EQ("has a first field that isn't equal to 13"
  1172. ", and has a second field that is equal to 42",
  1173. DescribeNegation(m2));
  1174. }
  1175. TEST(PairTest, CanExplainMatchResultTo) {
  1176. // If neither field matches, Pair() should explain about the first
  1177. // field.
  1178. const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
  1179. EXPECT_EQ("whose first field does not match, which is 1 less than 0",
  1180. Explain(m, make_pair(-1, -2)));
  1181. // If the first field matches but the second doesn't, Pair() should
  1182. // explain about the second field.
  1183. EXPECT_EQ("whose second field does not match, which is 2 less than 0",
  1184. Explain(m, make_pair(1, -2)));
  1185. // If the first field doesn't match but the second does, Pair()
  1186. // should explain about the first field.
  1187. EXPECT_EQ("whose first field does not match, which is 1 less than 0",
  1188. Explain(m, make_pair(-1, 2)));
  1189. // If both fields match, Pair() should explain about them both.
  1190. EXPECT_EQ("whose both fields match, where the first field is a value "
  1191. "which is 1 more than 0, and the second field is a value "
  1192. "which is 2 more than 0",
  1193. Explain(m, make_pair(1, 2)));
  1194. // If only the first match has an explanation, only this explanation should
  1195. // be printed.
  1196. const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
  1197. EXPECT_EQ("whose both fields match, where the first field is a value "
  1198. "which is 1 more than 0",
  1199. Explain(explain_first, make_pair(1, 0)));
  1200. // If only the second match has an explanation, only this explanation should
  1201. // be printed.
  1202. const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
  1203. EXPECT_EQ("whose both fields match, where the second field is a value "
  1204. "which is 1 more than 0",
  1205. Explain(explain_second, make_pair(0, 1)));
  1206. }
  1207. TEST(PairTest, MatchesCorrectly) {
  1208. pair<int, std::string> p(25, "foo");
  1209. // Both fields match.
  1210. EXPECT_THAT(p, Pair(25, "foo"));
  1211. EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
  1212. // 'first' doesnt' match, but 'second' matches.
  1213. EXPECT_THAT(p, Not(Pair(42, "foo")));
  1214. EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
  1215. // 'first' matches, but 'second' doesn't match.
  1216. EXPECT_THAT(p, Not(Pair(25, "bar")));
  1217. EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
  1218. // Neither field matches.
  1219. EXPECT_THAT(p, Not(Pair(13, "bar")));
  1220. EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
  1221. }
  1222. TEST(PairTest, SafelyCastsInnerMatchers) {
  1223. Matcher<int> is_positive = Gt(0);
  1224. Matcher<int> is_negative = Lt(0);
  1225. pair<char, bool> p('a', true);
  1226. EXPECT_THAT(p, Pair(is_positive, _));
  1227. EXPECT_THAT(p, Not(Pair(is_negative, _)));
  1228. EXPECT_THAT(p, Pair(_, is_positive));
  1229. EXPECT_THAT(p, Not(Pair(_, is_negative)));
  1230. }
  1231. TEST(PairTest, InsideContainsUsingMap) {
  1232. map<int, char> container;
  1233. container.insert(make_pair(1, 'a'));
  1234. container.insert(make_pair(2, 'b'));
  1235. container.insert(make_pair(4, 'c'));
  1236. EXPECT_THAT(container, Contains(Pair(1, 'a')));
  1237. EXPECT_THAT(container, Contains(Pair(1, _)));
  1238. EXPECT_THAT(container, Contains(Pair(_, 'a')));
  1239. EXPECT_THAT(container, Not(Contains(Pair(3, _))));
  1240. }
  1241. // Tests StartsWith(s).
  1242. TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
  1243. const Matcher<const char*> m1 = StartsWith(string(""));
  1244. EXPECT_TRUE(m1.Matches("Hi"));
  1245. EXPECT_TRUE(m1.Matches(""));
  1246. EXPECT_FALSE(m1.Matches(NULL));
  1247. const Matcher<const string&> m2 = StartsWith("Hi");
  1248. EXPECT_TRUE(m2.Matches("Hi"));
  1249. EXPECT_TRUE(m2.Matches("Hi Hi!"));
  1250. EXPECT_TRUE(m2.Matches("High"));
  1251. EXPECT_FALSE(m2.Matches("H"));
  1252. EXPECT_FALSE(m2.Matches(" Hi"));
  1253. }
  1254. TEST(StartsWithTest, CanDescribeSelf) {
  1255. Matcher<const std::string> m = StartsWith("Hi");
  1256. EXPECT_EQ("starts with \"Hi\"", Describe(m));
  1257. }
  1258. // Tests EndsWith(s).
  1259. TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
  1260. const Matcher<const char*> m1 = EndsWith("");
  1261. EXPECT_TRUE(m1.Matches("Hi"));
  1262. EXPECT_TRUE(m1.Matches(""));
  1263. EXPECT_FALSE(m1.Matches(NULL));
  1264. const Matcher<const string&> m2 = EndsWith(string("Hi"));
  1265. EXPECT_TRUE(m2.Matches("Hi"));
  1266. EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
  1267. EXPECT_TRUE(m2.Matches("Super Hi"));
  1268. EXPECT_FALSE(m2.Matches("i"));
  1269. EXPECT_FALSE(m2.Matches("Hi "));
  1270. }
  1271. TEST(EndsWithTest, CanDescribeSelf) {
  1272. Matcher<const std::string> m = EndsWith("Hi");
  1273. EXPECT_EQ("ends with \"Hi\"", Describe(m));
  1274. }
  1275. // Tests MatchesRegex().
  1276. TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
  1277. const Matcher<const char*> m1 = MatchesRegex("a.*z");
  1278. EXPECT_TRUE(m1.Matches("az"));
  1279. EXPECT_TRUE(m1.Matches("abcz"));
  1280. EXPECT_FALSE(m1.Matches(NULL));
  1281. const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
  1282. EXPECT_TRUE(m2.Matches("azbz"));
  1283. EXPECT_FALSE(m2.Matches("az1"));
  1284. EXPECT_FALSE(m2.Matches("1az"));
  1285. }
  1286. TEST(MatchesRegexTest, CanDescribeSelf) {
  1287. Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
  1288. EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
  1289. Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
  1290. EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
  1291. }
  1292. // Tests ContainsRegex().
  1293. TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
  1294. const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
  1295. EXPECT_TRUE(m1.Matches("az"));
  1296. EXPECT_TRUE(m1.Matches("0abcz1"));
  1297. EXPECT_FALSE(m1.Matches(NULL));
  1298. const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
  1299. EXPECT_TRUE(m2.Matches("azbz"));
  1300. EXPECT_TRUE(m2.Matches("az1"));
  1301. EXPECT_FALSE(m2.Matches("1a"));
  1302. }
  1303. TEST(ContainsRegexTest, CanDescribeSelf) {
  1304. Matcher<const std::string> m1 = ContainsRegex("Hi.*");
  1305. EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
  1306. Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
  1307. EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
  1308. }
  1309. // Tests for wide strings.
  1310. #if GTEST_HAS_STD_WSTRING
  1311. TEST(StdWideStrEqTest, MatchesEqual) {
  1312. Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
  1313. EXPECT_TRUE(m.Matches(L"Hello"));
  1314. EXPECT_FALSE(m.Matches(L"hello"));
  1315. EXPECT_FALSE(m.Matches(NULL));
  1316. Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
  1317. EXPECT_TRUE(m2.Matches(L"Hello"));
  1318. EXPECT_FALSE(m2.Matches(L"Hi"));
  1319. Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1320. EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
  1321. EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
  1322. ::std::wstring str(L"01204500800");
  1323. str[3] = L'\0';
  1324. Matcher<const ::std::wstring&> m4 = StrEq(str);
  1325. EXPECT_TRUE(m4.Matches(str));
  1326. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1327. Matcher<const ::std::wstring&> m5 = StrEq(str);
  1328. EXPECT_TRUE(m5.Matches(str));
  1329. }
  1330. TEST(StdWideStrEqTest, CanDescribeSelf) {
  1331. Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
  1332. EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
  1333. Describe(m));
  1334. Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1335. EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
  1336. Describe(m2));
  1337. ::std::wstring str(L"01204500800");
  1338. str[3] = L'\0';
  1339. Matcher<const ::std::wstring&> m4 = StrEq(str);
  1340. EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
  1341. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1342. Matcher<const ::std::wstring&> m5 = StrEq(str);
  1343. EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
  1344. }
  1345. TEST(StdWideStrNeTest, MatchesUnequalString) {
  1346. Matcher<const wchar_t*> m = StrNe(L"Hello");
  1347. EXPECT_TRUE(m.Matches(L""));
  1348. EXPECT_TRUE(m.Matches(NULL));
  1349. EXPECT_FALSE(m.Matches(L"Hello"));
  1350. Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
  1351. EXPECT_TRUE(m2.Matches(L"hello"));
  1352. EXPECT_FALSE(m2.Matches(L"Hello"));
  1353. }
  1354. TEST(StdWideStrNeTest, CanDescribeSelf) {
  1355. Matcher<const wchar_t*> m = StrNe(L"Hi");
  1356. EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
  1357. }
  1358. TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
  1359. Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
  1360. EXPECT_TRUE(m.Matches(L"Hello"));
  1361. EXPECT_TRUE(m.Matches(L"hello"));
  1362. EXPECT_FALSE(m.Matches(L"Hi"));
  1363. EXPECT_FALSE(m.Matches(NULL));
  1364. Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
  1365. EXPECT_TRUE(m2.Matches(L"hello"));
  1366. EXPECT_FALSE(m2.Matches(L"Hi"));
  1367. }
  1368. TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
  1369. ::std::wstring str1(L"oabocdooeoo");
  1370. ::std::wstring str2(L"OABOCDOOEOO");
  1371. Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
  1372. EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
  1373. str1[3] = str2[3] = L'\0';
  1374. Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
  1375. EXPECT_TRUE(m1.Matches(str2));
  1376. str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
  1377. str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
  1378. Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
  1379. str1[9] = str2[9] = L'\0';
  1380. EXPECT_FALSE(m2.Matches(str2));
  1381. Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
  1382. EXPECT_TRUE(m3.Matches(str2));
  1383. EXPECT_FALSE(m3.Matches(str2 + L"x"));
  1384. str2.append(1, L'\0');
  1385. EXPECT_FALSE(m3.Matches(str2));
  1386. EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
  1387. }
  1388. TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
  1389. Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
  1390. EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
  1391. }
  1392. TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
  1393. Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
  1394. EXPECT_TRUE(m.Matches(L"Hi"));
  1395. EXPECT_TRUE(m.Matches(NULL));
  1396. EXPECT_FALSE(m.Matches(L"Hello"));
  1397. EXPECT_FALSE(m.Matches(L"hello"));
  1398. Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
  1399. EXPECT_TRUE(m2.Matches(L""));
  1400. EXPECT_FALSE(m2.Matches(L"Hello"));
  1401. }
  1402. TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
  1403. Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
  1404. EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
  1405. }
  1406. // Tests that HasSubstr() works for matching wstring-typed values.
  1407. TEST(StdWideHasSubstrTest, WorksForStringClasses) {
  1408. const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
  1409. EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
  1410. EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
  1411. const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
  1412. EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
  1413. EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
  1414. }
  1415. // Tests that HasSubstr() works for matching C-wide-string-typed values.
  1416. TEST(StdWideHasSubstrTest, WorksForCStrings) {
  1417. const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
  1418. EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
  1419. EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
  1420. EXPECT_FALSE(m1.Matches(NULL));
  1421. const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
  1422. EXPECT_TRUE(m2.Matches(L"I love food."));
  1423. EXPECT_FALSE(m2.Matches(L"tofo"));
  1424. EXPECT_FALSE(m2.Matches(NULL));
  1425. }
  1426. // Tests that HasSubstr(s) describes itself properly.
  1427. TEST(StdWideHasSubstrTest, CanDescribeSelf) {
  1428. Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
  1429. EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
  1430. }
  1431. // Tests StartsWith(s).
  1432. TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
  1433. const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
  1434. EXPECT_TRUE(m1.Matches(L"Hi"));
  1435. EXPECT_TRUE(m1.Matches(L""));
  1436. EXPECT_FALSE(m1.Matches(NULL));
  1437. const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
  1438. EXPECT_TRUE(m2.Matches(L"Hi"));
  1439. EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
  1440. EXPECT_TRUE(m2.Matches(L"High"));
  1441. EXPECT_FALSE(m2.Matches(L"H"));
  1442. EXPECT_FALSE(m2.Matches(L" Hi"));
  1443. }
  1444. TEST(StdWideStartsWithTest, CanDescribeSelf) {
  1445. Matcher<const ::std::wstring> m = StartsWith(L"Hi");
  1446. EXPECT_EQ("starts with L\"Hi\"", Describe(m));
  1447. }
  1448. // Tests EndsWith(s).
  1449. TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
  1450. const Matcher<const wchar_t*> m1 = EndsWith(L"");
  1451. EXPECT_TRUE(m1.Matches(L"Hi"));
  1452. EXPECT_TRUE(m1.Matches(L""));
  1453. EXPECT_FALSE(m1.Matches(NULL));
  1454. const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
  1455. EXPECT_TRUE(m2.Matches(L"Hi"));
  1456. EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
  1457. EXPECT_TRUE(m2.Matches(L"Super Hi"));
  1458. EXPECT_FALSE(m2.Matches(L"i"));
  1459. EXPECT_FALSE(m2.Matches(L"Hi "));
  1460. }
  1461. TEST(StdWideEndsWithTest, CanDescribeSelf) {
  1462. Matcher<const ::std::wstring> m = EndsWith(L"Hi");
  1463. EXPECT_EQ("ends with L\"Hi\"", Describe(m));
  1464. }
  1465. #endif // GTEST_HAS_STD_WSTRING
  1466. #if GTEST_HAS_GLOBAL_WSTRING
  1467. TEST(GlobalWideStrEqTest, MatchesEqual) {
  1468. Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
  1469. EXPECT_TRUE(m.Matches(L"Hello"));
  1470. EXPECT_FALSE(m.Matches(L"hello"));
  1471. EXPECT_FALSE(m.Matches(NULL));
  1472. Matcher<const ::wstring&> m2 = StrEq(L"Hello");
  1473. EXPECT_TRUE(m2.Matches(L"Hello"));
  1474. EXPECT_FALSE(m2.Matches(L"Hi"));
  1475. Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1476. EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
  1477. EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
  1478. ::wstring str(L"01204500800");
  1479. str[3] = L'\0';
  1480. Matcher<const ::wstring&> m4 = StrEq(str);
  1481. EXPECT_TRUE(m4.Matches(str));
  1482. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1483. Matcher<const ::wstring&> m5 = StrEq(str);
  1484. EXPECT_TRUE(m5.Matches(str));
  1485. }
  1486. TEST(GlobalWideStrEqTest, CanDescribeSelf) {
  1487. Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
  1488. EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
  1489. Describe(m));
  1490. Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1491. EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
  1492. Describe(m2));
  1493. ::wstring str(L"01204500800");
  1494. str[3] = L'\0';
  1495. Matcher<const ::wstring&> m4 = StrEq(str);
  1496. EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
  1497. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1498. Matcher<const ::wstring&> m5 = StrEq(str);
  1499. EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
  1500. }
  1501. TEST(GlobalWideStrNeTest, MatchesUnequalString) {
  1502. Matcher<const wchar_t*> m = StrNe(L"Hello");
  1503. EXPECT_TRUE(m.Matches(L""));
  1504. EXPECT_TRUE(m.Matches(NULL));
  1505. EXPECT_FALSE(m.Matches(L"Hello"));
  1506. Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
  1507. EXPECT_TRUE(m2.Matches(L"hello"));
  1508. EXPECT_FALSE(m2.Matches(L"Hello"));
  1509. }
  1510. TEST(GlobalWideStrNeTest, CanDescribeSelf) {
  1511. Matcher<const wchar_t*> m = StrNe(L"Hi");
  1512. EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
  1513. }
  1514. TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
  1515. Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
  1516. EXPECT_TRUE(m.Matches(L"Hello"));
  1517. EXPECT_TRUE(m.Matches(L"hello"));
  1518. EXPECT_FALSE(m.Matches(L"Hi"));
  1519. EXPECT_FALSE(m.Matches(NULL));
  1520. Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
  1521. EXPECT_TRUE(m2.Matches(L"hello"));
  1522. EXPECT_FALSE(m2.Matches(L"Hi"));
  1523. }
  1524. TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
  1525. ::wstring str1(L"oabocdooeoo");
  1526. ::wstring str2(L"OABOCDOOEOO");
  1527. Matcher<const ::wstring&> m0 = StrCaseEq(str1);
  1528. EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
  1529. str1[3] = str2[3] = L'\0';
  1530. Matcher<const ::wstring&> m1 = StrCaseEq(str1);
  1531. EXPECT_TRUE(m1.Matches(str2));
  1532. str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
  1533. str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
  1534. Matcher<const ::wstring&> m2 = StrCaseEq(str1);
  1535. str1[9] = str2[9] = L'\0';
  1536. EXPECT_FALSE(m2.Matches(str2));
  1537. Matcher<const ::wstring&> m3 = StrCaseEq(str1);
  1538. EXPECT_TRUE(m3.Matches(str2));
  1539. EXPECT_FALSE(m3.Matches(str2 + L"x"));
  1540. str2.append(1, L'\0');
  1541. EXPECT_FALSE(m3.Matches(str2));
  1542. EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
  1543. }
  1544. TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
  1545. Matcher< ::wstring> m = StrCaseEq(L"Hi");
  1546. EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
  1547. }
  1548. TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
  1549. Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
  1550. EXPECT_TRUE(m.Matches(L"Hi"));
  1551. EXPECT_TRUE(m.Matches(NULL));
  1552. EXPECT_FALSE(m.Matches(L"Hello"));
  1553. EXPECT_FALSE(m.Matches(L"hello"));
  1554. Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
  1555. EXPECT_TRUE(m2.Matches(L""));
  1556. EXPECT_FALSE(m2.Matches(L"Hello"));
  1557. }
  1558. TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
  1559. Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
  1560. EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
  1561. }
  1562. // Tests that HasSubstr() works for matching wstring-typed values.
  1563. TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
  1564. const Matcher< ::wstring> m1 = HasSubstr(L"foo");
  1565. EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
  1566. EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
  1567. const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
  1568. EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
  1569. EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
  1570. }
  1571. // Tests that HasSubstr() works for matching C-wide-string-typed values.
  1572. TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
  1573. const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
  1574. EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
  1575. EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
  1576. EXPECT_FALSE(m1.Matches(NULL));
  1577. const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
  1578. EXPECT_TRUE(m2.Matches(L"I love food."));
  1579. EXPECT_FALSE(m2.Matches(L"tofo"));
  1580. EXPECT_FALSE(m2.Matches(NULL));
  1581. }
  1582. // Tests that HasSubstr(s) describes itself properly.
  1583. TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
  1584. Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
  1585. EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
  1586. }
  1587. // Tests StartsWith(s).
  1588. TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
  1589. const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
  1590. EXPECT_TRUE(m1.Matches(L"Hi"));
  1591. EXPECT_TRUE(m1.Matches(L""));
  1592. EXPECT_FALSE(m1.Matches(NULL));
  1593. const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
  1594. EXPECT_TRUE(m2.Matches(L"Hi"));
  1595. EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
  1596. EXPECT_TRUE(m2.Matches(L"High"));
  1597. EXPECT_FALSE(m2.Matches(L"H"));
  1598. EXPECT_FALSE(m2.Matches(L" Hi"));
  1599. }
  1600. TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
  1601. Matcher<const ::wstring> m = StartsWith(L"Hi");
  1602. EXPECT_EQ("starts with L\"Hi\"", Describe(m));
  1603. }
  1604. // Tests EndsWith(s).
  1605. TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
  1606. const Matcher<const wchar_t*> m1 = EndsWith(L"");
  1607. EXPECT_TRUE(m1.Matches(L"Hi"));
  1608. EXPECT_TRUE(m1.Matches(L""));
  1609. EXPECT_FALSE(m1.Matches(NULL));
  1610. const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
  1611. EXPECT_TRUE(m2.Matches(L"Hi"));
  1612. EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
  1613. EXPECT_TRUE(m2.Matches(L"Super Hi"));
  1614. EXPECT_FALSE(m2.Matches(L"i"));
  1615. EXPECT_FALSE(m2.Matches(L"Hi "));
  1616. }
  1617. TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
  1618. Matcher<const ::wstring> m = EndsWith(L"Hi");
  1619. EXPECT_EQ("ends with L\"Hi\"", Describe(m));
  1620. }
  1621. #endif // GTEST_HAS_GLOBAL_WSTRING
  1622. typedef ::testing::tuple<long, int> Tuple2; // NOLINT
  1623. // Tests that Eq() matches a 2-tuple where the first field == the
  1624. // second field.
  1625. TEST(Eq2Test, MatchesEqualArguments) {
  1626. Matcher<const Tuple2&> m = Eq();
  1627. EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
  1628. EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
  1629. }
  1630. // Tests that Eq() describes itself properly.
  1631. TEST(Eq2Test, CanDescribeSelf) {
  1632. Matcher<const Tuple2&> m = Eq();
  1633. EXPECT_EQ("are an equal pair", Describe(m));
  1634. }
  1635. // Tests that Ge() matches a 2-tuple where the first field >= the
  1636. // second field.
  1637. TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
  1638. Matcher<const Tuple2&> m = Ge();
  1639. EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
  1640. EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
  1641. EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
  1642. }
  1643. // Tests that Ge() describes itself properly.
  1644. TEST(Ge2Test, CanDescribeSelf) {
  1645. Matcher<const Tuple2&> m = Ge();
  1646. EXPECT_EQ("are a pair where the first >= the second", Describe(m));
  1647. }
  1648. // Tests that Gt() matches a 2-tuple where the first field > the
  1649. // second field.
  1650. TEST(Gt2Test, MatchesGreaterThanArguments) {
  1651. Matcher<const Tuple2&> m = Gt();
  1652. EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
  1653. EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
  1654. EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
  1655. }
  1656. // Tests that Gt() describes itself properly.
  1657. TEST(Gt2Test, CanDescribeSelf) {
  1658. Matcher<const Tuple2&> m = Gt();
  1659. EXPECT_EQ("are a pair where the first > the second", Describe(m));
  1660. }
  1661. // Tests that Le() matches a 2-tuple where the first field <= the
  1662. // second field.
  1663. TEST(Le2Test, MatchesLessThanOrEqualArguments) {
  1664. Matcher<const Tuple2&> m = Le();
  1665. EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
  1666. EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
  1667. EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
  1668. }
  1669. // Tests that Le() describes itself properly.
  1670. TEST(Le2Test, CanDescribeSelf) {
  1671. Matcher<const Tuple2&> m = Le();
  1672. EXPECT_EQ("are a pair where the first <= the second", Describe(m));
  1673. }
  1674. // Tests that Lt() matches a 2-tuple where the first field < the
  1675. // second field.
  1676. TEST(Lt2Test, MatchesLessThanArguments) {
  1677. Matcher<const Tuple2&> m = Lt();
  1678. EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
  1679. EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
  1680. EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
  1681. }
  1682. // Tests that Lt() describes itself properly.
  1683. TEST(Lt2Test, CanDescribeSelf) {
  1684. Matcher<const Tuple2&> m = Lt();
  1685. EXPECT_EQ("are a pair where the first < the second", Describe(m));
  1686. }
  1687. // Tests that Ne() matches a 2-tuple where the first field != the
  1688. // second field.
  1689. TEST(Ne2Test, MatchesUnequalArguments) {
  1690. Matcher<const Tuple2&> m = Ne();
  1691. EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
  1692. EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
  1693. EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
  1694. }
  1695. // Tests that Ne() describes itself properly.
  1696. TEST(Ne2Test, CanDescribeSelf) {
  1697. Matcher<const Tuple2&> m = Ne();
  1698. EXPECT_EQ("are an unequal pair", Describe(m));
  1699. }
  1700. // Tests that Not(m) matches any value that doesn't match m.
  1701. TEST(NotTest, NegatesMatcher) {
  1702. Matcher<int> m;
  1703. m = Not(Eq(2));
  1704. EXPECT_TRUE(m.Matches(3));
  1705. EXPECT_FALSE(m.Matches(2));
  1706. }
  1707. // Tests that Not(m) describes itself properly.
  1708. TEST(NotTest, CanDescribeSelf) {
  1709. Matcher<int> m = Not(Eq(5));
  1710. EXPECT_EQ("isn't equal to 5", Describe(m));
  1711. }
  1712. // Tests that monomorphic matchers are safely cast by the Not matcher.
  1713. TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
  1714. // greater_than_5 is a monomorphic matcher.
  1715. Matcher<int> greater_than_5 = Gt(5);
  1716. Matcher<const int&> m = Not(greater_than_5);
  1717. Matcher<int&> m2 = Not(greater_than_5);
  1718. Matcher<int&> m3 = Not(m);
  1719. }
  1720. // Helper to allow easy testing of AllOf matchers with num parameters.
  1721. void AllOfMatches(int num, const Matcher<int>& m) {
  1722. SCOPED_TRACE(Describe(m));
  1723. EXPECT_TRUE(m.Matches(0));
  1724. for (int i = 1; i <= num; ++i) {
  1725. EXPECT_FALSE(m.Matches(i));
  1726. }
  1727. EXPECT_TRUE(m.Matches(num + 1));
  1728. }
  1729. // Tests that AllOf(m1, ..., mn) matches any value that matches all of
  1730. // the given matchers.
  1731. TEST(AllOfTest, MatchesWhenAllMatch) {
  1732. Matcher<int> m;
  1733. m = AllOf(Le(2), Ge(1));
  1734. EXPECT_TRUE(m.Matches(1));
  1735. EXPECT_TRUE(m.Matches(2));
  1736. EXPECT_FALSE(m.Matches(0));
  1737. EXPECT_FALSE(m.Matches(3));
  1738. m = AllOf(Gt(0), Ne(1), Ne(2));
  1739. EXPECT_TRUE(m.Matches(3));
  1740. EXPECT_FALSE(m.Matches(2));
  1741. EXPECT_FALSE(m.Matches(1));
  1742. EXPECT_FALSE(m.Matches(0));
  1743. m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
  1744. EXPECT_TRUE(m.Matches(4));
  1745. EXPECT_FALSE(m.Matches(3));
  1746. EXPECT_FALSE(m.Matches(2));
  1747. EXPECT_FALSE(m.Matches(1));
  1748. EXPECT_FALSE(m.Matches(0));
  1749. m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
  1750. EXPECT_TRUE(m.Matches(0));
  1751. EXPECT_TRUE(m.Matches(1));
  1752. EXPECT_FALSE(m.Matches(3));
  1753. // The following tests for varying number of sub-matchers. Due to the way
  1754. // the sub-matchers are handled it is enough to test every sub-matcher once
  1755. // with sub-matchers using the same matcher type. Varying matcher types are
  1756. // checked for above.
  1757. AllOfMatches(2, AllOf(Ne(1), Ne(2)));
  1758. AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
  1759. AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
  1760. AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
  1761. AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
  1762. AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
  1763. AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
  1764. Ne(8)));
  1765. AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
  1766. Ne(8), Ne(9)));
  1767. AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
  1768. Ne(9), Ne(10)));
  1769. }
  1770. #if GTEST_LANG_CXX11
  1771. // Tests the variadic version of the AllOfMatcher.
  1772. TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
  1773. // Make sure AllOf is defined in the right namespace and does not depend on
  1774. // ADL.
  1775. ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
  1776. Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
  1777. Ne(9), Ne(10), Ne(11));
  1778. EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
  1779. AllOfMatches(11, m);
  1780. AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
  1781. Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
  1782. Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
  1783. Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
  1784. Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
  1785. Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
  1786. Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
  1787. Ne(50)));
  1788. }
  1789. #endif // GTEST_LANG_CXX11
  1790. // Tests that AllOf(m1, ..., mn) describes itself properly.
  1791. TEST(AllOfTest, CanDescribeSelf) {
  1792. Matcher<int> m;
  1793. m = AllOf(Le(2), Ge(1));
  1794. EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
  1795. m = AllOf(Gt(0), Ne(1), Ne(2));
  1796. EXPECT_EQ("(is > 0) and "
  1797. "((isn't equal to 1) and "
  1798. "(isn't equal to 2))",
  1799. Describe(m));
  1800. m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
  1801. EXPECT_EQ("((is > 0) and "
  1802. "(isn't equal to 1)) and "
  1803. "((isn't equal to 2) and "
  1804. "(isn't equal to 3))",
  1805. Describe(m));
  1806. m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
  1807. EXPECT_EQ("((is >= 0) and "
  1808. "(is < 10)) and "
  1809. "((isn't equal to 3) and "
  1810. "((isn't equal to 5) and "
  1811. "(isn't equal to 7)))",
  1812. Describe(m));
  1813. }
  1814. // Tests that AllOf(m1, ..., mn) describes its negation properly.
  1815. TEST(AllOfTest, CanDescribeNegation) {
  1816. Matcher<int> m;
  1817. m = AllOf(Le(2), Ge(1));
  1818. EXPECT_EQ("(isn't <= 2) or "
  1819. "(isn't >= 1)",
  1820. DescribeNegation(m));
  1821. m = AllOf(Gt(0), Ne(1), Ne(2));
  1822. EXPECT_EQ("(isn't > 0) or "
  1823. "((is equal to 1) or "
  1824. "(is equal to 2))",
  1825. DescribeNegation(m));
  1826. m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
  1827. EXPECT_EQ("((isn't > 0) or "
  1828. "(is equal to 1)) or "
  1829. "((is equal to 2) or "
  1830. "(is equal to 3))",
  1831. DescribeNegation(m));
  1832. m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
  1833. EXPECT_EQ("((isn't >= 0) or "
  1834. "(isn't < 10)) or "
  1835. "((is equal to 3) or "
  1836. "((is equal to 5) or "
  1837. "(is equal to 7)))",
  1838. DescribeNegation(m));
  1839. }
  1840. // Tests that monomorphic matchers are safely cast by the AllOf matcher.
  1841. TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
  1842. // greater_than_5 and less_than_10 are monomorphic matchers.
  1843. Matcher<int> greater_than_5 = Gt(5);
  1844. Matcher<int> less_than_10 = Lt(10);
  1845. Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
  1846. Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
  1847. Matcher<int&> m3 = AllOf(greater_than_5, m2);
  1848. // Tests that BothOf works when composing itself.
  1849. Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
  1850. Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
  1851. }
  1852. TEST(AllOfTest, ExplainsResult) {
  1853. Matcher<int> m;
  1854. // Successful match. Both matchers need to explain. The second
  1855. // matcher doesn't give an explanation, so only the first matcher's
  1856. // explanation is printed.
  1857. m = AllOf(GreaterThan(10), Lt(30));
  1858. EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
  1859. // Successful match. Both matchers need to explain.
  1860. m = AllOf(GreaterThan(10), GreaterThan(20));
  1861. EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
  1862. Explain(m, 30));
  1863. // Successful match. All matchers need to explain. The second
  1864. // matcher doesn't given an explanation.
  1865. m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
  1866. EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
  1867. Explain(m, 25));
  1868. // Successful match. All matchers need to explain.
  1869. m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
  1870. EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
  1871. "and which is 10 more than 30",
  1872. Explain(m, 40));
  1873. // Failed match. The first matcher, which failed, needs to
  1874. // explain.
  1875. m = AllOf(GreaterThan(10), GreaterThan(20));
  1876. EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
  1877. // Failed match. The second matcher, which failed, needs to
  1878. // explain. Since it doesn't given an explanation, nothing is
  1879. // printed.
  1880. m = AllOf(GreaterThan(10), Lt(30));
  1881. EXPECT_EQ("", Explain(m, 40));
  1882. // Failed match. The second matcher, which failed, needs to
  1883. // explain.
  1884. m = AllOf(GreaterThan(10), GreaterThan(20));
  1885. EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
  1886. }
  1887. // Helper to allow easy testing of AnyOf matchers with num parameters.
  1888. void AnyOfMatches(int num, const Matcher<int>& m) {
  1889. SCOPED_TRACE(Describe(m));
  1890. EXPECT_FALSE(m.Matches(0));
  1891. for (int i = 1; i <= num; ++i) {
  1892. EXPECT_TRUE(m.Matches(i));
  1893. }
  1894. EXPECT_FALSE(m.Matches(num + 1));
  1895. }
  1896. // Tests that AnyOf(m1, ..., mn) matches any value that matches at
  1897. // least one of the given matchers.
  1898. TEST(AnyOfTest, MatchesWhenAnyMatches) {
  1899. Matcher<int> m;
  1900. m = AnyOf(Le(1), Ge(3));
  1901. EXPECT_TRUE(m.Matches(1));
  1902. EXPECT_TRUE(m.Matches(4));
  1903. EXPECT_FALSE(m.Matches(2));
  1904. m = AnyOf(Lt(0), Eq(1), Eq(2));
  1905. EXPECT_TRUE(m.Matches(-1));
  1906. EXPECT_TRUE(m.Matches(1));
  1907. EXPECT_TRUE(m.Matches(2));
  1908. EXPECT_FALSE(m.Matches(0));
  1909. m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
  1910. EXPECT_TRUE(m.Matches(-1));
  1911. EXPECT_TRUE(m.Matches(1));
  1912. EXPECT_TRUE(m.Matches(2));
  1913. EXPECT_TRUE(m.Matches(3));
  1914. EXPECT_FALSE(m.Matches(0));
  1915. m = AnyOf(Le(0), Gt(10), 3, 5, 7);
  1916. EXPECT_TRUE(m.Matches(0));
  1917. EXPECT_TRUE(m.Matches(11));
  1918. EXPECT_TRUE(m.Matches(3));
  1919. EXPECT_FALSE(m.Matches(2));
  1920. // The following tests for varying number of sub-matchers. Due to the way
  1921. // the sub-matchers are handled it is enough to test every sub-matcher once
  1922. // with sub-matchers using the same matcher type. Varying matcher types are
  1923. // checked for above.
  1924. AnyOfMatches(2, AnyOf(1, 2));
  1925. AnyOfMatches(3, AnyOf(1, 2, 3));
  1926. AnyOfMatches(4, AnyOf(1, 2, 3, 4));
  1927. AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
  1928. AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
  1929. AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
  1930. AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
  1931. AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
  1932. AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
  1933. }
  1934. #if GTEST_LANG_CXX11
  1935. // Tests the variadic version of the AnyOfMatcher.
  1936. TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
  1937. // Also make sure AnyOf is defined in the right namespace and does not depend
  1938. // on ADL.
  1939. Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
  1940. EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
  1941. AnyOfMatches(11, m);
  1942. AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  1943. 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  1944. 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
  1945. 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  1946. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
  1947. }
  1948. #endif // GTEST_LANG_CXX11
  1949. // Tests that AnyOf(m1, ..., mn) describes itself properly.
  1950. TEST(AnyOfTest, CanDescribeSelf) {
  1951. Matcher<int> m;
  1952. m = AnyOf(Le(1), Ge(3));
  1953. EXPECT_EQ("(is <= 1) or (is >= 3)",
  1954. Describe(m));
  1955. m = AnyOf(Lt(0), Eq(1), Eq(2));
  1956. EXPECT_EQ("(is < 0) or "
  1957. "((is equal to 1) or (is equal to 2))",
  1958. Describe(m));
  1959. m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
  1960. EXPECT_EQ("((is < 0) or "
  1961. "(is equal to 1)) or "
  1962. "((is equal to 2) or "
  1963. "(is equal to 3))",
  1964. Describe(m));
  1965. m = AnyOf(Le(0), Gt(10), 3, 5, 7);
  1966. EXPECT_EQ("((is <= 0) or "
  1967. "(is > 10)) or "
  1968. "((is equal to 3) or "
  1969. "((is equal to 5) or "
  1970. "(is equal to 7)))",
  1971. Describe(m));
  1972. }
  1973. // Tests that AnyOf(m1, ..., mn) describes its negation properly.
  1974. TEST(AnyOfTest, CanDescribeNegation) {
  1975. Matcher<int> m;
  1976. m = AnyOf(Le(1), Ge(3));
  1977. EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
  1978. DescribeNegation(m));
  1979. m = AnyOf(Lt(0), Eq(1), Eq(2));
  1980. EXPECT_EQ("(isn't < 0) and "
  1981. "((isn't equal to 1) and (isn't equal to 2))",
  1982. DescribeNegation(m));
  1983. m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
  1984. EXPECT_EQ("((isn't < 0) and "
  1985. "(isn't equal to 1)) and "
  1986. "((isn't equal to 2) and "
  1987. "(isn't equal to 3))",
  1988. DescribeNegation(m));
  1989. m = AnyOf(Le(0), Gt(10), 3, 5, 7);
  1990. EXPECT_EQ("((isn't <= 0) and "
  1991. "(isn't > 10)) and "
  1992. "((isn't equal to 3) and "
  1993. "((isn't equal to 5) and "
  1994. "(isn't equal to 7)))",
  1995. DescribeNegation(m));
  1996. }
  1997. // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
  1998. TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
  1999. // greater_than_5 and less_than_10 are monomorphic matchers.
  2000. Matcher<int> greater_than_5 = Gt(5);
  2001. Matcher<int> less_than_10 = Lt(10);
  2002. Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
  2003. Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
  2004. Matcher<int&> m3 = AnyOf(greater_than_5, m2);
  2005. // Tests that EitherOf works when composing itself.
  2006. Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
  2007. Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
  2008. }
  2009. TEST(AnyOfTest, ExplainsResult) {
  2010. Matcher<int> m;
  2011. // Failed match. Both matchers need to explain. The second
  2012. // matcher doesn't give an explanation, so only the first matcher's
  2013. // explanation is printed.
  2014. m = AnyOf(GreaterThan(10), Lt(0));
  2015. EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
  2016. // Failed match. Both matchers need to explain.
  2017. m = AnyOf(GreaterThan(10), GreaterThan(20));
  2018. EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
  2019. Explain(m, 5));
  2020. // Failed match. All matchers need to explain. The second
  2021. // matcher doesn't given an explanation.
  2022. m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
  2023. EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
  2024. Explain(m, 5));
  2025. // Failed match. All matchers need to explain.
  2026. m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
  2027. EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
  2028. "and which is 25 less than 30",
  2029. Explain(m, 5));
  2030. // Successful match. The first matcher, which succeeded, needs to
  2031. // explain.
  2032. m = AnyOf(GreaterThan(10), GreaterThan(20));
  2033. EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
  2034. // Successful match. The second matcher, which succeeded, needs to
  2035. // explain. Since it doesn't given an explanation, nothing is
  2036. // printed.
  2037. m = AnyOf(GreaterThan(10), Lt(30));
  2038. EXPECT_EQ("", Explain(m, 0));
  2039. // Successful match. The second matcher, which succeeded, needs to
  2040. // explain.
  2041. m = AnyOf(GreaterThan(30), GreaterThan(20));
  2042. EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
  2043. }
  2044. // The following predicate function and predicate functor are for
  2045. // testing the Truly(predicate) matcher.
  2046. // Returns non-zero if the input is positive. Note that the return
  2047. // type of this function is not bool. It's OK as Truly() accepts any
  2048. // unary function or functor whose return type can be implicitly
  2049. // converted to bool.
  2050. int IsPositive(double x) {
  2051. return x > 0 ? 1 : 0;
  2052. }
  2053. // This functor returns true if the input is greater than the given
  2054. // number.
  2055. class IsGreaterThan {
  2056. public:
  2057. explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
  2058. bool operator()(int n) const { return n > threshold_; }
  2059. private:
  2060. int threshold_;
  2061. };
  2062. // For testing Truly().
  2063. const int foo = 0;
  2064. // This predicate returns true iff the argument references foo and has
  2065. // a zero value.
  2066. bool ReferencesFooAndIsZero(const int& n) {
  2067. return (&n == &foo) && (n == 0);
  2068. }
  2069. // Tests that Truly(predicate) matches what satisfies the given
  2070. // predicate.
  2071. TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
  2072. Matcher<double> m = Truly(IsPositive);
  2073. EXPECT_TRUE(m.Matches(2.0));
  2074. EXPECT_FALSE(m.Matches(-1.5));
  2075. }
  2076. // Tests that Truly(predicate_functor) works too.
  2077. TEST(TrulyTest, CanBeUsedWithFunctor) {
  2078. Matcher<int> m = Truly(IsGreaterThan(5));
  2079. EXPECT_TRUE(m.Matches(6));
  2080. EXPECT_FALSE(m.Matches(4));
  2081. }
  2082. // A class that can be implicitly converted to bool.
  2083. class ConvertibleToBool {
  2084. public:
  2085. explicit ConvertibleToBool(int number) : number_(number) {}
  2086. operator bool() const { return number_ != 0; }
  2087. private:
  2088. int number_;
  2089. };
  2090. ConvertibleToBool IsNotZero(int number) {
  2091. return ConvertibleToBool(number);
  2092. }
  2093. // Tests that the predicate used in Truly() may return a class that's
  2094. // implicitly convertible to bool, even when the class has no
  2095. // operator!().
  2096. TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
  2097. Matcher<int> m = Truly(IsNotZero);
  2098. EXPECT_TRUE(m.Matches(1));
  2099. EXPECT_FALSE(m.Matches(0));
  2100. }
  2101. // Tests that Truly(predicate) can describe itself properly.
  2102. TEST(TrulyTest, CanDescribeSelf) {
  2103. Matcher<double> m = Truly(IsPositive);
  2104. EXPECT_EQ("satisfies the given predicate",
  2105. Describe(m));
  2106. }
  2107. // Tests that Truly(predicate) works when the matcher takes its
  2108. // argument by reference.
  2109. TEST(TrulyTest, WorksForByRefArguments) {
  2110. Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
  2111. EXPECT_TRUE(m.Matches(foo));
  2112. int n = 0;
  2113. EXPECT_FALSE(m.Matches(n));
  2114. }
  2115. // Tests that Matches(m) is a predicate satisfied by whatever that
  2116. // matches matcher m.
  2117. TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
  2118. EXPECT_TRUE(Matches(Ge(0))(1));
  2119. EXPECT_FALSE(Matches(Eq('a'))('b'));
  2120. }
  2121. // Tests that Matches(m) works when the matcher takes its argument by
  2122. // reference.
  2123. TEST(MatchesTest, WorksOnByRefArguments) {
  2124. int m = 0, n = 0;
  2125. EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
  2126. EXPECT_FALSE(Matches(Ref(m))(n));
  2127. }
  2128. // Tests that a Matcher on non-reference type can be used in
  2129. // Matches().
  2130. TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
  2131. Matcher<int> eq5 = Eq(5);
  2132. EXPECT_TRUE(Matches(eq5)(5));
  2133. EXPECT_FALSE(Matches(eq5)(2));
  2134. }
  2135. // Tests Value(value, matcher). Since Value() is a simple wrapper for
  2136. // Matches(), which has been tested already, we don't spend a lot of
  2137. // effort on testing Value().
  2138. TEST(ValueTest, WorksWithPolymorphicMatcher) {
  2139. EXPECT_TRUE(Value("hi", StartsWith("h")));
  2140. EXPECT_FALSE(Value(5, Gt(10)));
  2141. }
  2142. TEST(ValueTest, WorksWithMonomorphicMatcher) {
  2143. const Matcher<int> is_zero = Eq(0);
  2144. EXPECT_TRUE(Value(0, is_zero));
  2145. EXPECT_FALSE(Value('a', is_zero));
  2146. int n = 0;
  2147. const Matcher<const int&> ref_n = Ref(n);
  2148. EXPECT_TRUE(Value(n, ref_n));
  2149. EXPECT_FALSE(Value(1, ref_n));
  2150. }
  2151. TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
  2152. StringMatchResultListener listener1;
  2153. EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
  2154. EXPECT_EQ("% 2 == 0", listener1.str());
  2155. StringMatchResultListener listener2;
  2156. EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
  2157. EXPECT_EQ("", listener2.str());
  2158. }
  2159. TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
  2160. const Matcher<int> is_even = PolymorphicIsEven();
  2161. StringMatchResultListener listener1;
  2162. EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
  2163. EXPECT_EQ("% 2 == 0", listener1.str());
  2164. const Matcher<const double&> is_zero = Eq(0);
  2165. StringMatchResultListener listener2;
  2166. EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
  2167. EXPECT_EQ("", listener2.str());
  2168. }
  2169. MATCHER_P(Really, inner_matcher, "") {
  2170. return ExplainMatchResult(inner_matcher, arg, result_listener);
  2171. }
  2172. TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
  2173. EXPECT_THAT(0, Really(Eq(0)));
  2174. }
  2175. TEST(AllArgsTest, WorksForTuple) {
  2176. EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
  2177. EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
  2178. }
  2179. TEST(AllArgsTest, WorksForNonTuple) {
  2180. EXPECT_THAT(42, AllArgs(Gt(0)));
  2181. EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
  2182. }
  2183. class AllArgsHelper {
  2184. public:
  2185. AllArgsHelper() {}
  2186. MOCK_METHOD2(Helper, int(char x, int y));
  2187. private:
  2188. GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
  2189. };
  2190. TEST(AllArgsTest, WorksInWithClause) {
  2191. AllArgsHelper helper;
  2192. ON_CALL(helper, Helper(_, _))
  2193. .With(AllArgs(Lt()))
  2194. .WillByDefault(Return(1));
  2195. EXPECT_CALL(helper, Helper(_, _));
  2196. EXPECT_CALL(helper, Helper(_, _))
  2197. .With(AllArgs(Gt()))
  2198. .WillOnce(Return(2));
  2199. EXPECT_EQ(1, helper.Helper('\1', 2));
  2200. EXPECT_EQ(2, helper.Helper('a', 1));
  2201. }
  2202. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
  2203. // matches the matcher.
  2204. TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
  2205. ASSERT_THAT(5, Ge(2)) << "This should succeed.";
  2206. ASSERT_THAT("Foo", EndsWith("oo"));
  2207. EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
  2208. EXPECT_THAT("Hello", StartsWith("Hell"));
  2209. }
  2210. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
  2211. // doesn't match the matcher.
  2212. TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
  2213. // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
  2214. // which cannot reference auto variables.
  2215. static unsigned short n; // NOLINT
  2216. n = 5;
  2217. // VC++ prior to version 8.0 SP1 has a bug where it will not see any
  2218. // functions declared in the namespace scope from within nested classes.
  2219. // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
  2220. // namespace-level functions invoked inside them need to be explicitly
  2221. // resolved.
  2222. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
  2223. "Value of: n\n"
  2224. "Expected: is > 10\n"
  2225. " Actual: 5" + OfType("unsigned short"));
  2226. n = 0;
  2227. EXPECT_NONFATAL_FAILURE(
  2228. EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
  2229. "Value of: n\n"
  2230. "Expected: (is <= 7) and (is >= 5)\n"
  2231. " Actual: 0" + OfType("unsigned short"));
  2232. }
  2233. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
  2234. // has a reference type.
  2235. TEST(MatcherAssertionTest, WorksForByRefArguments) {
  2236. // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
  2237. // reference auto variables.
  2238. static int n;
  2239. n = 0;
  2240. EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
  2241. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
  2242. "Value of: n\n"
  2243. "Expected: does not reference the variable @");
  2244. // Tests the "Actual" part.
  2245. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
  2246. "Actual: 0" + OfType("int") + ", which is located @");
  2247. }
  2248. #if !GTEST_OS_SYMBIAN
  2249. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
  2250. // monomorphic.
  2251. // ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
  2252. // Symbian compiler: it tries to compile
  2253. // template<T, U> class MatcherCastImpl { ...
  2254. // virtual bool MatchAndExplain(T x, ...) const {
  2255. // return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
  2256. // with U == string and T == const char*
  2257. // With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
  2258. // the compiler silently crashes with no output.
  2259. // If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
  2260. // the code compiles but the converted string is bogus.
  2261. TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
  2262. Matcher<const char*> starts_with_he = StartsWith("he");
  2263. ASSERT_THAT("hello", starts_with_he);
  2264. Matcher<const string&> ends_with_ok = EndsWith("ok");
  2265. ASSERT_THAT("book", ends_with_ok);
  2266. const string bad = "bad";
  2267. EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
  2268. "Value of: bad\n"
  2269. "Expected: ends with \"ok\"\n"
  2270. " Actual: \"bad\"");
  2271. Matcher<int> is_greater_than_5 = Gt(5);
  2272. EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
  2273. "Value of: 5\n"
  2274. "Expected: is > 5\n"
  2275. " Actual: 5" + OfType("int"));
  2276. }
  2277. #endif // !GTEST_OS_SYMBIAN
  2278. // Tests floating-point matchers.
  2279. template <typename RawType>
  2280. class FloatingPointTest : public testing::Test {
  2281. protected:
  2282. typedef testing::internal::FloatingPoint<RawType> Floating;
  2283. typedef typename Floating::Bits Bits;
  2284. FloatingPointTest()
  2285. : max_ulps_(Floating::kMaxUlps),
  2286. zero_bits_(Floating(0).bits()),
  2287. one_bits_(Floating(1).bits()),
  2288. infinity_bits_(Floating(Floating::Infinity()).bits()),
  2289. close_to_positive_zero_(AsBits(zero_bits_ + max_ulps_/2)),
  2290. close_to_negative_zero_(AsBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
  2291. further_from_negative_zero_(-AsBits(
  2292. zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
  2293. close_to_one_(AsBits(one_bits_ + max_ulps_)),
  2294. further_from_one_(AsBits(one_bits_ + max_ulps_ + 1)),
  2295. infinity_(Floating::Infinity()),
  2296. close_to_infinity_(AsBits(infinity_bits_ - max_ulps_)),
  2297. further_from_infinity_(AsBits(infinity_bits_ - max_ulps_ - 1)),
  2298. max_(Floating::Max()),
  2299. nan1_(AsBits(Floating::kExponentBitMask | 1)),
  2300. nan2_(AsBits(Floating::kExponentBitMask | 200)) {
  2301. }
  2302. void TestSize() {
  2303. EXPECT_EQ(sizeof(RawType), sizeof(Bits));
  2304. }
  2305. // A battery of tests for FloatingEqMatcher::Matches.
  2306. // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
  2307. void TestMatches(
  2308. testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
  2309. Matcher<RawType> m1 = matcher_maker(0.0);
  2310. EXPECT_TRUE(m1.Matches(-0.0));
  2311. EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
  2312. EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
  2313. EXPECT_FALSE(m1.Matches(1.0));
  2314. Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
  2315. EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
  2316. Matcher<RawType> m3 = matcher_maker(1.0);
  2317. EXPECT_TRUE(m3.Matches(close_to_one_));
  2318. EXPECT_FALSE(m3.Matches(further_from_one_));
  2319. // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
  2320. EXPECT_FALSE(m3.Matches(0.0));
  2321. Matcher<RawType> m4 = matcher_maker(-infinity_);
  2322. EXPECT_TRUE(m4.Matches(-close_to_infinity_));
  2323. Matcher<RawType> m5 = matcher_maker(infinity_);
  2324. EXPECT_TRUE(m5.Matches(close_to_infinity_));
  2325. // This is interesting as the representations of infinity_ and nan1_
  2326. // are only 1 DLP apart.
  2327. EXPECT_FALSE(m5.Matches(nan1_));
  2328. // matcher_maker can produce a Matcher<const RawType&>, which is needed in
  2329. // some cases.
  2330. Matcher<const RawType&> m6 = matcher_maker(0.0);
  2331. EXPECT_TRUE(m6.Matches(-0.0));
  2332. EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
  2333. EXPECT_FALSE(m6.Matches(1.0));
  2334. // matcher_maker can produce a Matcher<RawType&>, which is needed in some
  2335. // cases.
  2336. Matcher<RawType&> m7 = matcher_maker(0.0);
  2337. RawType x = 0.0;
  2338. EXPECT_TRUE(m7.Matches(x));
  2339. x = 0.01f;
  2340. EXPECT_FALSE(m7.Matches(x));
  2341. }
  2342. // Pre-calculated numbers to be used by the tests.
  2343. const size_t max_ulps_;
  2344. const Bits zero_bits_; // The bits that represent 0.0.
  2345. const Bits one_bits_; // The bits that represent 1.0.
  2346. const Bits infinity_bits_; // The bits that represent +infinity.
  2347. // Some numbers close to 0.0.
  2348. const RawType close_to_positive_zero_;
  2349. const RawType close_to_negative_zero_;
  2350. const RawType further_from_negative_zero_;
  2351. // Some numbers close to 1.0.
  2352. const RawType close_to_one_;
  2353. const RawType further_from_one_;
  2354. // Some numbers close to +infinity.
  2355. const RawType infinity_;
  2356. const RawType close_to_infinity_;
  2357. const RawType further_from_infinity_;
  2358. // Maximum representable value that's not infinity.
  2359. const RawType max_;
  2360. // Some NaNs.
  2361. const RawType nan1_;
  2362. const RawType nan2_;
  2363. private:
  2364. template <typename T>
  2365. static RawType AsBits(T value) {
  2366. return Floating::ReinterpretBits(static_cast<Bits>(value));
  2367. }
  2368. };
  2369. // Tests floating-point matchers with fixed epsilons.
  2370. template <typename RawType>
  2371. class FloatingPointNearTest : public FloatingPointTest<RawType> {
  2372. protected:
  2373. typedef FloatingPointTest<RawType> ParentType;
  2374. // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
  2375. // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
  2376. void TestNearMatches(
  2377. testing::internal::FloatingEqMatcher<RawType>
  2378. (*matcher_maker)(RawType, RawType)) {
  2379. Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
  2380. EXPECT_TRUE(m1.Matches(0.0));
  2381. EXPECT_TRUE(m1.Matches(-0.0));
  2382. EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
  2383. EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
  2384. EXPECT_FALSE(m1.Matches(1.0));
  2385. Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
  2386. EXPECT_TRUE(m2.Matches(0.0));
  2387. EXPECT_TRUE(m2.Matches(-0.0));
  2388. EXPECT_TRUE(m2.Matches(1.0));
  2389. EXPECT_TRUE(m2.Matches(-1.0));
  2390. EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
  2391. EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
  2392. // Check that inf matches inf, regardless of the of the specified max
  2393. // absolute error.
  2394. Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
  2395. EXPECT_TRUE(m3.Matches(ParentType::infinity_));
  2396. EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
  2397. EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
  2398. Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
  2399. EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
  2400. EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
  2401. EXPECT_FALSE(m4.Matches(ParentType::infinity_));
  2402. // Test various overflow scenarios.
  2403. Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
  2404. EXPECT_TRUE(m5.Matches(ParentType::max_));
  2405. EXPECT_FALSE(m5.Matches(-ParentType::max_));
  2406. Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
  2407. EXPECT_FALSE(m6.Matches(ParentType::max_));
  2408. EXPECT_TRUE(m6.Matches(-ParentType::max_));
  2409. Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
  2410. EXPECT_TRUE(m7.Matches(ParentType::max_));
  2411. EXPECT_FALSE(m7.Matches(-ParentType::max_));
  2412. Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
  2413. EXPECT_FALSE(m8.Matches(ParentType::max_));
  2414. EXPECT_TRUE(m8.Matches(-ParentType::max_));
  2415. // The difference between max() and -max() normally overflows to infinity,
  2416. // but it should still match if the max_abs_error is also infinity.
  2417. Matcher<RawType> m9 = matcher_maker(
  2418. ParentType::max_, ParentType::infinity_);
  2419. EXPECT_TRUE(m8.Matches(-ParentType::max_));
  2420. // matcher_maker can produce a Matcher<const RawType&>, which is needed in
  2421. // some cases.
  2422. Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
  2423. EXPECT_TRUE(m10.Matches(-0.0));
  2424. EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
  2425. EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
  2426. // matcher_maker can produce a Matcher<RawType&>, which is needed in some
  2427. // cases.
  2428. Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
  2429. RawType x = 0.0;
  2430. EXPECT_TRUE(m11.Matches(x));
  2431. x = 1.0f;
  2432. EXPECT_TRUE(m11.Matches(x));
  2433. x = -1.0f;
  2434. EXPECT_TRUE(m11.Matches(x));
  2435. x = 1.1f;
  2436. EXPECT_FALSE(m11.Matches(x));
  2437. x = -1.1f;
  2438. EXPECT_FALSE(m11.Matches(x));
  2439. }
  2440. };
  2441. // Instantiate FloatingPointTest for testing floats.
  2442. typedef FloatingPointTest<float> FloatTest;
  2443. TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
  2444. TestMatches(&FloatEq);
  2445. }
  2446. TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
  2447. TestMatches(&NanSensitiveFloatEq);
  2448. }
  2449. TEST_F(FloatTest, FloatEqCannotMatchNaN) {
  2450. // FloatEq never matches NaN.
  2451. Matcher<float> m = FloatEq(nan1_);
  2452. EXPECT_FALSE(m.Matches(nan1_));
  2453. EXPECT_FALSE(m.Matches(nan2_));
  2454. EXPECT_FALSE(m.Matches(1.0));
  2455. }
  2456. TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
  2457. // NanSensitiveFloatEq will match NaN.
  2458. Matcher<float> m = NanSensitiveFloatEq(nan1_);
  2459. EXPECT_TRUE(m.Matches(nan1_));
  2460. EXPECT_TRUE(m.Matches(nan2_));
  2461. EXPECT_FALSE(m.Matches(1.0));
  2462. }
  2463. TEST_F(FloatTest, FloatEqCanDescribeSelf) {
  2464. Matcher<float> m1 = FloatEq(2.0f);
  2465. EXPECT_EQ("is approximately 2", Describe(m1));
  2466. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2467. Matcher<float> m2 = FloatEq(0.5f);
  2468. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2469. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2470. Matcher<float> m3 = FloatEq(nan1_);
  2471. EXPECT_EQ("never matches", Describe(m3));
  2472. EXPECT_EQ("is anything", DescribeNegation(m3));
  2473. }
  2474. TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
  2475. Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
  2476. EXPECT_EQ("is approximately 2", Describe(m1));
  2477. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2478. Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
  2479. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2480. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2481. Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
  2482. EXPECT_EQ("is NaN", Describe(m3));
  2483. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2484. }
  2485. // Instantiate FloatingPointTest for testing floats with a user-specified
  2486. // max absolute error.
  2487. typedef FloatingPointNearTest<float> FloatNearTest;
  2488. TEST_F(FloatNearTest, FloatNearMatches) {
  2489. TestNearMatches(&FloatNear);
  2490. }
  2491. TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
  2492. TestNearMatches(&NanSensitiveFloatNear);
  2493. }
  2494. TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
  2495. Matcher<float> m1 = FloatNear(2.0f, 0.5f);
  2496. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2497. EXPECT_EQ(
  2498. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2499. Matcher<float> m2 = FloatNear(0.5f, 0.5f);
  2500. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2501. EXPECT_EQ(
  2502. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2503. Matcher<float> m3 = FloatNear(nan1_, 0.0);
  2504. EXPECT_EQ("never matches", Describe(m3));
  2505. EXPECT_EQ("is anything", DescribeNegation(m3));
  2506. }
  2507. TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
  2508. Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
  2509. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2510. EXPECT_EQ(
  2511. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2512. Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
  2513. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2514. EXPECT_EQ(
  2515. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2516. Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
  2517. EXPECT_EQ("is NaN", Describe(m3));
  2518. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2519. }
  2520. TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
  2521. // FloatNear never matches NaN.
  2522. Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
  2523. EXPECT_FALSE(m.Matches(nan1_));
  2524. EXPECT_FALSE(m.Matches(nan2_));
  2525. EXPECT_FALSE(m.Matches(1.0));
  2526. }
  2527. TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
  2528. // NanSensitiveFloatNear will match NaN.
  2529. Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
  2530. EXPECT_TRUE(m.Matches(nan1_));
  2531. EXPECT_TRUE(m.Matches(nan2_));
  2532. EXPECT_FALSE(m.Matches(1.0));
  2533. }
  2534. // Instantiate FloatingPointTest for testing doubles.
  2535. typedef FloatingPointTest<double> DoubleTest;
  2536. TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
  2537. TestMatches(&DoubleEq);
  2538. }
  2539. TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
  2540. TestMatches(&NanSensitiveDoubleEq);
  2541. }
  2542. TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
  2543. // DoubleEq never matches NaN.
  2544. Matcher<double> m = DoubleEq(nan1_);
  2545. EXPECT_FALSE(m.Matches(nan1_));
  2546. EXPECT_FALSE(m.Matches(nan2_));
  2547. EXPECT_FALSE(m.Matches(1.0));
  2548. }
  2549. TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
  2550. // NanSensitiveDoubleEq will match NaN.
  2551. Matcher<double> m = NanSensitiveDoubleEq(nan1_);
  2552. EXPECT_TRUE(m.Matches(nan1_));
  2553. EXPECT_TRUE(m.Matches(nan2_));
  2554. EXPECT_FALSE(m.Matches(1.0));
  2555. }
  2556. TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
  2557. Matcher<double> m1 = DoubleEq(2.0);
  2558. EXPECT_EQ("is approximately 2", Describe(m1));
  2559. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2560. Matcher<double> m2 = DoubleEq(0.5);
  2561. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2562. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2563. Matcher<double> m3 = DoubleEq(nan1_);
  2564. EXPECT_EQ("never matches", Describe(m3));
  2565. EXPECT_EQ("is anything", DescribeNegation(m3));
  2566. }
  2567. TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
  2568. Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
  2569. EXPECT_EQ("is approximately 2", Describe(m1));
  2570. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2571. Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
  2572. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2573. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2574. Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
  2575. EXPECT_EQ("is NaN", Describe(m3));
  2576. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2577. }
  2578. // Instantiate FloatingPointTest for testing floats with a user-specified
  2579. // max absolute error.
  2580. typedef FloatingPointNearTest<double> DoubleNearTest;
  2581. TEST_F(DoubleNearTest, DoubleNearMatches) {
  2582. TestNearMatches(&DoubleNear);
  2583. }
  2584. TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
  2585. TestNearMatches(&NanSensitiveDoubleNear);
  2586. }
  2587. TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
  2588. Matcher<double> m1 = DoubleNear(2.0, 0.5);
  2589. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2590. EXPECT_EQ(
  2591. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2592. Matcher<double> m2 = DoubleNear(0.5, 0.5);
  2593. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2594. EXPECT_EQ(
  2595. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2596. Matcher<double> m3 = DoubleNear(nan1_, 0.0);
  2597. EXPECT_EQ("never matches", Describe(m3));
  2598. EXPECT_EQ("is anything", DescribeNegation(m3));
  2599. }
  2600. TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
  2601. EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
  2602. EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
  2603. EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
  2604. const string explanation = Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
  2605. // Different C++ implementations may print floating-point numbers
  2606. // slightly differently.
  2607. EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
  2608. explanation == "which is 1.2e-010 from 2.1") // MSVC
  2609. << " where explanation is \"" << explanation << "\".";
  2610. }
  2611. TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
  2612. Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
  2613. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2614. EXPECT_EQ(
  2615. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2616. Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
  2617. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2618. EXPECT_EQ(
  2619. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2620. Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
  2621. EXPECT_EQ("is NaN", Describe(m3));
  2622. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2623. }
  2624. TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
  2625. // DoubleNear never matches NaN.
  2626. Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
  2627. EXPECT_FALSE(m.Matches(nan1_));
  2628. EXPECT_FALSE(m.Matches(nan2_));
  2629. EXPECT_FALSE(m.Matches(1.0));
  2630. }
  2631. TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
  2632. // NanSensitiveDoubleNear will match NaN.
  2633. Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
  2634. EXPECT_TRUE(m.Matches(nan1_));
  2635. EXPECT_TRUE(m.Matches(nan2_));
  2636. EXPECT_FALSE(m.Matches(1.0));
  2637. }
  2638. TEST(PointeeTest, RawPointer) {
  2639. const Matcher<int*> m = Pointee(Ge(0));
  2640. int n = 1;
  2641. EXPECT_TRUE(m.Matches(&n));
  2642. n = -1;
  2643. EXPECT_FALSE(m.Matches(&n));
  2644. EXPECT_FALSE(m.Matches(NULL));
  2645. }
  2646. TEST(PointeeTest, RawPointerToConst) {
  2647. const Matcher<const double*> m = Pointee(Ge(0));
  2648. double x = 1;
  2649. EXPECT_TRUE(m.Matches(&x));
  2650. x = -1;
  2651. EXPECT_FALSE(m.Matches(&x));
  2652. EXPECT_FALSE(m.Matches(NULL));
  2653. }
  2654. TEST(PointeeTest, ReferenceToConstRawPointer) {
  2655. const Matcher<int* const &> m = Pointee(Ge(0));
  2656. int n = 1;
  2657. EXPECT_TRUE(m.Matches(&n));
  2658. n = -1;
  2659. EXPECT_FALSE(m.Matches(&n));
  2660. EXPECT_FALSE(m.Matches(NULL));
  2661. }
  2662. TEST(PointeeTest, ReferenceToNonConstRawPointer) {
  2663. const Matcher<double* &> m = Pointee(Ge(0));
  2664. double x = 1.0;
  2665. double* p = &x;
  2666. EXPECT_TRUE(m.Matches(p));
  2667. x = -1;
  2668. EXPECT_FALSE(m.Matches(p));
  2669. p = NULL;
  2670. EXPECT_FALSE(m.Matches(p));
  2671. }
  2672. MATCHER_P(FieldIIs, inner_matcher, "") {
  2673. return ExplainMatchResult(inner_matcher, arg.i, result_listener);
  2674. }
  2675. #if GTEST_HAS_RTTI
  2676. TEST(WhenDynamicCastToTest, SameType) {
  2677. Derived derived;
  2678. derived.i = 4;
  2679. // Right type. A pointer is passed down.
  2680. Base* as_base_ptr = &derived;
  2681. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
  2682. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
  2683. EXPECT_THAT(as_base_ptr,
  2684. Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
  2685. }
  2686. TEST(WhenDynamicCastToTest, WrongTypes) {
  2687. Base base;
  2688. Derived derived;
  2689. OtherDerived other_derived;
  2690. // Wrong types. NULL is passed.
  2691. EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
  2692. EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
  2693. Base* as_base_ptr = &derived;
  2694. EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
  2695. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
  2696. as_base_ptr = &other_derived;
  2697. EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
  2698. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
  2699. }
  2700. TEST(WhenDynamicCastToTest, AlreadyNull) {
  2701. // Already NULL.
  2702. Base* as_base_ptr = NULL;
  2703. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
  2704. }
  2705. struct AmbiguousCastTypes {
  2706. class VirtualDerived : public virtual Base {};
  2707. class DerivedSub1 : public VirtualDerived {};
  2708. class DerivedSub2 : public VirtualDerived {};
  2709. class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
  2710. };
  2711. TEST(WhenDynamicCastToTest, AmbiguousCast) {
  2712. AmbiguousCastTypes::DerivedSub1 sub1;
  2713. AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
  2714. // Multiply derived from Base. dynamic_cast<> returns NULL.
  2715. Base* as_base_ptr =
  2716. static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
  2717. EXPECT_THAT(as_base_ptr,
  2718. WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
  2719. as_base_ptr = &sub1;
  2720. EXPECT_THAT(
  2721. as_base_ptr,
  2722. WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
  2723. }
  2724. TEST(WhenDynamicCastToTest, Describe) {
  2725. Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
  2726. const string prefix =
  2727. "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
  2728. EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
  2729. EXPECT_EQ(prefix + "does not point to a value that is anything",
  2730. DescribeNegation(matcher));
  2731. }
  2732. TEST(WhenDynamicCastToTest, Explain) {
  2733. Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
  2734. Base* null = NULL;
  2735. EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
  2736. Derived derived;
  2737. EXPECT_TRUE(matcher.Matches(&derived));
  2738. EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
  2739. // With references, the matcher itself can fail. Test for that one.
  2740. Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
  2741. EXPECT_THAT(Explain(ref_matcher, derived),
  2742. HasSubstr("which cannot be dynamic_cast"));
  2743. }
  2744. TEST(WhenDynamicCastToTest, GoodReference) {
  2745. Derived derived;
  2746. derived.i = 4;
  2747. Base& as_base_ref = derived;
  2748. EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
  2749. EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
  2750. }
  2751. TEST(WhenDynamicCastToTest, BadReference) {
  2752. Derived derived;
  2753. Base& as_base_ref = derived;
  2754. EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
  2755. }
  2756. #endif // GTEST_HAS_RTTI
  2757. // Minimal const-propagating pointer.
  2758. template <typename T>
  2759. class ConstPropagatingPtr {
  2760. public:
  2761. typedef T element_type;
  2762. ConstPropagatingPtr() : val_() {}
  2763. explicit ConstPropagatingPtr(T* t) : val_(t) {}
  2764. ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
  2765. T* get() { return val_; }
  2766. T& operator*() { return *val_; }
  2767. // Most smart pointers return non-const T* and T& from the next methods.
  2768. const T* get() const { return val_; }
  2769. const T& operator*() const { return *val_; }
  2770. private:
  2771. T* val_;
  2772. };
  2773. TEST(PointeeTest, WorksWithConstPropagatingPointers) {
  2774. const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
  2775. int three = 3;
  2776. const ConstPropagatingPtr<int> co(&three);
  2777. ConstPropagatingPtr<int> o(&three);
  2778. EXPECT_TRUE(m.Matches(o));
  2779. EXPECT_TRUE(m.Matches(co));
  2780. *o = 6;
  2781. EXPECT_FALSE(m.Matches(o));
  2782. EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
  2783. }
  2784. TEST(PointeeTest, NeverMatchesNull) {
  2785. const Matcher<const char*> m = Pointee(_);
  2786. EXPECT_FALSE(m.Matches(NULL));
  2787. }
  2788. // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
  2789. TEST(PointeeTest, MatchesAgainstAValue) {
  2790. const Matcher<int*> m = Pointee(5);
  2791. int n = 5;
  2792. EXPECT_TRUE(m.Matches(&n));
  2793. n = -1;
  2794. EXPECT_FALSE(m.Matches(&n));
  2795. EXPECT_FALSE(m.Matches(NULL));
  2796. }
  2797. TEST(PointeeTest, CanDescribeSelf) {
  2798. const Matcher<int*> m = Pointee(Gt(3));
  2799. EXPECT_EQ("points to a value that is > 3", Describe(m));
  2800. EXPECT_EQ("does not point to a value that is > 3",
  2801. DescribeNegation(m));
  2802. }
  2803. TEST(PointeeTest, CanExplainMatchResult) {
  2804. const Matcher<const string*> m = Pointee(StartsWith("Hi"));
  2805. EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
  2806. const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
  2807. long n = 3; // NOLINT
  2808. EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
  2809. Explain(m2, &n));
  2810. }
  2811. TEST(PointeeTest, AlwaysExplainsPointee) {
  2812. const Matcher<int*> m = Pointee(0);
  2813. int n = 42;
  2814. EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
  2815. }
  2816. // An uncopyable class.
  2817. class Uncopyable {
  2818. public:
  2819. Uncopyable() : value_(-1) {}
  2820. explicit Uncopyable(int a_value) : value_(a_value) {}
  2821. int value() const { return value_; }
  2822. void set_value(int i) { value_ = i; }
  2823. private:
  2824. int value_;
  2825. GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
  2826. };
  2827. // Returns true iff x.value() is positive.
  2828. bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
  2829. MATCHER_P(UncopyableIs, inner_matcher, "") {
  2830. return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
  2831. }
  2832. // A user-defined struct for testing Field().
  2833. struct AStruct {
  2834. AStruct() : x(0), y(1.0), z(5), p(NULL) {}
  2835. AStruct(const AStruct& rhs)
  2836. : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
  2837. int x; // A non-const field.
  2838. const double y; // A const field.
  2839. Uncopyable z; // An uncopyable field.
  2840. const char* p; // A pointer field.
  2841. private:
  2842. GTEST_DISALLOW_ASSIGN_(AStruct);
  2843. };
  2844. // A derived struct for testing Field().
  2845. struct DerivedStruct : public AStruct {
  2846. char ch;
  2847. private:
  2848. GTEST_DISALLOW_ASSIGN_(DerivedStruct);
  2849. };
  2850. // Tests that Field(&Foo::field, ...) works when field is non-const.
  2851. TEST(FieldTest, WorksForNonConstField) {
  2852. Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
  2853. AStruct a;
  2854. EXPECT_TRUE(m.Matches(a));
  2855. a.x = -1;
  2856. EXPECT_FALSE(m.Matches(a));
  2857. }
  2858. // Tests that Field(&Foo::field, ...) works when field is const.
  2859. TEST(FieldTest, WorksForConstField) {
  2860. AStruct a;
  2861. Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
  2862. EXPECT_TRUE(m.Matches(a));
  2863. m = Field(&AStruct::y, Le(0.0));
  2864. EXPECT_FALSE(m.Matches(a));
  2865. }
  2866. // Tests that Field(&Foo::field, ...) works when field is not copyable.
  2867. TEST(FieldTest, WorksForUncopyableField) {
  2868. AStruct a;
  2869. Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
  2870. EXPECT_TRUE(m.Matches(a));
  2871. m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
  2872. EXPECT_FALSE(m.Matches(a));
  2873. }
  2874. // Tests that Field(&Foo::field, ...) works when field is a pointer.
  2875. TEST(FieldTest, WorksForPointerField) {
  2876. // Matching against NULL.
  2877. Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
  2878. AStruct a;
  2879. EXPECT_TRUE(m.Matches(a));
  2880. a.p = "hi";
  2881. EXPECT_FALSE(m.Matches(a));
  2882. // Matching a pointer that is not NULL.
  2883. m = Field(&AStruct::p, StartsWith("hi"));
  2884. a.p = "hill";
  2885. EXPECT_TRUE(m.Matches(a));
  2886. a.p = "hole";
  2887. EXPECT_FALSE(m.Matches(a));
  2888. }
  2889. // Tests that Field() works when the object is passed by reference.
  2890. TEST(FieldTest, WorksForByRefArgument) {
  2891. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  2892. AStruct a;
  2893. EXPECT_TRUE(m.Matches(a));
  2894. a.x = -1;
  2895. EXPECT_FALSE(m.Matches(a));
  2896. }
  2897. // Tests that Field(&Foo::field, ...) works when the argument's type
  2898. // is a sub-type of Foo.
  2899. TEST(FieldTest, WorksForArgumentOfSubType) {
  2900. // Note that the matcher expects DerivedStruct but we say AStruct
  2901. // inside Field().
  2902. Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
  2903. DerivedStruct d;
  2904. EXPECT_TRUE(m.Matches(d));
  2905. d.x = -1;
  2906. EXPECT_FALSE(m.Matches(d));
  2907. }
  2908. // Tests that Field(&Foo::field, m) works when field's type and m's
  2909. // argument type are compatible but not the same.
  2910. TEST(FieldTest, WorksForCompatibleMatcherType) {
  2911. // The field is an int, but the inner matcher expects a signed char.
  2912. Matcher<const AStruct&> m = Field(&AStruct::x,
  2913. Matcher<signed char>(Ge(0)));
  2914. AStruct a;
  2915. EXPECT_TRUE(m.Matches(a));
  2916. a.x = -1;
  2917. EXPECT_FALSE(m.Matches(a));
  2918. }
  2919. // Tests that Field() can describe itself.
  2920. TEST(FieldTest, CanDescribeSelf) {
  2921. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  2922. EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
  2923. EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
  2924. }
  2925. // Tests that Field() can explain the match result.
  2926. TEST(FieldTest, CanExplainMatchResult) {
  2927. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  2928. AStruct a;
  2929. a.x = 1;
  2930. EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
  2931. m = Field(&AStruct::x, GreaterThan(0));
  2932. EXPECT_EQ(
  2933. "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
  2934. Explain(m, a));
  2935. }
  2936. // Tests that Field() works when the argument is a pointer to const.
  2937. TEST(FieldForPointerTest, WorksForPointerToConst) {
  2938. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  2939. AStruct a;
  2940. EXPECT_TRUE(m.Matches(&a));
  2941. a.x = -1;
  2942. EXPECT_FALSE(m.Matches(&a));
  2943. }
  2944. // Tests that Field() works when the argument is a pointer to non-const.
  2945. TEST(FieldForPointerTest, WorksForPointerToNonConst) {
  2946. Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
  2947. AStruct a;
  2948. EXPECT_TRUE(m.Matches(&a));
  2949. a.x = -1;
  2950. EXPECT_FALSE(m.Matches(&a));
  2951. }
  2952. // Tests that Field() works when the argument is a reference to a const pointer.
  2953. TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
  2954. Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
  2955. AStruct a;
  2956. EXPECT_TRUE(m.Matches(&a));
  2957. a.x = -1;
  2958. EXPECT_FALSE(m.Matches(&a));
  2959. }
  2960. // Tests that Field() does not match the NULL pointer.
  2961. TEST(FieldForPointerTest, DoesNotMatchNull) {
  2962. Matcher<const AStruct*> m = Field(&AStruct::x, _);
  2963. EXPECT_FALSE(m.Matches(NULL));
  2964. }
  2965. // Tests that Field(&Foo::field, ...) works when the argument's type
  2966. // is a sub-type of const Foo*.
  2967. TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
  2968. // Note that the matcher expects DerivedStruct but we say AStruct
  2969. // inside Field().
  2970. Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
  2971. DerivedStruct d;
  2972. EXPECT_TRUE(m.Matches(&d));
  2973. d.x = -1;
  2974. EXPECT_FALSE(m.Matches(&d));
  2975. }
  2976. // Tests that Field() can describe itself when used to match a pointer.
  2977. TEST(FieldForPointerTest, CanDescribeSelf) {
  2978. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  2979. EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
  2980. EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
  2981. }
  2982. // Tests that Field() can explain the result of matching a pointer.
  2983. TEST(FieldForPointerTest, CanExplainMatchResult) {
  2984. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  2985. AStruct a;
  2986. a.x = 1;
  2987. EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
  2988. EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
  2989. Explain(m, &a));
  2990. m = Field(&AStruct::x, GreaterThan(0));
  2991. EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
  2992. ", which is 1 more than 0", Explain(m, &a));
  2993. }
  2994. // A user-defined class for testing Property().
  2995. class AClass {
  2996. public:
  2997. AClass() : n_(0) {}
  2998. // A getter that returns a non-reference.
  2999. int n() const { return n_; }
  3000. void set_n(int new_n) { n_ = new_n; }
  3001. // A getter that returns a reference to const.
  3002. const string& s() const { return s_; }
  3003. void set_s(const string& new_s) { s_ = new_s; }
  3004. // A getter that returns a reference to non-const.
  3005. double& x() const { return x_; }
  3006. private:
  3007. int n_;
  3008. string s_;
  3009. static double x_;
  3010. };
  3011. double AClass::x_ = 0.0;
  3012. // A derived class for testing Property().
  3013. class DerivedClass : public AClass {
  3014. public:
  3015. int k() const { return k_; }
  3016. private:
  3017. int k_;
  3018. };
  3019. // Tests that Property(&Foo::property, ...) works when property()
  3020. // returns a non-reference.
  3021. TEST(PropertyTest, WorksForNonReferenceProperty) {
  3022. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  3023. AClass a;
  3024. a.set_n(1);
  3025. EXPECT_TRUE(m.Matches(a));
  3026. a.set_n(-1);
  3027. EXPECT_FALSE(m.Matches(a));
  3028. }
  3029. // Tests that Property(&Foo::property, ...) works when property()
  3030. // returns a reference to const.
  3031. TEST(PropertyTest, WorksForReferenceToConstProperty) {
  3032. Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
  3033. AClass a;
  3034. a.set_s("hill");
  3035. EXPECT_TRUE(m.Matches(a));
  3036. a.set_s("hole");
  3037. EXPECT_FALSE(m.Matches(a));
  3038. }
  3039. // Tests that Property(&Foo::property, ...) works when property()
  3040. // returns a reference to non-const.
  3041. TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
  3042. double x = 0.0;
  3043. AClass a;
  3044. Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
  3045. EXPECT_FALSE(m.Matches(a));
  3046. m = Property(&AClass::x, Not(Ref(x)));
  3047. EXPECT_TRUE(m.Matches(a));
  3048. }
  3049. // Tests that Property(&Foo::property, ...) works when the argument is
  3050. // passed by value.
  3051. TEST(PropertyTest, WorksForByValueArgument) {
  3052. Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
  3053. AClass a;
  3054. a.set_s("hill");
  3055. EXPECT_TRUE(m.Matches(a));
  3056. a.set_s("hole");
  3057. EXPECT_FALSE(m.Matches(a));
  3058. }
  3059. // Tests that Property(&Foo::property, ...) works when the argument's
  3060. // type is a sub-type of Foo.
  3061. TEST(PropertyTest, WorksForArgumentOfSubType) {
  3062. // The matcher expects a DerivedClass, but inside the Property() we
  3063. // say AClass.
  3064. Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
  3065. DerivedClass d;
  3066. d.set_n(1);
  3067. EXPECT_TRUE(m.Matches(d));
  3068. d.set_n(-1);
  3069. EXPECT_FALSE(m.Matches(d));
  3070. }
  3071. // Tests that Property(&Foo::property, m) works when property()'s type
  3072. // and m's argument type are compatible but different.
  3073. TEST(PropertyTest, WorksForCompatibleMatcherType) {
  3074. // n() returns an int but the inner matcher expects a signed char.
  3075. Matcher<const AClass&> m = Property(&AClass::n,
  3076. Matcher<signed char>(Ge(0)));
  3077. AClass a;
  3078. EXPECT_TRUE(m.Matches(a));
  3079. a.set_n(-1);
  3080. EXPECT_FALSE(m.Matches(a));
  3081. }
  3082. // Tests that Property() can describe itself.
  3083. TEST(PropertyTest, CanDescribeSelf) {
  3084. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  3085. EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
  3086. EXPECT_EQ("is an object whose given property isn't >= 0",
  3087. DescribeNegation(m));
  3088. }
  3089. // Tests that Property() can explain the match result.
  3090. TEST(PropertyTest, CanExplainMatchResult) {
  3091. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  3092. AClass a;
  3093. a.set_n(1);
  3094. EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
  3095. m = Property(&AClass::n, GreaterThan(0));
  3096. EXPECT_EQ(
  3097. "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
  3098. Explain(m, a));
  3099. }
  3100. // Tests that Property() works when the argument is a pointer to const.
  3101. TEST(PropertyForPointerTest, WorksForPointerToConst) {
  3102. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  3103. AClass a;
  3104. a.set_n(1);
  3105. EXPECT_TRUE(m.Matches(&a));
  3106. a.set_n(-1);
  3107. EXPECT_FALSE(m.Matches(&a));
  3108. }
  3109. // Tests that Property() works when the argument is a pointer to non-const.
  3110. TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
  3111. Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
  3112. AClass a;
  3113. a.set_s("hill");
  3114. EXPECT_TRUE(m.Matches(&a));
  3115. a.set_s("hole");
  3116. EXPECT_FALSE(m.Matches(&a));
  3117. }
  3118. // Tests that Property() works when the argument is a reference to a
  3119. // const pointer.
  3120. TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
  3121. Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
  3122. AClass a;
  3123. a.set_s("hill");
  3124. EXPECT_TRUE(m.Matches(&a));
  3125. a.set_s("hole");
  3126. EXPECT_FALSE(m.Matches(&a));
  3127. }
  3128. // Tests that Property() does not match the NULL pointer.
  3129. TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
  3130. Matcher<const AClass*> m = Property(&AClass::x, _);
  3131. EXPECT_FALSE(m.Matches(NULL));
  3132. }
  3133. // Tests that Property(&Foo::property, ...) works when the argument's
  3134. // type is a sub-type of const Foo*.
  3135. TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
  3136. // The matcher expects a DerivedClass, but inside the Property() we
  3137. // say AClass.
  3138. Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
  3139. DerivedClass d;
  3140. d.set_n(1);
  3141. EXPECT_TRUE(m.Matches(&d));
  3142. d.set_n(-1);
  3143. EXPECT_FALSE(m.Matches(&d));
  3144. }
  3145. // Tests that Property() can describe itself when used to match a pointer.
  3146. TEST(PropertyForPointerTest, CanDescribeSelf) {
  3147. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  3148. EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
  3149. EXPECT_EQ("is an object whose given property isn't >= 0",
  3150. DescribeNegation(m));
  3151. }
  3152. // Tests that Property() can explain the result of matching a pointer.
  3153. TEST(PropertyForPointerTest, CanExplainMatchResult) {
  3154. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  3155. AClass a;
  3156. a.set_n(1);
  3157. EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
  3158. EXPECT_EQ(
  3159. "which points to an object whose given property is 1" + OfType("int"),
  3160. Explain(m, &a));
  3161. m = Property(&AClass::n, GreaterThan(0));
  3162. EXPECT_EQ("which points to an object whose given property is 1" +
  3163. OfType("int") + ", which is 1 more than 0",
  3164. Explain(m, &a));
  3165. }
  3166. // Tests ResultOf.
  3167. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3168. // function pointer.
  3169. string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
  3170. TEST(ResultOfTest, WorksForFunctionPointers) {
  3171. Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
  3172. EXPECT_TRUE(matcher.Matches(1));
  3173. EXPECT_FALSE(matcher.Matches(2));
  3174. }
  3175. // Tests that ResultOf() can describe itself.
  3176. TEST(ResultOfTest, CanDescribeItself) {
  3177. Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
  3178. EXPECT_EQ("is mapped by the given callable to a value that "
  3179. "is equal to \"foo\"", Describe(matcher));
  3180. EXPECT_EQ("is mapped by the given callable to a value that "
  3181. "isn't equal to \"foo\"", DescribeNegation(matcher));
  3182. }
  3183. // Tests that ResultOf() can explain the match result.
  3184. int IntFunction(int input) { return input == 42 ? 80 : 90; }
  3185. TEST(ResultOfTest, CanExplainMatchResult) {
  3186. Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
  3187. EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
  3188. Explain(matcher, 36));
  3189. matcher = ResultOf(&IntFunction, GreaterThan(85));
  3190. EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
  3191. ", which is 5 more than 85", Explain(matcher, 36));
  3192. }
  3193. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  3194. // returns a non-reference.
  3195. TEST(ResultOfTest, WorksForNonReferenceResults) {
  3196. Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
  3197. EXPECT_TRUE(matcher.Matches(42));
  3198. EXPECT_FALSE(matcher.Matches(36));
  3199. }
  3200. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  3201. // returns a reference to non-const.
  3202. double& DoubleFunction(double& input) { return input; } // NOLINT
  3203. Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
  3204. return obj;
  3205. }
  3206. TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
  3207. double x = 3.14;
  3208. double x2 = x;
  3209. Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
  3210. EXPECT_TRUE(matcher.Matches(x));
  3211. EXPECT_FALSE(matcher.Matches(x2));
  3212. // Test that ResultOf works with uncopyable objects
  3213. Uncopyable obj(0);
  3214. Uncopyable obj2(0);
  3215. Matcher<Uncopyable&> matcher2 =
  3216. ResultOf(&RefUncopyableFunction, Ref(obj));
  3217. EXPECT_TRUE(matcher2.Matches(obj));
  3218. EXPECT_FALSE(matcher2.Matches(obj2));
  3219. }
  3220. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  3221. // returns a reference to const.
  3222. const string& StringFunction(const string& input) { return input; }
  3223. TEST(ResultOfTest, WorksForReferenceToConstResults) {
  3224. string s = "foo";
  3225. string s2 = s;
  3226. Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
  3227. EXPECT_TRUE(matcher.Matches(s));
  3228. EXPECT_FALSE(matcher.Matches(s2));
  3229. }
  3230. // Tests that ResultOf(f, m) works when f(x) and m's
  3231. // argument types are compatible but different.
  3232. TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
  3233. // IntFunction() returns int but the inner matcher expects a signed char.
  3234. Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
  3235. EXPECT_TRUE(matcher.Matches(36));
  3236. EXPECT_FALSE(matcher.Matches(42));
  3237. }
  3238. // Tests that the program aborts when ResultOf is passed
  3239. // a NULL function pointer.
  3240. TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
  3241. EXPECT_DEATH_IF_SUPPORTED(
  3242. ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
  3243. "NULL function pointer is passed into ResultOf\\(\\)\\.");
  3244. }
  3245. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3246. // function reference.
  3247. TEST(ResultOfTest, WorksForFunctionReferences) {
  3248. Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
  3249. EXPECT_TRUE(matcher.Matches(1));
  3250. EXPECT_FALSE(matcher.Matches(2));
  3251. }
  3252. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3253. // function object.
  3254. struct Functor : public ::std::unary_function<int, string> {
  3255. result_type operator()(argument_type input) const {
  3256. return IntToStringFunction(input);
  3257. }
  3258. };
  3259. TEST(ResultOfTest, WorksForFunctors) {
  3260. Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
  3261. EXPECT_TRUE(matcher.Matches(1));
  3262. EXPECT_FALSE(matcher.Matches(2));
  3263. }
  3264. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3265. // functor with more then one operator() defined. ResultOf() must work
  3266. // for each defined operator().
  3267. struct PolymorphicFunctor {
  3268. typedef int result_type;
  3269. int operator()(int n) { return n; }
  3270. int operator()(const char* s) { return static_cast<int>(strlen(s)); }
  3271. };
  3272. TEST(ResultOfTest, WorksForPolymorphicFunctors) {
  3273. Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
  3274. EXPECT_TRUE(matcher_int.Matches(10));
  3275. EXPECT_FALSE(matcher_int.Matches(2));
  3276. Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
  3277. EXPECT_TRUE(matcher_string.Matches("long string"));
  3278. EXPECT_FALSE(matcher_string.Matches("shrt"));
  3279. }
  3280. const int* ReferencingFunction(const int& n) { return &n; }
  3281. struct ReferencingFunctor {
  3282. typedef const int* result_type;
  3283. result_type operator()(const int& n) { return &n; }
  3284. };
  3285. TEST(ResultOfTest, WorksForReferencingCallables) {
  3286. const int n = 1;
  3287. const int n2 = 1;
  3288. Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
  3289. EXPECT_TRUE(matcher2.Matches(n));
  3290. EXPECT_FALSE(matcher2.Matches(n2));
  3291. Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
  3292. EXPECT_TRUE(matcher3.Matches(n));
  3293. EXPECT_FALSE(matcher3.Matches(n2));
  3294. }
  3295. class DivisibleByImpl {
  3296. public:
  3297. explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
  3298. // For testing using ExplainMatchResultTo() with polymorphic matchers.
  3299. template <typename T>
  3300. bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
  3301. *listener << "which is " << (n % divider_) << " modulo "
  3302. << divider_;
  3303. return (n % divider_) == 0;
  3304. }
  3305. void DescribeTo(ostream* os) const {
  3306. *os << "is divisible by " << divider_;
  3307. }
  3308. void DescribeNegationTo(ostream* os) const {
  3309. *os << "is not divisible by " << divider_;
  3310. }
  3311. void set_divider(int a_divider) { divider_ = a_divider; }
  3312. int divider() const { return divider_; }
  3313. private:
  3314. int divider_;
  3315. };
  3316. PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
  3317. return MakePolymorphicMatcher(DivisibleByImpl(n));
  3318. }
  3319. // Tests that when AllOf() fails, only the first failing matcher is
  3320. // asked to explain why.
  3321. TEST(ExplainMatchResultTest, AllOf_False_False) {
  3322. const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
  3323. EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
  3324. }
  3325. // Tests that when AllOf() fails, only the first failing matcher is
  3326. // asked to explain why.
  3327. TEST(ExplainMatchResultTest, AllOf_False_True) {
  3328. const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
  3329. EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
  3330. }
  3331. // Tests that when AllOf() fails, only the first failing matcher is
  3332. // asked to explain why.
  3333. TEST(ExplainMatchResultTest, AllOf_True_False) {
  3334. const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
  3335. EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
  3336. }
  3337. // Tests that when AllOf() succeeds, all matchers are asked to explain
  3338. // why.
  3339. TEST(ExplainMatchResultTest, AllOf_True_True) {
  3340. const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
  3341. EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
  3342. }
  3343. TEST(ExplainMatchResultTest, AllOf_True_True_2) {
  3344. const Matcher<int> m = AllOf(Ge(2), Le(3));
  3345. EXPECT_EQ("", Explain(m, 2));
  3346. }
  3347. TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
  3348. const Matcher<int> m = GreaterThan(5);
  3349. EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
  3350. }
  3351. // The following two tests verify that values without a public copy
  3352. // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
  3353. // with the help of ByRef().
  3354. class NotCopyable {
  3355. public:
  3356. explicit NotCopyable(int a_value) : value_(a_value) {}
  3357. int value() const { return value_; }
  3358. bool operator==(const NotCopyable& rhs) const {
  3359. return value() == rhs.value();
  3360. }
  3361. bool operator>=(const NotCopyable& rhs) const {
  3362. return value() >= rhs.value();
  3363. }
  3364. private:
  3365. int value_;
  3366. GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
  3367. };
  3368. TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
  3369. const NotCopyable const_value1(1);
  3370. const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
  3371. const NotCopyable n1(1), n2(2);
  3372. EXPECT_TRUE(m.Matches(n1));
  3373. EXPECT_FALSE(m.Matches(n2));
  3374. }
  3375. TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
  3376. NotCopyable value2(2);
  3377. const Matcher<NotCopyable&> m = Ge(ByRef(value2));
  3378. NotCopyable n1(1), n2(2);
  3379. EXPECT_FALSE(m.Matches(n1));
  3380. EXPECT_TRUE(m.Matches(n2));
  3381. }
  3382. TEST(IsEmptyTest, ImplementsIsEmpty) {
  3383. vector<int> container;
  3384. EXPECT_THAT(container, IsEmpty());
  3385. container.push_back(0);
  3386. EXPECT_THAT(container, Not(IsEmpty()));
  3387. container.push_back(1);
  3388. EXPECT_THAT(container, Not(IsEmpty()));
  3389. }
  3390. TEST(IsEmptyTest, WorksWithString) {
  3391. string text;
  3392. EXPECT_THAT(text, IsEmpty());
  3393. text = "foo";
  3394. EXPECT_THAT(text, Not(IsEmpty()));
  3395. text = string("\0", 1);
  3396. EXPECT_THAT(text, Not(IsEmpty()));
  3397. }
  3398. TEST(IsEmptyTest, CanDescribeSelf) {
  3399. Matcher<vector<int> > m = IsEmpty();
  3400. EXPECT_EQ("is empty", Describe(m));
  3401. EXPECT_EQ("isn't empty", DescribeNegation(m));
  3402. }
  3403. TEST(IsEmptyTest, ExplainsResult) {
  3404. Matcher<vector<int> > m = IsEmpty();
  3405. vector<int> container;
  3406. EXPECT_EQ("", Explain(m, container));
  3407. container.push_back(0);
  3408. EXPECT_EQ("whose size is 1", Explain(m, container));
  3409. }
  3410. TEST(SizeIsTest, ImplementsSizeIs) {
  3411. vector<int> container;
  3412. EXPECT_THAT(container, SizeIs(0));
  3413. EXPECT_THAT(container, Not(SizeIs(1)));
  3414. container.push_back(0);
  3415. EXPECT_THAT(container, Not(SizeIs(0)));
  3416. EXPECT_THAT(container, SizeIs(1));
  3417. container.push_back(0);
  3418. EXPECT_THAT(container, Not(SizeIs(0)));
  3419. EXPECT_THAT(container, SizeIs(2));
  3420. }
  3421. TEST(SizeIsTest, WorksWithMap) {
  3422. map<string, int> container;
  3423. EXPECT_THAT(container, SizeIs(0));
  3424. EXPECT_THAT(container, Not(SizeIs(1)));
  3425. container.insert(make_pair("foo", 1));
  3426. EXPECT_THAT(container, Not(SizeIs(0)));
  3427. EXPECT_THAT(container, SizeIs(1));
  3428. container.insert(make_pair("bar", 2));
  3429. EXPECT_THAT(container, Not(SizeIs(0)));
  3430. EXPECT_THAT(container, SizeIs(2));
  3431. }
  3432. TEST(SizeIsTest, WorksWithReferences) {
  3433. vector<int> container;
  3434. Matcher<const vector<int>&> m = SizeIs(1);
  3435. EXPECT_THAT(container, Not(m));
  3436. container.push_back(0);
  3437. EXPECT_THAT(container, m);
  3438. }
  3439. TEST(SizeIsTest, CanDescribeSelf) {
  3440. Matcher<vector<int> > m = SizeIs(2);
  3441. EXPECT_EQ("size is equal to 2", Describe(m));
  3442. EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
  3443. }
  3444. TEST(SizeIsTest, ExplainsResult) {
  3445. Matcher<vector<int> > m1 = SizeIs(2);
  3446. Matcher<vector<int> > m2 = SizeIs(Lt(2u));
  3447. Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
  3448. Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
  3449. vector<int> container;
  3450. EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
  3451. EXPECT_EQ("whose size 0 matches", Explain(m2, container));
  3452. EXPECT_EQ("whose size 0 matches", Explain(m3, container));
  3453. EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
  3454. Explain(m4, container));
  3455. container.push_back(0);
  3456. container.push_back(0);
  3457. EXPECT_EQ("whose size 2 matches", Explain(m1, container));
  3458. EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
  3459. EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
  3460. EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
  3461. Explain(m4, container));
  3462. }
  3463. #if GTEST_HAS_TYPED_TEST
  3464. // Tests ContainerEq with different container types, and
  3465. // different element types.
  3466. template <typename T>
  3467. class ContainerEqTest : public testing::Test {};
  3468. typedef testing::Types<
  3469. set<int>,
  3470. vector<size_t>,
  3471. multiset<size_t>,
  3472. list<int> >
  3473. ContainerEqTestTypes;
  3474. TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
  3475. // Tests that the filled container is equal to itself.
  3476. TYPED_TEST(ContainerEqTest, EqualsSelf) {
  3477. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3478. TypeParam my_set(vals, vals + 6);
  3479. const Matcher<TypeParam> m = ContainerEq(my_set);
  3480. EXPECT_TRUE(m.Matches(my_set));
  3481. EXPECT_EQ("", Explain(m, my_set));
  3482. }
  3483. // Tests that missing values are reported.
  3484. TYPED_TEST(ContainerEqTest, ValueMissing) {
  3485. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3486. static const int test_vals[] = {2, 1, 8, 5};
  3487. TypeParam my_set(vals, vals + 6);
  3488. TypeParam test_set(test_vals, test_vals + 4);
  3489. const Matcher<TypeParam> m = ContainerEq(my_set);
  3490. EXPECT_FALSE(m.Matches(test_set));
  3491. EXPECT_EQ("which doesn't have these expected elements: 3",
  3492. Explain(m, test_set));
  3493. }
  3494. // Tests that added values are reported.
  3495. TYPED_TEST(ContainerEqTest, ValueAdded) {
  3496. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3497. static const int test_vals[] = {1, 2, 3, 5, 8, 46};
  3498. TypeParam my_set(vals, vals + 6);
  3499. TypeParam test_set(test_vals, test_vals + 6);
  3500. const Matcher<const TypeParam&> m = ContainerEq(my_set);
  3501. EXPECT_FALSE(m.Matches(test_set));
  3502. EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
  3503. }
  3504. // Tests that added and missing values are reported together.
  3505. TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
  3506. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3507. static const int test_vals[] = {1, 2, 3, 8, 46};
  3508. TypeParam my_set(vals, vals + 6);
  3509. TypeParam test_set(test_vals, test_vals + 5);
  3510. const Matcher<TypeParam> m = ContainerEq(my_set);
  3511. EXPECT_FALSE(m.Matches(test_set));
  3512. EXPECT_EQ("which has these unexpected elements: 46,\n"
  3513. "and doesn't have these expected elements: 5",
  3514. Explain(m, test_set));
  3515. }
  3516. // Tests duplicated value -- expect no explanation.
  3517. TYPED_TEST(ContainerEqTest, DuplicateDifference) {
  3518. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3519. static const int test_vals[] = {1, 2, 3, 5, 8};
  3520. TypeParam my_set(vals, vals + 6);
  3521. TypeParam test_set(test_vals, test_vals + 5);
  3522. const Matcher<const TypeParam&> m = ContainerEq(my_set);
  3523. // Depending on the container, match may be true or false
  3524. // But in any case there should be no explanation.
  3525. EXPECT_EQ("", Explain(m, test_set));
  3526. }
  3527. #endif // GTEST_HAS_TYPED_TEST
  3528. // Tests that mutliple missing values are reported.
  3529. // Using just vector here, so order is predicatble.
  3530. TEST(ContainerEqExtraTest, MultipleValuesMissing) {
  3531. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3532. static const int test_vals[] = {2, 1, 5};
  3533. vector<int> my_set(vals, vals + 6);
  3534. vector<int> test_set(test_vals, test_vals + 3);
  3535. const Matcher<vector<int> > m = ContainerEq(my_set);
  3536. EXPECT_FALSE(m.Matches(test_set));
  3537. EXPECT_EQ("which doesn't have these expected elements: 3, 8",
  3538. Explain(m, test_set));
  3539. }
  3540. // Tests that added values are reported.
  3541. // Using just vector here, so order is predicatble.
  3542. TEST(ContainerEqExtraTest, MultipleValuesAdded) {
  3543. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3544. static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
  3545. list<size_t> my_set(vals, vals + 6);
  3546. list<size_t> test_set(test_vals, test_vals + 7);
  3547. const Matcher<const list<size_t>&> m = ContainerEq(my_set);
  3548. EXPECT_FALSE(m.Matches(test_set));
  3549. EXPECT_EQ("which has these unexpected elements: 92, 46",
  3550. Explain(m, test_set));
  3551. }
  3552. // Tests that added and missing values are reported together.
  3553. TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
  3554. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3555. static const int test_vals[] = {1, 2, 3, 92, 46};
  3556. list<size_t> my_set(vals, vals + 6);
  3557. list<size_t> test_set(test_vals, test_vals + 5);
  3558. const Matcher<const list<size_t> > m = ContainerEq(my_set);
  3559. EXPECT_FALSE(m.Matches(test_set));
  3560. EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
  3561. "and doesn't have these expected elements: 5, 8",
  3562. Explain(m, test_set));
  3563. }
  3564. // Tests to see that duplicate elements are detected,
  3565. // but (as above) not reported in the explanation.
  3566. TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
  3567. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3568. static const int test_vals[] = {1, 2, 3, 5, 8};
  3569. vector<int> my_set(vals, vals + 6);
  3570. vector<int> test_set(test_vals, test_vals + 5);
  3571. const Matcher<vector<int> > m = ContainerEq(my_set);
  3572. EXPECT_TRUE(m.Matches(my_set));
  3573. EXPECT_FALSE(m.Matches(test_set));
  3574. // There is nothing to report when both sets contain all the same values.
  3575. EXPECT_EQ("", Explain(m, test_set));
  3576. }
  3577. // Tests that ContainerEq works for non-trivial associative containers,
  3578. // like maps.
  3579. TEST(ContainerEqExtraTest, WorksForMaps) {
  3580. map<int, std::string> my_map;
  3581. my_map[0] = "a";
  3582. my_map[1] = "b";
  3583. map<int, std::string> test_map;
  3584. test_map[0] = "aa";
  3585. test_map[1] = "b";
  3586. const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
  3587. EXPECT_TRUE(m.Matches(my_map));
  3588. EXPECT_FALSE(m.Matches(test_map));
  3589. EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
  3590. "and doesn't have these expected elements: (0, \"a\")",
  3591. Explain(m, test_map));
  3592. }
  3593. TEST(ContainerEqExtraTest, WorksForNativeArray) {
  3594. int a1[] = {1, 2, 3};
  3595. int a2[] = {1, 2, 3};
  3596. int b[] = {1, 2, 4};
  3597. EXPECT_THAT(a1, ContainerEq(a2));
  3598. EXPECT_THAT(a1, Not(ContainerEq(b)));
  3599. }
  3600. TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
  3601. const char a1[][3] = {"hi", "lo"};
  3602. const char a2[][3] = {"hi", "lo"};
  3603. const char b[][3] = {"lo", "hi"};
  3604. // Tests using ContainerEq() in the first dimension.
  3605. EXPECT_THAT(a1, ContainerEq(a2));
  3606. EXPECT_THAT(a1, Not(ContainerEq(b)));
  3607. // Tests using ContainerEq() in the second dimension.
  3608. EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
  3609. EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
  3610. }
  3611. TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
  3612. const int a1[] = {1, 2, 3};
  3613. const int a2[] = {1, 2, 3};
  3614. const int b[] = {1, 2, 3, 4};
  3615. const int* const p1 = a1;
  3616. EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
  3617. EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
  3618. const int c[] = {1, 3, 2};
  3619. EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
  3620. }
  3621. TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
  3622. std::string a1[][3] = {
  3623. {"hi", "hello", "ciao"},
  3624. {"bye", "see you", "ciao"}
  3625. };
  3626. std::string a2[][3] = {
  3627. {"hi", "hello", "ciao"},
  3628. {"bye", "see you", "ciao"}
  3629. };
  3630. const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
  3631. EXPECT_THAT(a1, m);
  3632. a2[0][0] = "ha";
  3633. EXPECT_THAT(a1, m);
  3634. }
  3635. TEST(WhenSortedByTest, WorksForEmptyContainer) {
  3636. const vector<int> numbers;
  3637. EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
  3638. EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
  3639. }
  3640. TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
  3641. vector<unsigned> numbers;
  3642. numbers.push_back(3);
  3643. numbers.push_back(1);
  3644. numbers.push_back(2);
  3645. numbers.push_back(2);
  3646. EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
  3647. ElementsAre(3, 2, 2, 1)));
  3648. EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
  3649. ElementsAre(1, 2, 2, 3))));
  3650. }
  3651. TEST(WhenSortedByTest, WorksForNonVectorContainer) {
  3652. list<string> words;
  3653. words.push_back("say");
  3654. words.push_back("hello");
  3655. words.push_back("world");
  3656. EXPECT_THAT(words, WhenSortedBy(less<string>(),
  3657. ElementsAre("hello", "say", "world")));
  3658. EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
  3659. ElementsAre("say", "hello", "world"))));
  3660. }
  3661. TEST(WhenSortedByTest, WorksForNativeArray) {
  3662. const int numbers[] = {1, 3, 2, 4};
  3663. const int sorted_numbers[] = {1, 2, 3, 4};
  3664. EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
  3665. EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
  3666. ElementsAreArray(sorted_numbers)));
  3667. EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
  3668. }
  3669. TEST(WhenSortedByTest, CanDescribeSelf) {
  3670. const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
  3671. EXPECT_EQ("(when sorted) has 2 elements where\n"
  3672. "element #0 is equal to 1,\n"
  3673. "element #1 is equal to 2",
  3674. Describe(m));
  3675. EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
  3676. "element #0 isn't equal to 1, or\n"
  3677. "element #1 isn't equal to 2",
  3678. DescribeNegation(m));
  3679. }
  3680. TEST(WhenSortedByTest, ExplainsMatchResult) {
  3681. const int a[] = {2, 1};
  3682. EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
  3683. Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
  3684. EXPECT_EQ("which is { 1, 2 } when sorted",
  3685. Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
  3686. }
  3687. // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
  3688. // need to test it as exhaustively as we test the latter.
  3689. TEST(WhenSortedTest, WorksForEmptyContainer) {
  3690. const vector<int> numbers;
  3691. EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
  3692. EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
  3693. }
  3694. TEST(WhenSortedTest, WorksForNonEmptyContainer) {
  3695. list<string> words;
  3696. words.push_back("3");
  3697. words.push_back("1");
  3698. words.push_back("2");
  3699. words.push_back("2");
  3700. EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
  3701. EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
  3702. }
  3703. TEST(WhenSortedTest, WorksForMapTypes) {
  3704. map<string, int> word_counts;
  3705. word_counts["and"] = 1;
  3706. word_counts["the"] = 1;
  3707. word_counts["buffalo"] = 2;
  3708. EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
  3709. Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
  3710. EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
  3711. Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
  3712. }
  3713. TEST(WhenSortedTest, WorksForMultiMapTypes) {
  3714. multimap<int, int> ifib;
  3715. ifib.insert(make_pair(8, 6));
  3716. ifib.insert(make_pair(2, 3));
  3717. ifib.insert(make_pair(1, 1));
  3718. ifib.insert(make_pair(3, 4));
  3719. ifib.insert(make_pair(1, 2));
  3720. ifib.insert(make_pair(5, 5));
  3721. EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
  3722. Pair(1, 2),
  3723. Pair(2, 3),
  3724. Pair(3, 4),
  3725. Pair(5, 5),
  3726. Pair(8, 6))));
  3727. EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
  3728. Pair(2, 3),
  3729. Pair(1, 1),
  3730. Pair(3, 4),
  3731. Pair(1, 2),
  3732. Pair(5, 5)))));
  3733. }
  3734. TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
  3735. std::deque<int> d;
  3736. d.push_back(2);
  3737. d.push_back(1);
  3738. EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
  3739. EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
  3740. }
  3741. TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
  3742. std::deque<int> d;
  3743. d.push_back(2);
  3744. d.push_back(1);
  3745. Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
  3746. EXPECT_THAT(d, WhenSorted(vector_match));
  3747. Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
  3748. EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
  3749. }
  3750. // Deliberately bare pseudo-container.
  3751. // Offers only begin() and end() accessors, yielding InputIterator.
  3752. template <typename T>
  3753. class Streamlike {
  3754. private:
  3755. class ConstIter;
  3756. public:
  3757. typedef ConstIter const_iterator;
  3758. typedef T value_type;
  3759. template <typename InIter>
  3760. Streamlike(InIter first, InIter last) : remainder_(first, last) {}
  3761. const_iterator begin() const {
  3762. return const_iterator(this, remainder_.begin());
  3763. }
  3764. const_iterator end() const {
  3765. return const_iterator(this, remainder_.end());
  3766. }
  3767. private:
  3768. class ConstIter : public std::iterator<std::input_iterator_tag,
  3769. value_type,
  3770. ptrdiff_t,
  3771. const value_type*,
  3772. const value_type&> {
  3773. public:
  3774. ConstIter(const Streamlike* s,
  3775. typename std::list<value_type>::iterator pos)
  3776. : s_(s), pos_(pos) {}
  3777. const value_type& operator*() const { return *pos_; }
  3778. const value_type* operator->() const { return &*pos_; }
  3779. ConstIter& operator++() {
  3780. s_->remainder_.erase(pos_++);
  3781. return *this;
  3782. }
  3783. // *iter++ is required to work (see std::istreambuf_iterator).
  3784. // (void)iter++ is also required to work.
  3785. class PostIncrProxy {
  3786. public:
  3787. explicit PostIncrProxy(const value_type& value) : value_(value) {}
  3788. value_type operator*() const { return value_; }
  3789. private:
  3790. value_type value_;
  3791. };
  3792. PostIncrProxy operator++(int) {
  3793. PostIncrProxy proxy(**this);
  3794. ++(*this);
  3795. return proxy;
  3796. }
  3797. friend bool operator==(const ConstIter& a, const ConstIter& b) {
  3798. return a.s_ == b.s_ && a.pos_ == b.pos_;
  3799. }
  3800. friend bool operator!=(const ConstIter& a, const ConstIter& b) {
  3801. return !(a == b);
  3802. }
  3803. private:
  3804. const Streamlike* s_;
  3805. typename std::list<value_type>::iterator pos_;
  3806. };
  3807. friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
  3808. os << "[";
  3809. typedef typename std::list<value_type>::const_iterator Iter;
  3810. const char* sep = "";
  3811. for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
  3812. os << sep << *it;
  3813. sep = ",";
  3814. }
  3815. os << "]";
  3816. return os;
  3817. }
  3818. mutable std::list<value_type> remainder_; // modified by iteration
  3819. };
  3820. TEST(StreamlikeTest, Iteration) {
  3821. const int a[5] = {2, 1, 4, 5, 3};
  3822. Streamlike<int> s(a, a + 5);
  3823. Streamlike<int>::const_iterator it = s.begin();
  3824. const int* ip = a;
  3825. while (it != s.end()) {
  3826. SCOPED_TRACE(ip - a);
  3827. EXPECT_EQ(*ip++, *it++);
  3828. }
  3829. }
  3830. #if GTEST_HAS_STD_FORWARD_LIST_
  3831. TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
  3832. std::forward_list<int> container;
  3833. EXPECT_THAT(container, BeginEndDistanceIs(0));
  3834. EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
  3835. container.push_front(0);
  3836. EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
  3837. EXPECT_THAT(container, BeginEndDistanceIs(1));
  3838. container.push_front(0);
  3839. EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
  3840. EXPECT_THAT(container, BeginEndDistanceIs(2));
  3841. }
  3842. #endif // GTEST_HAS_STD_FORWARD_LIST_
  3843. TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
  3844. const int a[5] = {1, 2, 3, 4, 5};
  3845. Streamlike<int> s(a, a + 5);
  3846. EXPECT_THAT(s, BeginEndDistanceIs(5));
  3847. }
  3848. TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
  3849. Matcher<vector<int> > m = BeginEndDistanceIs(2);
  3850. EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
  3851. EXPECT_EQ("distance between begin() and end() isn't equal to 2",
  3852. DescribeNegation(m));
  3853. }
  3854. TEST(BeginEndDistanceIsTest, ExplainsResult) {
  3855. Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
  3856. Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
  3857. Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
  3858. Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
  3859. vector<int> container;
  3860. EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
  3861. Explain(m1, container));
  3862. EXPECT_EQ("whose distance between begin() and end() 0 matches",
  3863. Explain(m2, container));
  3864. EXPECT_EQ("whose distance between begin() and end() 0 matches",
  3865. Explain(m3, container));
  3866. EXPECT_EQ(
  3867. "whose distance between begin() and end() 0 doesn't match, which is 1 "
  3868. "less than 1",
  3869. Explain(m4, container));
  3870. container.push_back(0);
  3871. container.push_back(0);
  3872. EXPECT_EQ("whose distance between begin() and end() 2 matches",
  3873. Explain(m1, container));
  3874. EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
  3875. Explain(m2, container));
  3876. EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
  3877. Explain(m3, container));
  3878. EXPECT_EQ(
  3879. "whose distance between begin() and end() 2 matches, which is 1 more "
  3880. "than 1",
  3881. Explain(m4, container));
  3882. }
  3883. TEST(WhenSortedTest, WorksForStreamlike) {
  3884. // Streamlike 'container' provides only minimal iterator support.
  3885. // Its iterators are tagged with input_iterator_tag.
  3886. const int a[5] = {2, 1, 4, 5, 3};
  3887. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  3888. EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
  3889. EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
  3890. }
  3891. TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
  3892. const int a[] = {2, 1, 4, 5, 3};
  3893. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  3894. Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
  3895. EXPECT_THAT(s, WhenSorted(vector_match));
  3896. EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
  3897. }
  3898. // Tests using ElementsAre() and ElementsAreArray() with stream-like
  3899. // "containers".
  3900. TEST(ElemensAreStreamTest, WorksForStreamlike) {
  3901. const int a[5] = {1, 2, 3, 4, 5};
  3902. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  3903. EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
  3904. EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
  3905. }
  3906. TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
  3907. const int a[5] = {1, 2, 3, 4, 5};
  3908. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  3909. vector<int> expected;
  3910. expected.push_back(1);
  3911. expected.push_back(2);
  3912. expected.push_back(3);
  3913. expected.push_back(4);
  3914. expected.push_back(5);
  3915. EXPECT_THAT(s, ElementsAreArray(expected));
  3916. expected[3] = 0;
  3917. EXPECT_THAT(s, Not(ElementsAreArray(expected)));
  3918. }
  3919. TEST(ElementsAreTest, WorksWithUncopyable) {
  3920. Uncopyable objs[2];
  3921. objs[0].set_value(-3);
  3922. objs[1].set_value(1);
  3923. EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
  3924. }
  3925. TEST(ElementsAreTest, TakesStlContainer) {
  3926. const int actual[] = {3, 1, 2};
  3927. ::std::list<int> expected;
  3928. expected.push_back(3);
  3929. expected.push_back(1);
  3930. expected.push_back(2);
  3931. EXPECT_THAT(actual, ElementsAreArray(expected));
  3932. expected.push_back(4);
  3933. EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
  3934. }
  3935. // Tests for UnorderedElementsAreArray()
  3936. TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
  3937. const int a[] = {0, 1, 2, 3, 4};
  3938. std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  3939. do {
  3940. StringMatchResultListener listener;
  3941. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
  3942. s, &listener)) << listener.str();
  3943. } while (std::next_permutation(s.begin(), s.end()));
  3944. }
  3945. TEST(UnorderedElementsAreArrayTest, VectorBool) {
  3946. const bool a[] = {0, 1, 0, 1, 1};
  3947. const bool b[] = {1, 0, 1, 1, 0};
  3948. std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
  3949. std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
  3950. StringMatchResultListener listener;
  3951. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
  3952. actual, &listener)) << listener.str();
  3953. }
  3954. TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
  3955. // Streamlike 'container' provides only minimal iterator support.
  3956. // Its iterators are tagged with input_iterator_tag, and it has no
  3957. // size() or empty() methods.
  3958. const int a[5] = {2, 1, 4, 5, 3};
  3959. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  3960. ::std::vector<int> expected;
  3961. expected.push_back(1);
  3962. expected.push_back(2);
  3963. expected.push_back(3);
  3964. expected.push_back(4);
  3965. expected.push_back(5);
  3966. EXPECT_THAT(s, UnorderedElementsAreArray(expected));
  3967. expected.push_back(6);
  3968. EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
  3969. }
  3970. TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
  3971. const int actual[] = {3, 1, 2};
  3972. ::std::list<int> expected;
  3973. expected.push_back(1);
  3974. expected.push_back(2);
  3975. expected.push_back(3);
  3976. EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
  3977. expected.push_back(4);
  3978. EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
  3979. }
  3980. #if GTEST_HAS_STD_INITIALIZER_LIST_
  3981. TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
  3982. const int a[5] = {2, 1, 4, 5, 3};
  3983. EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
  3984. EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
  3985. }
  3986. TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
  3987. const string a[5] = {"a", "b", "c", "d", "e"};
  3988. EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
  3989. EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
  3990. }
  3991. TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
  3992. const int a[5] = {2, 1, 4, 5, 3};
  3993. EXPECT_THAT(a, UnorderedElementsAreArray(
  3994. {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
  3995. EXPECT_THAT(a, Not(UnorderedElementsAreArray(
  3996. {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
  3997. }
  3998. TEST(UnorderedElementsAreArrayTest,
  3999. TakesInitializerListOfDifferentTypedMatchers) {
  4000. const int a[5] = {2, 1, 4, 5, 3};
  4001. // The compiler cannot infer the type of the initializer list if its
  4002. // elements have different types. We must explicitly specify the
  4003. // unified element type in this case.
  4004. EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
  4005. {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
  4006. EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
  4007. {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
  4008. }
  4009. #endif // GTEST_HAS_STD_INITIALIZER_LIST_
  4010. class UnorderedElementsAreTest : public testing::Test {
  4011. protected:
  4012. typedef std::vector<int> IntVec;
  4013. };
  4014. TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
  4015. Uncopyable objs[2];
  4016. objs[0].set_value(-3);
  4017. objs[1].set_value(1);
  4018. EXPECT_THAT(objs,
  4019. UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
  4020. }
  4021. TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
  4022. const int a[] = {1, 2, 3};
  4023. std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4024. do {
  4025. StringMatchResultListener listener;
  4026. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
  4027. s, &listener)) << listener.str();
  4028. } while (std::next_permutation(s.begin(), s.end()));
  4029. }
  4030. TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
  4031. const int a[] = {1, 2, 3};
  4032. std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4033. std::vector<Matcher<int> > mv;
  4034. mv.push_back(1);
  4035. mv.push_back(2);
  4036. mv.push_back(2);
  4037. // The element with value '3' matches nothing: fail fast.
  4038. StringMatchResultListener listener;
  4039. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
  4040. s, &listener)) << listener.str();
  4041. }
  4042. TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
  4043. // Streamlike 'container' provides only minimal iterator support.
  4044. // Its iterators are tagged with input_iterator_tag, and it has no
  4045. // size() or empty() methods.
  4046. const int a[5] = {2, 1, 4, 5, 3};
  4047. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4048. EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
  4049. EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
  4050. }
  4051. // One naive implementation of the matcher runs in O(N!) time, which is too
  4052. // slow for many real-world inputs. This test shows that our matcher can match
  4053. // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
  4054. // iterations and obviously effectively incomputable.
  4055. // [ RUN ] UnorderedElementsAreTest.Performance
  4056. // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
  4057. TEST_F(UnorderedElementsAreTest, Performance) {
  4058. std::vector<int> s;
  4059. std::vector<Matcher<int> > mv;
  4060. for (int i = 0; i < 100; ++i) {
  4061. s.push_back(i);
  4062. mv.push_back(_);
  4063. }
  4064. mv[50] = Eq(0);
  4065. StringMatchResultListener listener;
  4066. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
  4067. s, &listener)) << listener.str();
  4068. }
  4069. // Another variant of 'Performance' with similar expectations.
  4070. // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
  4071. // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
  4072. TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
  4073. std::vector<int> s;
  4074. std::vector<Matcher<int> > mv;
  4075. for (int i = 0; i < 100; ++i) {
  4076. s.push_back(i);
  4077. if (i & 1) {
  4078. mv.push_back(_);
  4079. } else {
  4080. mv.push_back(i);
  4081. }
  4082. }
  4083. StringMatchResultListener listener;
  4084. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
  4085. s, &listener)) << listener.str();
  4086. }
  4087. TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
  4088. std::vector<int> v;
  4089. v.push_back(4);
  4090. StringMatchResultListener listener;
  4091. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
  4092. v, &listener)) << listener.str();
  4093. EXPECT_THAT(listener.str(), Eq("which has 1 element"));
  4094. }
  4095. TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
  4096. std::vector<int> v;
  4097. StringMatchResultListener listener;
  4098. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
  4099. v, &listener)) << listener.str();
  4100. EXPECT_THAT(listener.str(), Eq(""));
  4101. }
  4102. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
  4103. std::vector<int> v;
  4104. v.push_back(1);
  4105. v.push_back(1);
  4106. StringMatchResultListener listener;
  4107. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
  4108. v, &listener)) << listener.str();
  4109. EXPECT_THAT(
  4110. listener.str(),
  4111. Eq("where the following matchers don't match any elements:\n"
  4112. "matcher #1: is equal to 2"));
  4113. }
  4114. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
  4115. std::vector<int> v;
  4116. v.push_back(1);
  4117. v.push_back(2);
  4118. StringMatchResultListener listener;
  4119. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
  4120. v, &listener)) << listener.str();
  4121. EXPECT_THAT(
  4122. listener.str(),
  4123. Eq("where the following elements don't match any matchers:\n"
  4124. "element #1: 2"));
  4125. }
  4126. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
  4127. std::vector<int> v;
  4128. v.push_back(2);
  4129. v.push_back(3);
  4130. StringMatchResultListener listener;
  4131. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
  4132. v, &listener)) << listener.str();
  4133. EXPECT_THAT(
  4134. listener.str(),
  4135. Eq("where"
  4136. " the following matchers don't match any elements:\n"
  4137. "matcher #0: is equal to 1\n"
  4138. "and"
  4139. " where"
  4140. " the following elements don't match any matchers:\n"
  4141. "element #1: 3"));
  4142. }
  4143. // Test helper for formatting element, matcher index pairs in expectations.
  4144. static string EMString(int element, int matcher) {
  4145. stringstream ss;
  4146. ss << "(element #" << element << ", matcher #" << matcher << ")";
  4147. return ss.str();
  4148. }
  4149. TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
  4150. // A situation where all elements and matchers have a match
  4151. // associated with them, but the max matching is not perfect.
  4152. std::vector<string> v;
  4153. v.push_back("a");
  4154. v.push_back("b");
  4155. v.push_back("c");
  4156. StringMatchResultListener listener;
  4157. EXPECT_FALSE(ExplainMatchResult(
  4158. UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
  4159. << listener.str();
  4160. string prefix =
  4161. "where no permutation of the elements can satisfy all matchers, "
  4162. "and the closest match is 2 of 3 matchers with the "
  4163. "pairings:\n";
  4164. // We have to be a bit loose here, because there are 4 valid max matches.
  4165. EXPECT_THAT(
  4166. listener.str(),
  4167. AnyOf(prefix + "{\n " + EMString(0, 0) +
  4168. ",\n " + EMString(1, 2) + "\n}",
  4169. prefix + "{\n " + EMString(0, 1) +
  4170. ",\n " + EMString(1, 2) + "\n}",
  4171. prefix + "{\n " + EMString(0, 0) +
  4172. ",\n " + EMString(2, 2) + "\n}",
  4173. prefix + "{\n " + EMString(0, 1) +
  4174. ",\n " + EMString(2, 2) + "\n}"));
  4175. }
  4176. TEST_F(UnorderedElementsAreTest, Describe) {
  4177. EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
  4178. Eq("is empty"));
  4179. EXPECT_THAT(
  4180. Describe<IntVec>(UnorderedElementsAre(345)),
  4181. Eq("has 1 element and that element is equal to 345"));
  4182. EXPECT_THAT(
  4183. Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
  4184. Eq("has 3 elements and there exists some permutation "
  4185. "of elements such that:\n"
  4186. " - element #0 is equal to 111, and\n"
  4187. " - element #1 is equal to 222, and\n"
  4188. " - element #2 is equal to 333"));
  4189. }
  4190. TEST_F(UnorderedElementsAreTest, DescribeNegation) {
  4191. EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
  4192. Eq("isn't empty"));
  4193. EXPECT_THAT(
  4194. DescribeNegation<IntVec>(UnorderedElementsAre(345)),
  4195. Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
  4196. EXPECT_THAT(
  4197. DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
  4198. Eq("doesn't have 3 elements, or there exists no permutation "
  4199. "of elements such that:\n"
  4200. " - element #0 is equal to 123, and\n"
  4201. " - element #1 is equal to 234, and\n"
  4202. " - element #2 is equal to 345"));
  4203. }
  4204. namespace {
  4205. // Used as a check on the more complex max flow method used in the
  4206. // real testing::internal::FindMaxBipartiteMatching. This method is
  4207. // compatible but runs in worst-case factorial time, so we only
  4208. // use it in testing for small problem sizes.
  4209. template <typename Graph>
  4210. class BacktrackingMaxBPMState {
  4211. public:
  4212. // Does not take ownership of 'g'.
  4213. explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
  4214. ElementMatcherPairs Compute() {
  4215. if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
  4216. return best_so_far_;
  4217. }
  4218. lhs_used_.assign(graph_->LhsSize(), kUnused);
  4219. rhs_used_.assign(graph_->RhsSize(), kUnused);
  4220. for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
  4221. matches_.clear();
  4222. RecurseInto(irhs);
  4223. if (best_so_far_.size() == graph_->RhsSize())
  4224. break;
  4225. }
  4226. return best_so_far_;
  4227. }
  4228. private:
  4229. static const size_t kUnused = static_cast<size_t>(-1);
  4230. void PushMatch(size_t lhs, size_t rhs) {
  4231. matches_.push_back(ElementMatcherPair(lhs, rhs));
  4232. lhs_used_[lhs] = rhs;
  4233. rhs_used_[rhs] = lhs;
  4234. if (matches_.size() > best_so_far_.size()) {
  4235. best_so_far_ = matches_;
  4236. }
  4237. }
  4238. void PopMatch() {
  4239. const ElementMatcherPair& back = matches_.back();
  4240. lhs_used_[back.first] = kUnused;
  4241. rhs_used_[back.second] = kUnused;
  4242. matches_.pop_back();
  4243. }
  4244. bool RecurseInto(size_t irhs) {
  4245. if (rhs_used_[irhs] != kUnused) {
  4246. return true;
  4247. }
  4248. for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
  4249. if (lhs_used_[ilhs] != kUnused) {
  4250. continue;
  4251. }
  4252. if (!graph_->HasEdge(ilhs, irhs)) {
  4253. continue;
  4254. }
  4255. PushMatch(ilhs, irhs);
  4256. if (best_so_far_.size() == graph_->RhsSize()) {
  4257. return false;
  4258. }
  4259. for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
  4260. if (!RecurseInto(mi)) return false;
  4261. }
  4262. PopMatch();
  4263. }
  4264. return true;
  4265. }
  4266. const Graph* graph_; // not owned
  4267. std::vector<size_t> lhs_used_;
  4268. std::vector<size_t> rhs_used_;
  4269. ElementMatcherPairs matches_;
  4270. ElementMatcherPairs best_so_far_;
  4271. };
  4272. template <typename Graph>
  4273. const size_t BacktrackingMaxBPMState<Graph>::kUnused;
  4274. } // namespace
  4275. // Implement a simple backtracking algorithm to determine if it is possible
  4276. // to find one element per matcher, without reusing elements.
  4277. template <typename Graph>
  4278. ElementMatcherPairs
  4279. FindBacktrackingMaxBPM(const Graph& g) {
  4280. return BacktrackingMaxBPMState<Graph>(&g).Compute();
  4281. }
  4282. class BacktrackingBPMTest : public ::testing::Test { };
  4283. // Tests the MaxBipartiteMatching algorithm with square matrices.
  4284. // The single int param is the # of nodes on each of the left and right sides.
  4285. class BipartiteTest : public ::testing::TestWithParam<int> { };
  4286. // Verify all match graphs up to some moderate number of edges.
  4287. TEST_P(BipartiteTest, Exhaustive) {
  4288. int nodes = GetParam();
  4289. MatchMatrix graph(nodes, nodes);
  4290. do {
  4291. ElementMatcherPairs matches =
  4292. internal::FindMaxBipartiteMatching(graph);
  4293. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
  4294. << "graph: " << graph.DebugString();
  4295. // Check that all elements of matches are in the graph.
  4296. // Check that elements of first and second are unique.
  4297. std::vector<bool> seen_element(graph.LhsSize());
  4298. std::vector<bool> seen_matcher(graph.RhsSize());
  4299. SCOPED_TRACE(PrintToString(matches));
  4300. for (size_t i = 0; i < matches.size(); ++i) {
  4301. size_t ilhs = matches[i].first;
  4302. size_t irhs = matches[i].second;
  4303. EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
  4304. EXPECT_FALSE(seen_element[ilhs]);
  4305. EXPECT_FALSE(seen_matcher[irhs]);
  4306. seen_element[ilhs] = true;
  4307. seen_matcher[irhs] = true;
  4308. }
  4309. } while (graph.NextGraph());
  4310. }
  4311. INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
  4312. ::testing::Range(0, 5));
  4313. // Parameterized by a pair interpreted as (LhsSize, RhsSize).
  4314. class BipartiteNonSquareTest
  4315. : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
  4316. };
  4317. TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
  4318. // .......
  4319. // 0:-----\ :
  4320. // 1:---\ | :
  4321. // 2:---\ | :
  4322. // 3:-\ | | :
  4323. // :.......:
  4324. // 0 1 2
  4325. MatchMatrix g(4, 3);
  4326. static const int kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
  4327. for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
  4328. g.SetEdge(kEdges[i][0], kEdges[i][1], true);
  4329. }
  4330. EXPECT_THAT(FindBacktrackingMaxBPM(g),
  4331. ElementsAre(Pair(3, 0),
  4332. Pair(AnyOf(1, 2), 1),
  4333. Pair(0, 2))) << g.DebugString();
  4334. }
  4335. // Verify a few nonsquare matrices.
  4336. TEST_P(BipartiteNonSquareTest, Exhaustive) {
  4337. size_t nlhs = GetParam().first;
  4338. size_t nrhs = GetParam().second;
  4339. MatchMatrix graph(nlhs, nrhs);
  4340. do {
  4341. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
  4342. internal::FindMaxBipartiteMatching(graph).size())
  4343. << "graph: " << graph.DebugString()
  4344. << "\nbacktracking: "
  4345. << PrintToString(FindBacktrackingMaxBPM(graph))
  4346. << "\nmax flow: "
  4347. << PrintToString(internal::FindMaxBipartiteMatching(graph));
  4348. } while (graph.NextGraph());
  4349. }
  4350. INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
  4351. testing::Values(
  4352. std::make_pair(1, 2),
  4353. std::make_pair(2, 1),
  4354. std::make_pair(3, 2),
  4355. std::make_pair(2, 3),
  4356. std::make_pair(4, 1),
  4357. std::make_pair(1, 4),
  4358. std::make_pair(4, 3),
  4359. std::make_pair(3, 4)));
  4360. class BipartiteRandomTest
  4361. : public ::testing::TestWithParam<std::pair<int, int> > {
  4362. };
  4363. // Verifies a large sample of larger graphs.
  4364. TEST_P(BipartiteRandomTest, LargerNets) {
  4365. int nodes = GetParam().first;
  4366. int iters = GetParam().second;
  4367. MatchMatrix graph(nodes, nodes);
  4368. testing::internal::Int32 seed = GTEST_FLAG(random_seed);
  4369. if (seed == 0) {
  4370. seed = static_cast<testing::internal::Int32>(time(NULL));
  4371. }
  4372. for (; iters > 0; --iters, ++seed) {
  4373. srand(static_cast<int>(seed));
  4374. graph.Randomize();
  4375. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
  4376. internal::FindMaxBipartiteMatching(graph).size())
  4377. << " graph: " << graph.DebugString()
  4378. << "\nTo reproduce the failure, rerun the test with the flag"
  4379. " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
  4380. }
  4381. }
  4382. // Test argument is a std::pair<int, int> representing (nodes, iters).
  4383. INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
  4384. testing::Values(
  4385. std::make_pair(5, 10000),
  4386. std::make_pair(6, 5000),
  4387. std::make_pair(7, 2000),
  4388. std::make_pair(8, 500),
  4389. std::make_pair(9, 100)));
  4390. // Tests IsReadableTypeName().
  4391. TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
  4392. EXPECT_TRUE(IsReadableTypeName("int"));
  4393. EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
  4394. EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
  4395. EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
  4396. }
  4397. TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
  4398. EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
  4399. EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
  4400. EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
  4401. }
  4402. TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
  4403. EXPECT_FALSE(
  4404. IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
  4405. EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
  4406. }
  4407. TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
  4408. EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
  4409. }
  4410. // Tests JoinAsTuple().
  4411. TEST(JoinAsTupleTest, JoinsEmptyTuple) {
  4412. EXPECT_EQ("", JoinAsTuple(Strings()));
  4413. }
  4414. TEST(JoinAsTupleTest, JoinsOneTuple) {
  4415. const char* fields[] = {"1"};
  4416. EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
  4417. }
  4418. TEST(JoinAsTupleTest, JoinsTwoTuple) {
  4419. const char* fields[] = {"1", "a"};
  4420. EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
  4421. }
  4422. TEST(JoinAsTupleTest, JoinsTenTuple) {
  4423. const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
  4424. EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
  4425. JoinAsTuple(Strings(fields, fields + 10)));
  4426. }
  4427. // Tests FormatMatcherDescription().
  4428. TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
  4429. EXPECT_EQ("is even",
  4430. FormatMatcherDescription(false, "IsEven", Strings()));
  4431. EXPECT_EQ("not (is even)",
  4432. FormatMatcherDescription(true, "IsEven", Strings()));
  4433. const char* params[] = {"5"};
  4434. EXPECT_EQ("equals 5",
  4435. FormatMatcherDescription(false, "Equals",
  4436. Strings(params, params + 1)));
  4437. const char* params2[] = {"5", "8"};
  4438. EXPECT_EQ("is in range (5, 8)",
  4439. FormatMatcherDescription(false, "IsInRange",
  4440. Strings(params2, params2 + 2)));
  4441. }
  4442. // Tests PolymorphicMatcher::mutable_impl().
  4443. TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
  4444. PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
  4445. DivisibleByImpl& impl = m.mutable_impl();
  4446. EXPECT_EQ(42, impl.divider());
  4447. impl.set_divider(0);
  4448. EXPECT_EQ(0, m.mutable_impl().divider());
  4449. }
  4450. // Tests PolymorphicMatcher::impl().
  4451. TEST(PolymorphicMatcherTest, CanAccessImpl) {
  4452. const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
  4453. const DivisibleByImpl& impl = m.impl();
  4454. EXPECT_EQ(42, impl.divider());
  4455. }
  4456. TEST(MatcherTupleTest, ExplainsMatchFailure) {
  4457. stringstream ss1;
  4458. ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
  4459. make_tuple('a', 10), &ss1);
  4460. EXPECT_EQ("", ss1.str()); // Successful match.
  4461. stringstream ss2;
  4462. ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
  4463. make_tuple(2, 'b'), &ss2);
  4464. EXPECT_EQ(" Expected arg #0: is > 5\n"
  4465. " Actual: 2, which is 3 less than 5\n"
  4466. " Expected arg #1: is equal to 'a' (97, 0x61)\n"
  4467. " Actual: 'b' (98, 0x62)\n",
  4468. ss2.str()); // Failed match where both arguments need explanation.
  4469. stringstream ss3;
  4470. ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
  4471. make_tuple(2, 'a'), &ss3);
  4472. EXPECT_EQ(" Expected arg #0: is > 5\n"
  4473. " Actual: 2, which is 3 less than 5\n",
  4474. ss3.str()); // Failed match where only one argument needs
  4475. // explanation.
  4476. }
  4477. // Tests Each().
  4478. TEST(EachTest, ExplainsMatchResultCorrectly) {
  4479. set<int> a; // empty
  4480. Matcher<set<int> > m = Each(2);
  4481. EXPECT_EQ("", Explain(m, a));
  4482. Matcher<const int(&)[1]> n = Each(1); // NOLINT
  4483. const int b[1] = {1};
  4484. EXPECT_EQ("", Explain(n, b));
  4485. n = Each(3);
  4486. EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
  4487. a.insert(1);
  4488. a.insert(2);
  4489. a.insert(3);
  4490. m = Each(GreaterThan(0));
  4491. EXPECT_EQ("", Explain(m, a));
  4492. m = Each(GreaterThan(10));
  4493. EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
  4494. Explain(m, a));
  4495. }
  4496. TEST(EachTest, DescribesItselfCorrectly) {
  4497. Matcher<vector<int> > m = Each(1);
  4498. EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
  4499. Matcher<vector<int> > m2 = Not(m);
  4500. EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
  4501. }
  4502. TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
  4503. vector<int> some_vector;
  4504. EXPECT_THAT(some_vector, Each(1));
  4505. some_vector.push_back(3);
  4506. EXPECT_THAT(some_vector, Not(Each(1)));
  4507. EXPECT_THAT(some_vector, Each(3));
  4508. some_vector.push_back(1);
  4509. some_vector.push_back(2);
  4510. EXPECT_THAT(some_vector, Not(Each(3)));
  4511. EXPECT_THAT(some_vector, Each(Lt(3.5)));
  4512. vector<string> another_vector;
  4513. another_vector.push_back("fee");
  4514. EXPECT_THAT(another_vector, Each(string("fee")));
  4515. another_vector.push_back("fie");
  4516. another_vector.push_back("foe");
  4517. another_vector.push_back("fum");
  4518. EXPECT_THAT(another_vector, Not(Each(string("fee"))));
  4519. }
  4520. TEST(EachTest, MatchesMapWhenAllElementsMatch) {
  4521. map<const char*, int> my_map;
  4522. const char* bar = "a string";
  4523. my_map[bar] = 2;
  4524. EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
  4525. map<string, int> another_map;
  4526. EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
  4527. another_map["fee"] = 1;
  4528. EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
  4529. another_map["fie"] = 2;
  4530. another_map["foe"] = 3;
  4531. another_map["fum"] = 4;
  4532. EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
  4533. EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
  4534. EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
  4535. }
  4536. TEST(EachTest, AcceptsMatcher) {
  4537. const int a[] = {1, 2, 3};
  4538. EXPECT_THAT(a, Each(Gt(0)));
  4539. EXPECT_THAT(a, Not(Each(Gt(1))));
  4540. }
  4541. TEST(EachTest, WorksForNativeArrayAsTuple) {
  4542. const int a[] = {1, 2};
  4543. const int* const pointer = a;
  4544. EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
  4545. EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
  4546. }
  4547. // For testing Pointwise().
  4548. class IsHalfOfMatcher {
  4549. public:
  4550. template <typename T1, typename T2>
  4551. bool MatchAndExplain(const tuple<T1, T2>& a_pair,
  4552. MatchResultListener* listener) const {
  4553. if (get<0>(a_pair) == get<1>(a_pair)/2) {
  4554. *listener << "where the second is " << get<1>(a_pair);
  4555. return true;
  4556. } else {
  4557. *listener << "where the second/2 is " << get<1>(a_pair)/2;
  4558. return false;
  4559. }
  4560. }
  4561. void DescribeTo(ostream* os) const {
  4562. *os << "are a pair where the first is half of the second";
  4563. }
  4564. void DescribeNegationTo(ostream* os) const {
  4565. *os << "are a pair where the first isn't half of the second";
  4566. }
  4567. };
  4568. PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
  4569. return MakePolymorphicMatcher(IsHalfOfMatcher());
  4570. }
  4571. TEST(PointwiseTest, DescribesSelf) {
  4572. vector<int> rhs;
  4573. rhs.push_back(1);
  4574. rhs.push_back(2);
  4575. rhs.push_back(3);
  4576. const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
  4577. EXPECT_EQ("contains 3 values, where each value and its corresponding value "
  4578. "in { 1, 2, 3 } are a pair where the first is half of the second",
  4579. Describe(m));
  4580. EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
  4581. "index i where x and the i-th value of { 1, 2, 3 } are a pair "
  4582. "where the first isn't half of the second",
  4583. DescribeNegation(m));
  4584. }
  4585. TEST(PointwiseTest, MakesCopyOfRhs) {
  4586. list<signed char> rhs;
  4587. rhs.push_back(2);
  4588. rhs.push_back(4);
  4589. int lhs[] = {1, 2};
  4590. const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
  4591. EXPECT_THAT(lhs, m);
  4592. // Changing rhs now shouldn't affect m, which made a copy of rhs.
  4593. rhs.push_back(6);
  4594. EXPECT_THAT(lhs, m);
  4595. }
  4596. TEST(PointwiseTest, WorksForLhsNativeArray) {
  4597. const int lhs[] = {1, 2, 3};
  4598. vector<int> rhs;
  4599. rhs.push_back(2);
  4600. rhs.push_back(4);
  4601. rhs.push_back(6);
  4602. EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
  4603. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
  4604. }
  4605. TEST(PointwiseTest, WorksForRhsNativeArray) {
  4606. const int rhs[] = {1, 2, 3};
  4607. vector<int> lhs;
  4608. lhs.push_back(2);
  4609. lhs.push_back(4);
  4610. lhs.push_back(6);
  4611. EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
  4612. EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
  4613. }
  4614. #if GTEST_HAS_STD_INITIALIZER_LIST_
  4615. TEST(PointwiseTest, WorksForRhsInitializerList) {
  4616. const vector<int> lhs{2, 4, 6};
  4617. EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
  4618. EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
  4619. }
  4620. #endif // GTEST_HAS_STD_INITIALIZER_LIST_
  4621. TEST(PointwiseTest, RejectsWrongSize) {
  4622. const double lhs[2] = {1, 2};
  4623. const int rhs[1] = {0};
  4624. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
  4625. EXPECT_EQ("which contains 2 values",
  4626. Explain(Pointwise(Gt(), rhs), lhs));
  4627. const int rhs2[3] = {0, 1, 2};
  4628. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
  4629. }
  4630. TEST(PointwiseTest, RejectsWrongContent) {
  4631. const double lhs[3] = {1, 2, 3};
  4632. const int rhs[3] = {2, 6, 4};
  4633. EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
  4634. EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
  4635. "where the second/2 is 3",
  4636. Explain(Pointwise(IsHalfOf(), rhs), lhs));
  4637. }
  4638. TEST(PointwiseTest, AcceptsCorrectContent) {
  4639. const double lhs[3] = {1, 2, 3};
  4640. const int rhs[3] = {2, 4, 6};
  4641. EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
  4642. EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
  4643. }
  4644. TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
  4645. const double lhs[3] = {1, 2, 3};
  4646. const int rhs[3] = {2, 4, 6};
  4647. const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
  4648. EXPECT_THAT(lhs, Pointwise(m1, rhs));
  4649. EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
  4650. // This type works as a tuple<const double&, const int&> can be
  4651. // implicitly cast to tuple<double, int>.
  4652. const Matcher<tuple<double, int> > m2 = IsHalfOf();
  4653. EXPECT_THAT(lhs, Pointwise(m2, rhs));
  4654. EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
  4655. }
  4656. TEST(UnorderedPointwiseTest, DescribesSelf) {
  4657. vector<int> rhs;
  4658. rhs.push_back(1);
  4659. rhs.push_back(2);
  4660. rhs.push_back(3);
  4661. const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
  4662. EXPECT_EQ(
  4663. "has 3 elements and there exists some permutation of elements such "
  4664. "that:\n"
  4665. " - element #0 and 1 are a pair where the first is half of the second, "
  4666. "and\n"
  4667. " - element #1 and 2 are a pair where the first is half of the second, "
  4668. "and\n"
  4669. " - element #2 and 3 are a pair where the first is half of the second",
  4670. Describe(m));
  4671. EXPECT_EQ(
  4672. "doesn't have 3 elements, or there exists no permutation of elements "
  4673. "such that:\n"
  4674. " - element #0 and 1 are a pair where the first is half of the second, "
  4675. "and\n"
  4676. " - element #1 and 2 are a pair where the first is half of the second, "
  4677. "and\n"
  4678. " - element #2 and 3 are a pair where the first is half of the second",
  4679. DescribeNegation(m));
  4680. }
  4681. TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
  4682. list<signed char> rhs;
  4683. rhs.push_back(2);
  4684. rhs.push_back(4);
  4685. int lhs[] = {2, 1};
  4686. const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
  4687. EXPECT_THAT(lhs, m);
  4688. // Changing rhs now shouldn't affect m, which made a copy of rhs.
  4689. rhs.push_back(6);
  4690. EXPECT_THAT(lhs, m);
  4691. }
  4692. TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
  4693. const int lhs[] = {1, 2, 3};
  4694. vector<int> rhs;
  4695. rhs.push_back(4);
  4696. rhs.push_back(6);
  4697. rhs.push_back(2);
  4698. EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
  4699. EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
  4700. }
  4701. TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
  4702. const int rhs[] = {1, 2, 3};
  4703. vector<int> lhs;
  4704. lhs.push_back(4);
  4705. lhs.push_back(2);
  4706. lhs.push_back(6);
  4707. EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
  4708. EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
  4709. }
  4710. #if GTEST_HAS_STD_INITIALIZER_LIST_
  4711. TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
  4712. const vector<int> lhs{2, 4, 6};
  4713. EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
  4714. EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
  4715. }
  4716. #endif // GTEST_HAS_STD_INITIALIZER_LIST_
  4717. TEST(UnorderedPointwiseTest, RejectsWrongSize) {
  4718. const double lhs[2] = {1, 2};
  4719. const int rhs[1] = {0};
  4720. EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
  4721. EXPECT_EQ("which has 2 elements",
  4722. Explain(UnorderedPointwise(Gt(), rhs), lhs));
  4723. const int rhs2[3] = {0, 1, 2};
  4724. EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
  4725. }
  4726. TEST(UnorderedPointwiseTest, RejectsWrongContent) {
  4727. const double lhs[3] = {1, 2, 3};
  4728. const int rhs[3] = {2, 6, 6};
  4729. EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
  4730. EXPECT_EQ("where the following elements don't match any matchers:\n"
  4731. "element #1: 2",
  4732. Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
  4733. }
  4734. TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
  4735. const double lhs[3] = {1, 2, 3};
  4736. const int rhs[3] = {2, 4, 6};
  4737. EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
  4738. }
  4739. TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
  4740. const double lhs[3] = {1, 2, 3};
  4741. const int rhs[3] = {6, 4, 2};
  4742. EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
  4743. }
  4744. TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
  4745. const double lhs[3] = {1, 2, 3};
  4746. const int rhs[3] = {4, 6, 2};
  4747. const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
  4748. EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
  4749. // This type works as a tuple<const double&, const int&> can be
  4750. // implicitly cast to tuple<double, int>.
  4751. const Matcher<tuple<double, int> > m2 = IsHalfOf();
  4752. EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
  4753. }
  4754. } // namespace gmock_matchers_test
  4755. } // namespace testing