gmock-matchers_test.cc 277 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562
  1. // Copyright 2007, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. // Google Mock - a framework for writing C++ mock classes.
  30. //
  31. // This file tests some commonly used argument matchers.
  32. // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
  33. // possible loss of data and C4100, unreferenced local parameter
  34. #ifdef _MSC_VER
  35. # pragma warning(push)
  36. # pragma warning(disable:4244)
  37. # pragma warning(disable:4100)
  38. #endif
  39. #include "gmock/gmock-matchers.h"
  40. #include <string.h>
  41. #include <time.h>
  42. #include <array>
  43. #include <cstdint>
  44. #include <deque>
  45. #include <forward_list>
  46. #include <functional>
  47. #include <iostream>
  48. #include <iterator>
  49. #include <limits>
  50. #include <list>
  51. #include <map>
  52. #include <memory>
  53. #include <set>
  54. #include <sstream>
  55. #include <string>
  56. #include <type_traits>
  57. #include <unordered_map>
  58. #include <unordered_set>
  59. #include <utility>
  60. #include <vector>
  61. #include "gmock/gmock-more-matchers.h"
  62. #include "gmock/gmock.h"
  63. #include "gtest/gtest-spi.h"
  64. #include "gtest/gtest.h"
  65. namespace testing {
  66. namespace gmock_matchers_test {
  67. namespace {
  68. using std::greater;
  69. using std::less;
  70. using std::list;
  71. using std::make_pair;
  72. using std::map;
  73. using std::multimap;
  74. using std::multiset;
  75. using std::ostream;
  76. using std::pair;
  77. using std::set;
  78. using std::stringstream;
  79. using std::vector;
  80. using testing::internal::DummyMatchResultListener;
  81. using testing::internal::ElementMatcherPair;
  82. using testing::internal::ElementMatcherPairs;
  83. using testing::internal::ElementsAreArrayMatcher;
  84. using testing::internal::ExplainMatchFailureTupleTo;
  85. using testing::internal::FloatingEqMatcher;
  86. using testing::internal::FormatMatcherDescription;
  87. using testing::internal::IsReadableTypeName;
  88. using testing::internal::MatchMatrix;
  89. using testing::internal::PredicateFormatterFromMatcher;
  90. using testing::internal::RE;
  91. using testing::internal::StreamMatchResultListener;
  92. using testing::internal::Strings;
  93. // Helper for testing container-valued matchers in mock method context. It is
  94. // important to test matchers in this context, since it requires additional type
  95. // deduction beyond what EXPECT_THAT does, thus making it more restrictive.
  96. struct ContainerHelper {
  97. MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>));
  98. };
  99. std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {
  100. std::vector<std::unique_ptr<int>> pointers;
  101. for (int i : ints) pointers.emplace_back(new int(i));
  102. return pointers;
  103. }
  104. // For testing ExplainMatchResultTo().
  105. class GreaterThanMatcher : public MatcherInterface<int> {
  106. public:
  107. explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
  108. void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; }
  109. bool MatchAndExplain(int lhs, MatchResultListener* listener) const override {
  110. const int diff = lhs - rhs_;
  111. if (diff > 0) {
  112. *listener << "which is " << diff << " more than " << rhs_;
  113. } else if (diff == 0) {
  114. *listener << "which is the same as " << rhs_;
  115. } else {
  116. *listener << "which is " << -diff << " less than " << rhs_;
  117. }
  118. return lhs > rhs_;
  119. }
  120. private:
  121. int rhs_;
  122. };
  123. Matcher<int> GreaterThan(int n) {
  124. return MakeMatcher(new GreaterThanMatcher(n));
  125. }
  126. std::string OfType(const std::string& type_name) {
  127. #if GTEST_HAS_RTTI
  128. return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
  129. #else
  130. return "";
  131. #endif
  132. }
  133. // Returns the description of the given matcher.
  134. template <typename T>
  135. std::string Describe(const Matcher<T>& m) {
  136. return DescribeMatcher<T>(m);
  137. }
  138. // Returns the description of the negation of the given matcher.
  139. template <typename T>
  140. std::string DescribeNegation(const Matcher<T>& m) {
  141. return DescribeMatcher<T>(m, true);
  142. }
  143. // Returns the reason why x matches, or doesn't match, m.
  144. template <typename MatcherType, typename Value>
  145. std::string Explain(const MatcherType& m, const Value& x) {
  146. StringMatchResultListener listener;
  147. ExplainMatchResult(m, x, &listener);
  148. return listener.str();
  149. }
  150. TEST(MonotonicMatcherTest, IsPrintable) {
  151. stringstream ss;
  152. ss << GreaterThan(5);
  153. EXPECT_EQ("is > 5", ss.str());
  154. }
  155. TEST(MatchResultListenerTest, StreamingWorks) {
  156. StringMatchResultListener listener;
  157. listener << "hi" << 5;
  158. EXPECT_EQ("hi5", listener.str());
  159. listener.Clear();
  160. EXPECT_EQ("", listener.str());
  161. listener << 42;
  162. EXPECT_EQ("42", listener.str());
  163. // Streaming shouldn't crash when the underlying ostream is NULL.
  164. DummyMatchResultListener dummy;
  165. dummy << "hi" << 5;
  166. }
  167. TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
  168. EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);
  169. EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);
  170. EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
  171. }
  172. TEST(MatchResultListenerTest, IsInterestedWorks) {
  173. EXPECT_TRUE(StringMatchResultListener().IsInterested());
  174. EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
  175. EXPECT_FALSE(DummyMatchResultListener().IsInterested());
  176. EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());
  177. }
  178. // Makes sure that the MatcherInterface<T> interface doesn't
  179. // change.
  180. class EvenMatcherImpl : public MatcherInterface<int> {
  181. public:
  182. bool MatchAndExplain(int x,
  183. MatchResultListener* /* listener */) const override {
  184. return x % 2 == 0;
  185. }
  186. void DescribeTo(ostream* os) const override { *os << "is an even number"; }
  187. // We deliberately don't define DescribeNegationTo() and
  188. // ExplainMatchResultTo() here, to make sure the definition of these
  189. // two methods is optional.
  190. };
  191. // Makes sure that the MatcherInterface API doesn't change.
  192. TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
  193. EvenMatcherImpl m;
  194. }
  195. // Tests implementing a monomorphic matcher using MatchAndExplain().
  196. class NewEvenMatcherImpl : public MatcherInterface<int> {
  197. public:
  198. bool MatchAndExplain(int x, MatchResultListener* listener) const override {
  199. const bool match = x % 2 == 0;
  200. // Verifies that we can stream to a listener directly.
  201. *listener << "value % " << 2;
  202. if (listener->stream() != nullptr) {
  203. // Verifies that we can stream to a listener's underlying stream
  204. // too.
  205. *listener->stream() << " == " << (x % 2);
  206. }
  207. return match;
  208. }
  209. void DescribeTo(ostream* os) const override { *os << "is an even number"; }
  210. };
  211. TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
  212. Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
  213. EXPECT_TRUE(m.Matches(2));
  214. EXPECT_FALSE(m.Matches(3));
  215. EXPECT_EQ("value % 2 == 0", Explain(m, 2));
  216. EXPECT_EQ("value % 2 == 1", Explain(m, 3));
  217. }
  218. // Tests default-constructing a matcher.
  219. TEST(MatcherTest, CanBeDefaultConstructed) {
  220. Matcher<double> m;
  221. }
  222. // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
  223. TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
  224. const MatcherInterface<int>* impl = new EvenMatcherImpl;
  225. Matcher<int> m(impl);
  226. EXPECT_TRUE(m.Matches(4));
  227. EXPECT_FALSE(m.Matches(5));
  228. }
  229. // Tests that value can be used in place of Eq(value).
  230. TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
  231. Matcher<int> m1 = 5;
  232. EXPECT_TRUE(m1.Matches(5));
  233. EXPECT_FALSE(m1.Matches(6));
  234. }
  235. // Tests that NULL can be used in place of Eq(NULL).
  236. TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
  237. Matcher<int*> m1 = nullptr;
  238. EXPECT_TRUE(m1.Matches(nullptr));
  239. int n = 0;
  240. EXPECT_FALSE(m1.Matches(&n));
  241. }
  242. // Tests that matchers can be constructed from a variable that is not properly
  243. // defined. This should be illegal, but many users rely on this accidentally.
  244. struct Undefined {
  245. virtual ~Undefined() = 0;
  246. static const int kInt = 1;
  247. };
  248. TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
  249. Matcher<int> m1 = Undefined::kInt;
  250. EXPECT_TRUE(m1.Matches(1));
  251. EXPECT_FALSE(m1.Matches(2));
  252. }
  253. // Test that a matcher parameterized with an abstract class compiles.
  254. TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
  255. // Tests that matchers are copyable.
  256. TEST(MatcherTest, IsCopyable) {
  257. // Tests the copy constructor.
  258. Matcher<bool> m1 = Eq(false);
  259. EXPECT_TRUE(m1.Matches(false));
  260. EXPECT_FALSE(m1.Matches(true));
  261. // Tests the assignment operator.
  262. m1 = Eq(true);
  263. EXPECT_TRUE(m1.Matches(true));
  264. EXPECT_FALSE(m1.Matches(false));
  265. }
  266. // Tests that Matcher<T>::DescribeTo() calls
  267. // MatcherInterface<T>::DescribeTo().
  268. TEST(MatcherTest, CanDescribeItself) {
  269. EXPECT_EQ("is an even number",
  270. Describe(Matcher<int>(new EvenMatcherImpl)));
  271. }
  272. // Tests Matcher<T>::MatchAndExplain().
  273. TEST(MatcherTest, MatchAndExplain) {
  274. Matcher<int> m = GreaterThan(0);
  275. StringMatchResultListener listener1;
  276. EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
  277. EXPECT_EQ("which is 42 more than 0", listener1.str());
  278. StringMatchResultListener listener2;
  279. EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
  280. EXPECT_EQ("which is 9 less than 0", listener2.str());
  281. }
  282. // Tests that a C-string literal can be implicitly converted to a
  283. // Matcher<std::string> or Matcher<const std::string&>.
  284. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
  285. Matcher<std::string> m1 = "hi";
  286. EXPECT_TRUE(m1.Matches("hi"));
  287. EXPECT_FALSE(m1.Matches("hello"));
  288. Matcher<const std::string&> m2 = "hi";
  289. EXPECT_TRUE(m2.Matches("hi"));
  290. EXPECT_FALSE(m2.Matches("hello"));
  291. }
  292. // Tests that a string object can be implicitly converted to a
  293. // Matcher<std::string> or Matcher<const std::string&>.
  294. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
  295. Matcher<std::string> m1 = std::string("hi");
  296. EXPECT_TRUE(m1.Matches("hi"));
  297. EXPECT_FALSE(m1.Matches("hello"));
  298. Matcher<const std::string&> m2 = std::string("hi");
  299. EXPECT_TRUE(m2.Matches("hi"));
  300. EXPECT_FALSE(m2.Matches("hello"));
  301. }
  302. #if GTEST_INTERNAL_HAS_STRING_VIEW
  303. // Tests that a C-string literal can be implicitly converted to a
  304. // Matcher<StringView> or Matcher<const StringView&>.
  305. TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
  306. Matcher<internal::StringView> m1 = "cats";
  307. EXPECT_TRUE(m1.Matches("cats"));
  308. EXPECT_FALSE(m1.Matches("dogs"));
  309. Matcher<const internal::StringView&> m2 = "cats";
  310. EXPECT_TRUE(m2.Matches("cats"));
  311. EXPECT_FALSE(m2.Matches("dogs"));
  312. }
  313. // Tests that a std::string object can be implicitly converted to a
  314. // Matcher<StringView> or Matcher<const StringView&>.
  315. TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
  316. Matcher<internal::StringView> m1 = std::string("cats");
  317. EXPECT_TRUE(m1.Matches("cats"));
  318. EXPECT_FALSE(m1.Matches("dogs"));
  319. Matcher<const internal::StringView&> m2 = std::string("cats");
  320. EXPECT_TRUE(m2.Matches("cats"));
  321. EXPECT_FALSE(m2.Matches("dogs"));
  322. }
  323. // Tests that a StringView object can be implicitly converted to a
  324. // Matcher<StringView> or Matcher<const StringView&>.
  325. TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
  326. Matcher<internal::StringView> m1 = internal::StringView("cats");
  327. EXPECT_TRUE(m1.Matches("cats"));
  328. EXPECT_FALSE(m1.Matches("dogs"));
  329. Matcher<const internal::StringView&> m2 = internal::StringView("cats");
  330. EXPECT_TRUE(m2.Matches("cats"));
  331. EXPECT_FALSE(m2.Matches("dogs"));
  332. }
  333. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  334. // Tests that a std::reference_wrapper<std::string> object can be implicitly
  335. // converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
  336. TEST(StringMatcherTest,
  337. CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
  338. std::string value = "cats";
  339. Matcher<std::string> m1 = Eq(std::ref(value));
  340. EXPECT_TRUE(m1.Matches("cats"));
  341. EXPECT_FALSE(m1.Matches("dogs"));
  342. Matcher<const std::string&> m2 = Eq(std::ref(value));
  343. EXPECT_TRUE(m2.Matches("cats"));
  344. EXPECT_FALSE(m2.Matches("dogs"));
  345. }
  346. // Tests that MakeMatcher() constructs a Matcher<T> from a
  347. // MatcherInterface* without requiring the user to explicitly
  348. // write the type.
  349. TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
  350. const MatcherInterface<int>* dummy_impl = new EvenMatcherImpl;
  351. Matcher<int> m = MakeMatcher(dummy_impl);
  352. }
  353. // Tests that MakePolymorphicMatcher() can construct a polymorphic
  354. // matcher from its implementation using the old API.
  355. const int g_bar = 1;
  356. class ReferencesBarOrIsZeroImpl {
  357. public:
  358. template <typename T>
  359. bool MatchAndExplain(const T& x,
  360. MatchResultListener* /* listener */) const {
  361. const void* p = &x;
  362. return p == &g_bar || x == 0;
  363. }
  364. void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
  365. void DescribeNegationTo(ostream* os) const {
  366. *os << "doesn't reference g_bar and is not zero";
  367. }
  368. };
  369. // This function verifies that MakePolymorphicMatcher() returns a
  370. // PolymorphicMatcher<T> where T is the argument's type.
  371. PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
  372. return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
  373. }
  374. TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
  375. // Using a polymorphic matcher to match a reference type.
  376. Matcher<const int&> m1 = ReferencesBarOrIsZero();
  377. EXPECT_TRUE(m1.Matches(0));
  378. // Verifies that the identity of a by-reference argument is preserved.
  379. EXPECT_TRUE(m1.Matches(g_bar));
  380. EXPECT_FALSE(m1.Matches(1));
  381. EXPECT_EQ("g_bar or zero", Describe(m1));
  382. // Using a polymorphic matcher to match a value type.
  383. Matcher<double> m2 = ReferencesBarOrIsZero();
  384. EXPECT_TRUE(m2.Matches(0.0));
  385. EXPECT_FALSE(m2.Matches(0.1));
  386. EXPECT_EQ("g_bar or zero", Describe(m2));
  387. }
  388. // Tests implementing a polymorphic matcher using MatchAndExplain().
  389. class PolymorphicIsEvenImpl {
  390. public:
  391. void DescribeTo(ostream* os) const { *os << "is even"; }
  392. void DescribeNegationTo(ostream* os) const {
  393. *os << "is odd";
  394. }
  395. template <typename T>
  396. bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
  397. // Verifies that we can stream to the listener directly.
  398. *listener << "% " << 2;
  399. if (listener->stream() != nullptr) {
  400. // Verifies that we can stream to the listener's underlying stream
  401. // too.
  402. *listener->stream() << " == " << (x % 2);
  403. }
  404. return (x % 2) == 0;
  405. }
  406. };
  407. PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
  408. return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
  409. }
  410. TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
  411. // Using PolymorphicIsEven() as a Matcher<int>.
  412. const Matcher<int> m1 = PolymorphicIsEven();
  413. EXPECT_TRUE(m1.Matches(42));
  414. EXPECT_FALSE(m1.Matches(43));
  415. EXPECT_EQ("is even", Describe(m1));
  416. const Matcher<int> not_m1 = Not(m1);
  417. EXPECT_EQ("is odd", Describe(not_m1));
  418. EXPECT_EQ("% 2 == 0", Explain(m1, 42));
  419. // Using PolymorphicIsEven() as a Matcher<char>.
  420. const Matcher<char> m2 = PolymorphicIsEven();
  421. EXPECT_TRUE(m2.Matches('\x42'));
  422. EXPECT_FALSE(m2.Matches('\x43'));
  423. EXPECT_EQ("is even", Describe(m2));
  424. const Matcher<char> not_m2 = Not(m2);
  425. EXPECT_EQ("is odd", Describe(not_m2));
  426. EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
  427. }
  428. // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
  429. TEST(MatcherCastTest, FromPolymorphicMatcher) {
  430. Matcher<int> m = MatcherCast<int>(Eq(5));
  431. EXPECT_TRUE(m.Matches(5));
  432. EXPECT_FALSE(m.Matches(6));
  433. }
  434. // For testing casting matchers between compatible types.
  435. class IntValue {
  436. public:
  437. // An int can be statically (although not implicitly) cast to a
  438. // IntValue.
  439. explicit IntValue(int a_value) : value_(a_value) {}
  440. int value() const { return value_; }
  441. private:
  442. int value_;
  443. };
  444. // For testing casting matchers between compatible types.
  445. bool IsPositiveIntValue(const IntValue& foo) {
  446. return foo.value() > 0;
  447. }
  448. // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
  449. // can be statically converted to U.
  450. TEST(MatcherCastTest, FromCompatibleType) {
  451. Matcher<double> m1 = Eq(2.0);
  452. Matcher<int> m2 = MatcherCast<int>(m1);
  453. EXPECT_TRUE(m2.Matches(2));
  454. EXPECT_FALSE(m2.Matches(3));
  455. Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
  456. Matcher<int> m4 = MatcherCast<int>(m3);
  457. // In the following, the arguments 1 and 0 are statically converted
  458. // to IntValue objects, and then tested by the IsPositiveIntValue()
  459. // predicate.
  460. EXPECT_TRUE(m4.Matches(1));
  461. EXPECT_FALSE(m4.Matches(0));
  462. }
  463. // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
  464. TEST(MatcherCastTest, FromConstReferenceToNonReference) {
  465. Matcher<const int&> m1 = Eq(0);
  466. Matcher<int> m2 = MatcherCast<int>(m1);
  467. EXPECT_TRUE(m2.Matches(0));
  468. EXPECT_FALSE(m2.Matches(1));
  469. }
  470. // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
  471. TEST(MatcherCastTest, FromReferenceToNonReference) {
  472. Matcher<int&> m1 = Eq(0);
  473. Matcher<int> m2 = MatcherCast<int>(m1);
  474. EXPECT_TRUE(m2.Matches(0));
  475. EXPECT_FALSE(m2.Matches(1));
  476. }
  477. // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
  478. TEST(MatcherCastTest, FromNonReferenceToConstReference) {
  479. Matcher<int> m1 = Eq(0);
  480. Matcher<const int&> m2 = MatcherCast<const int&>(m1);
  481. EXPECT_TRUE(m2.Matches(0));
  482. EXPECT_FALSE(m2.Matches(1));
  483. }
  484. // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
  485. TEST(MatcherCastTest, FromNonReferenceToReference) {
  486. Matcher<int> m1 = Eq(0);
  487. Matcher<int&> m2 = MatcherCast<int&>(m1);
  488. int n = 0;
  489. EXPECT_TRUE(m2.Matches(n));
  490. n = 1;
  491. EXPECT_FALSE(m2.Matches(n));
  492. }
  493. // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
  494. TEST(MatcherCastTest, FromSameType) {
  495. Matcher<int> m1 = Eq(0);
  496. Matcher<int> m2 = MatcherCast<int>(m1);
  497. EXPECT_TRUE(m2.Matches(0));
  498. EXPECT_FALSE(m2.Matches(1));
  499. }
  500. // Tests that MatcherCast<T>(m) works when m is a value of the same type as the
  501. // value type of the Matcher.
  502. TEST(MatcherCastTest, FromAValue) {
  503. Matcher<int> m = MatcherCast<int>(42);
  504. EXPECT_TRUE(m.Matches(42));
  505. EXPECT_FALSE(m.Matches(239));
  506. }
  507. // Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
  508. // convertible to the value type of the Matcher.
  509. TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
  510. const int kExpected = 'c';
  511. Matcher<int> m = MatcherCast<int>('c');
  512. EXPECT_TRUE(m.Matches(kExpected));
  513. EXPECT_FALSE(m.Matches(kExpected + 1));
  514. }
  515. struct NonImplicitlyConstructibleTypeWithOperatorEq {
  516. friend bool operator==(
  517. const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
  518. int rhs) {
  519. return 42 == rhs;
  520. }
  521. friend bool operator==(
  522. int lhs,
  523. const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
  524. return lhs == 42;
  525. }
  526. };
  527. // Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
  528. // implicitly convertible to the value type of the Matcher, but the value type
  529. // of the matcher has operator==() overload accepting m.
  530. TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
  531. Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
  532. MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
  533. EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
  534. Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
  535. MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
  536. EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
  537. // When updating the following lines please also change the comment to
  538. // namespace convertible_from_any.
  539. Matcher<int> m3 =
  540. MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
  541. EXPECT_TRUE(m3.Matches(42));
  542. EXPECT_FALSE(m3.Matches(239));
  543. }
  544. // ConvertibleFromAny does not work with MSVC. resulting in
  545. // error C2440: 'initializing': cannot convert from 'Eq' to 'M'
  546. // No constructor could take the source type, or constructor overload
  547. // resolution was ambiguous
  548. #if !defined _MSC_VER
  549. // The below ConvertibleFromAny struct is implicitly constructible from anything
  550. // and when in the same namespace can interact with other tests. In particular,
  551. // if it is in the same namespace as other tests and one removes
  552. // NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
  553. // then the corresponding test still compiles (and it should not!) by implicitly
  554. // converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
  555. // in m3.Matcher().
  556. namespace convertible_from_any {
  557. // Implicitly convertible from any type.
  558. struct ConvertibleFromAny {
  559. ConvertibleFromAny(int a_value) : value(a_value) {}
  560. template <typename T>
  561. ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
  562. ADD_FAILURE() << "Conversion constructor called";
  563. }
  564. int value;
  565. };
  566. bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
  567. return a.value == b.value;
  568. }
  569. ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
  570. return os << a.value;
  571. }
  572. TEST(MatcherCastTest, ConversionConstructorIsUsed) {
  573. Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
  574. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  575. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  576. }
  577. TEST(MatcherCastTest, FromConvertibleFromAny) {
  578. Matcher<ConvertibleFromAny> m =
  579. MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
  580. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  581. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  582. }
  583. } // namespace convertible_from_any
  584. #endif // !defined _MSC_VER
  585. struct IntReferenceWrapper {
  586. IntReferenceWrapper(const int& a_value) : value(&a_value) {}
  587. const int* value;
  588. };
  589. bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
  590. return a.value == b.value;
  591. }
  592. TEST(MatcherCastTest, ValueIsNotCopied) {
  593. int n = 42;
  594. Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
  595. // Verify that the matcher holds a reference to n, not to its temporary copy.
  596. EXPECT_TRUE(m.Matches(n));
  597. }
  598. class Base {
  599. public:
  600. virtual ~Base() {}
  601. Base() {}
  602. private:
  603. GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
  604. };
  605. class Derived : public Base {
  606. public:
  607. Derived() : Base() {}
  608. int i;
  609. };
  610. class OtherDerived : public Base {};
  611. // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
  612. TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
  613. Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
  614. EXPECT_TRUE(m2.Matches(' '));
  615. EXPECT_FALSE(m2.Matches('\n'));
  616. }
  617. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
  618. // T and U are arithmetic types and T can be losslessly converted to
  619. // U.
  620. TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
  621. Matcher<double> m1 = DoubleEq(1.0);
  622. Matcher<float> m2 = SafeMatcherCast<float>(m1);
  623. EXPECT_TRUE(m2.Matches(1.0f));
  624. EXPECT_FALSE(m2.Matches(2.0f));
  625. Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
  626. EXPECT_TRUE(m3.Matches('a'));
  627. EXPECT_FALSE(m3.Matches('b'));
  628. }
  629. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
  630. // are pointers or references to a derived and a base class, correspondingly.
  631. TEST(SafeMatcherCastTest, FromBaseClass) {
  632. Derived d, d2;
  633. Matcher<Base*> m1 = Eq(&d);
  634. Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
  635. EXPECT_TRUE(m2.Matches(&d));
  636. EXPECT_FALSE(m2.Matches(&d2));
  637. Matcher<Base&> m3 = Ref(d);
  638. Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
  639. EXPECT_TRUE(m4.Matches(d));
  640. EXPECT_FALSE(m4.Matches(d2));
  641. }
  642. // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
  643. TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
  644. int n = 0;
  645. Matcher<const int&> m1 = Ref(n);
  646. Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
  647. int n1 = 0;
  648. EXPECT_TRUE(m2.Matches(n));
  649. EXPECT_FALSE(m2.Matches(n1));
  650. }
  651. // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
  652. TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
  653. Matcher<std::unique_ptr<int>> m1 = IsNull();
  654. Matcher<const std::unique_ptr<int>&> m2 =
  655. SafeMatcherCast<const std::unique_ptr<int>&>(m1);
  656. EXPECT_TRUE(m2.Matches(std::unique_ptr<int>()));
  657. EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(new int)));
  658. }
  659. // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
  660. TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
  661. Matcher<int> m1 = Eq(0);
  662. Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
  663. int n = 0;
  664. EXPECT_TRUE(m2.Matches(n));
  665. n = 1;
  666. EXPECT_FALSE(m2.Matches(n));
  667. }
  668. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
  669. TEST(SafeMatcherCastTest, FromSameType) {
  670. Matcher<int> m1 = Eq(0);
  671. Matcher<int> m2 = SafeMatcherCast<int>(m1);
  672. EXPECT_TRUE(m2.Matches(0));
  673. EXPECT_FALSE(m2.Matches(1));
  674. }
  675. #if !defined _MSC_VER
  676. namespace convertible_from_any {
  677. TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
  678. Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
  679. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  680. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  681. }
  682. TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
  683. Matcher<ConvertibleFromAny> m =
  684. SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
  685. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  686. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  687. }
  688. } // namespace convertible_from_any
  689. #endif // !defined _MSC_VER
  690. TEST(SafeMatcherCastTest, ValueIsNotCopied) {
  691. int n = 42;
  692. Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
  693. // Verify that the matcher holds a reference to n, not to its temporary copy.
  694. EXPECT_TRUE(m.Matches(n));
  695. }
  696. TEST(ExpectThat, TakesLiterals) {
  697. EXPECT_THAT(1, 1);
  698. EXPECT_THAT(1.0, 1.0);
  699. EXPECT_THAT(std::string(), "");
  700. }
  701. TEST(ExpectThat, TakesFunctions) {
  702. struct Helper {
  703. static void Func() {}
  704. };
  705. void (*func)() = Helper::Func;
  706. EXPECT_THAT(func, Helper::Func);
  707. EXPECT_THAT(func, &Helper::Func);
  708. }
  709. // Tests that A<T>() matches any value of type T.
  710. TEST(ATest, MatchesAnyValue) {
  711. // Tests a matcher for a value type.
  712. Matcher<double> m1 = A<double>();
  713. EXPECT_TRUE(m1.Matches(91.43));
  714. EXPECT_TRUE(m1.Matches(-15.32));
  715. // Tests a matcher for a reference type.
  716. int a = 2;
  717. int b = -6;
  718. Matcher<int&> m2 = A<int&>();
  719. EXPECT_TRUE(m2.Matches(a));
  720. EXPECT_TRUE(m2.Matches(b));
  721. }
  722. TEST(ATest, WorksForDerivedClass) {
  723. Base base;
  724. Derived derived;
  725. EXPECT_THAT(&base, A<Base*>());
  726. // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
  727. EXPECT_THAT(&derived, A<Base*>());
  728. EXPECT_THAT(&derived, A<Derived*>());
  729. }
  730. // Tests that A<T>() describes itself properly.
  731. TEST(ATest, CanDescribeSelf) {
  732. EXPECT_EQ("is anything", Describe(A<bool>()));
  733. }
  734. // Tests that An<T>() matches any value of type T.
  735. TEST(AnTest, MatchesAnyValue) {
  736. // Tests a matcher for a value type.
  737. Matcher<int> m1 = An<int>();
  738. EXPECT_TRUE(m1.Matches(9143));
  739. EXPECT_TRUE(m1.Matches(-1532));
  740. // Tests a matcher for a reference type.
  741. int a = 2;
  742. int b = -6;
  743. Matcher<int&> m2 = An<int&>();
  744. EXPECT_TRUE(m2.Matches(a));
  745. EXPECT_TRUE(m2.Matches(b));
  746. }
  747. // Tests that An<T>() describes itself properly.
  748. TEST(AnTest, CanDescribeSelf) {
  749. EXPECT_EQ("is anything", Describe(An<int>()));
  750. }
  751. // Tests that _ can be used as a matcher for any type and matches any
  752. // value of that type.
  753. TEST(UnderscoreTest, MatchesAnyValue) {
  754. // Uses _ as a matcher for a value type.
  755. Matcher<int> m1 = _;
  756. EXPECT_TRUE(m1.Matches(123));
  757. EXPECT_TRUE(m1.Matches(-242));
  758. // Uses _ as a matcher for a reference type.
  759. bool a = false;
  760. const bool b = true;
  761. Matcher<const bool&> m2 = _;
  762. EXPECT_TRUE(m2.Matches(a));
  763. EXPECT_TRUE(m2.Matches(b));
  764. }
  765. // Tests that _ describes itself properly.
  766. TEST(UnderscoreTest, CanDescribeSelf) {
  767. Matcher<int> m = _;
  768. EXPECT_EQ("is anything", Describe(m));
  769. }
  770. // Tests that Eq(x) matches any value equal to x.
  771. TEST(EqTest, MatchesEqualValue) {
  772. // 2 C-strings with same content but different addresses.
  773. const char a1[] = "hi";
  774. const char a2[] = "hi";
  775. Matcher<const char*> m1 = Eq(a1);
  776. EXPECT_TRUE(m1.Matches(a1));
  777. EXPECT_FALSE(m1.Matches(a2));
  778. }
  779. // Tests that Eq(v) describes itself properly.
  780. class Unprintable {
  781. public:
  782. Unprintable() : c_('a') {}
  783. bool operator==(const Unprintable& /* rhs */) const { return true; }
  784. // -Wunused-private-field: dummy accessor for `c_`.
  785. char dummy_c() { return c_; }
  786. private:
  787. char c_;
  788. };
  789. TEST(EqTest, CanDescribeSelf) {
  790. Matcher<Unprintable> m = Eq(Unprintable());
  791. EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
  792. }
  793. // Tests that Eq(v) can be used to match any type that supports
  794. // comparing with type T, where T is v's type.
  795. TEST(EqTest, IsPolymorphic) {
  796. Matcher<int> m1 = Eq(1);
  797. EXPECT_TRUE(m1.Matches(1));
  798. EXPECT_FALSE(m1.Matches(2));
  799. Matcher<char> m2 = Eq(1);
  800. EXPECT_TRUE(m2.Matches('\1'));
  801. EXPECT_FALSE(m2.Matches('a'));
  802. }
  803. // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
  804. TEST(TypedEqTest, ChecksEqualityForGivenType) {
  805. Matcher<char> m1 = TypedEq<char>('a');
  806. EXPECT_TRUE(m1.Matches('a'));
  807. EXPECT_FALSE(m1.Matches('b'));
  808. Matcher<int> m2 = TypedEq<int>(6);
  809. EXPECT_TRUE(m2.Matches(6));
  810. EXPECT_FALSE(m2.Matches(7));
  811. }
  812. // Tests that TypedEq(v) describes itself properly.
  813. TEST(TypedEqTest, CanDescribeSelf) {
  814. EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
  815. }
  816. // Tests that TypedEq<T>(v) has type Matcher<T>.
  817. // Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where
  818. // T is a "bare" type (i.e. not in the form of const U or U&). If v's type is
  819. // not T, the compiler will generate a message about "undefined reference".
  820. template <typename T>
  821. struct Type {
  822. static bool IsTypeOf(const T& /* v */) { return true; }
  823. template <typename T2>
  824. static void IsTypeOf(T2 v);
  825. };
  826. TEST(TypedEqTest, HasSpecifiedType) {
  827. // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
  828. Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
  829. Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
  830. }
  831. // Tests that Ge(v) matches anything >= v.
  832. TEST(GeTest, ImplementsGreaterThanOrEqual) {
  833. Matcher<int> m1 = Ge(0);
  834. EXPECT_TRUE(m1.Matches(1));
  835. EXPECT_TRUE(m1.Matches(0));
  836. EXPECT_FALSE(m1.Matches(-1));
  837. }
  838. // Tests that Ge(v) describes itself properly.
  839. TEST(GeTest, CanDescribeSelf) {
  840. Matcher<int> m = Ge(5);
  841. EXPECT_EQ("is >= 5", Describe(m));
  842. }
  843. // Tests that Gt(v) matches anything > v.
  844. TEST(GtTest, ImplementsGreaterThan) {
  845. Matcher<double> m1 = Gt(0);
  846. EXPECT_TRUE(m1.Matches(1.0));
  847. EXPECT_FALSE(m1.Matches(0.0));
  848. EXPECT_FALSE(m1.Matches(-1.0));
  849. }
  850. // Tests that Gt(v) describes itself properly.
  851. TEST(GtTest, CanDescribeSelf) {
  852. Matcher<int> m = Gt(5);
  853. EXPECT_EQ("is > 5", Describe(m));
  854. }
  855. // Tests that Le(v) matches anything <= v.
  856. TEST(LeTest, ImplementsLessThanOrEqual) {
  857. Matcher<char> m1 = Le('b');
  858. EXPECT_TRUE(m1.Matches('a'));
  859. EXPECT_TRUE(m1.Matches('b'));
  860. EXPECT_FALSE(m1.Matches('c'));
  861. }
  862. // Tests that Le(v) describes itself properly.
  863. TEST(LeTest, CanDescribeSelf) {
  864. Matcher<int> m = Le(5);
  865. EXPECT_EQ("is <= 5", Describe(m));
  866. }
  867. // Tests that Lt(v) matches anything < v.
  868. TEST(LtTest, ImplementsLessThan) {
  869. Matcher<const std::string&> m1 = Lt("Hello");
  870. EXPECT_TRUE(m1.Matches("Abc"));
  871. EXPECT_FALSE(m1.Matches("Hello"));
  872. EXPECT_FALSE(m1.Matches("Hello, world!"));
  873. }
  874. // Tests that Lt(v) describes itself properly.
  875. TEST(LtTest, CanDescribeSelf) {
  876. Matcher<int> m = Lt(5);
  877. EXPECT_EQ("is < 5", Describe(m));
  878. }
  879. // Tests that Ne(v) matches anything != v.
  880. TEST(NeTest, ImplementsNotEqual) {
  881. Matcher<int> m1 = Ne(0);
  882. EXPECT_TRUE(m1.Matches(1));
  883. EXPECT_TRUE(m1.Matches(-1));
  884. EXPECT_FALSE(m1.Matches(0));
  885. }
  886. // Tests that Ne(v) describes itself properly.
  887. TEST(NeTest, CanDescribeSelf) {
  888. Matcher<int> m = Ne(5);
  889. EXPECT_EQ("isn't equal to 5", Describe(m));
  890. }
  891. class MoveOnly {
  892. public:
  893. explicit MoveOnly(int i) : i_(i) {}
  894. MoveOnly(const MoveOnly&) = delete;
  895. MoveOnly(MoveOnly&&) = default;
  896. MoveOnly& operator=(const MoveOnly&) = delete;
  897. MoveOnly& operator=(MoveOnly&&) = default;
  898. bool operator==(const MoveOnly& other) const { return i_ == other.i_; }
  899. bool operator!=(const MoveOnly& other) const { return i_ != other.i_; }
  900. bool operator<(const MoveOnly& other) const { return i_ < other.i_; }
  901. bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; }
  902. bool operator>(const MoveOnly& other) const { return i_ > other.i_; }
  903. bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; }
  904. private:
  905. int i_;
  906. };
  907. struct MoveHelper {
  908. MOCK_METHOD1(Call, void(MoveOnly));
  909. };
  910. // Disable this test in VS 2015 (version 14), where it fails when SEH is enabled
  911. #if defined(_MSC_VER) && (_MSC_VER < 1910)
  912. TEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) {
  913. #else
  914. TEST(ComparisonBaseTest, WorksWithMoveOnly) {
  915. #endif
  916. MoveOnly m{0};
  917. MoveHelper helper;
  918. EXPECT_CALL(helper, Call(Eq(ByRef(m))));
  919. helper.Call(MoveOnly(0));
  920. EXPECT_CALL(helper, Call(Ne(ByRef(m))));
  921. helper.Call(MoveOnly(1));
  922. EXPECT_CALL(helper, Call(Le(ByRef(m))));
  923. helper.Call(MoveOnly(0));
  924. EXPECT_CALL(helper, Call(Lt(ByRef(m))));
  925. helper.Call(MoveOnly(-1));
  926. EXPECT_CALL(helper, Call(Ge(ByRef(m))));
  927. helper.Call(MoveOnly(0));
  928. EXPECT_CALL(helper, Call(Gt(ByRef(m))));
  929. helper.Call(MoveOnly(1));
  930. }
  931. // Tests that IsNull() matches any NULL pointer of any type.
  932. TEST(IsNullTest, MatchesNullPointer) {
  933. Matcher<int*> m1 = IsNull();
  934. int* p1 = nullptr;
  935. int n = 0;
  936. EXPECT_TRUE(m1.Matches(p1));
  937. EXPECT_FALSE(m1.Matches(&n));
  938. Matcher<const char*> m2 = IsNull();
  939. const char* p2 = nullptr;
  940. EXPECT_TRUE(m2.Matches(p2));
  941. EXPECT_FALSE(m2.Matches("hi"));
  942. Matcher<void*> m3 = IsNull();
  943. void* p3 = nullptr;
  944. EXPECT_TRUE(m3.Matches(p3));
  945. EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
  946. }
  947. TEST(IsNullTest, StdFunction) {
  948. const Matcher<std::function<void()>> m = IsNull();
  949. EXPECT_TRUE(m.Matches(std::function<void()>()));
  950. EXPECT_FALSE(m.Matches([]{}));
  951. }
  952. // Tests that IsNull() describes itself properly.
  953. TEST(IsNullTest, CanDescribeSelf) {
  954. Matcher<int*> m = IsNull();
  955. EXPECT_EQ("is NULL", Describe(m));
  956. EXPECT_EQ("isn't NULL", DescribeNegation(m));
  957. }
  958. // Tests that NotNull() matches any non-NULL pointer of any type.
  959. TEST(NotNullTest, MatchesNonNullPointer) {
  960. Matcher<int*> m1 = NotNull();
  961. int* p1 = nullptr;
  962. int n = 0;
  963. EXPECT_FALSE(m1.Matches(p1));
  964. EXPECT_TRUE(m1.Matches(&n));
  965. Matcher<const char*> m2 = NotNull();
  966. const char* p2 = nullptr;
  967. EXPECT_FALSE(m2.Matches(p2));
  968. EXPECT_TRUE(m2.Matches("hi"));
  969. }
  970. TEST(NotNullTest, LinkedPtr) {
  971. const Matcher<std::shared_ptr<int>> m = NotNull();
  972. const std::shared_ptr<int> null_p;
  973. const std::shared_ptr<int> non_null_p(new int);
  974. EXPECT_FALSE(m.Matches(null_p));
  975. EXPECT_TRUE(m.Matches(non_null_p));
  976. }
  977. TEST(NotNullTest, ReferenceToConstLinkedPtr) {
  978. const Matcher<const std::shared_ptr<double>&> m = NotNull();
  979. const std::shared_ptr<double> null_p;
  980. const std::shared_ptr<double> non_null_p(new double);
  981. EXPECT_FALSE(m.Matches(null_p));
  982. EXPECT_TRUE(m.Matches(non_null_p));
  983. }
  984. TEST(NotNullTest, StdFunction) {
  985. const Matcher<std::function<void()>> m = NotNull();
  986. EXPECT_TRUE(m.Matches([]{}));
  987. EXPECT_FALSE(m.Matches(std::function<void()>()));
  988. }
  989. // Tests that NotNull() describes itself properly.
  990. TEST(NotNullTest, CanDescribeSelf) {
  991. Matcher<int*> m = NotNull();
  992. EXPECT_EQ("isn't NULL", Describe(m));
  993. }
  994. // Tests that Ref(variable) matches an argument that references
  995. // 'variable'.
  996. TEST(RefTest, MatchesSameVariable) {
  997. int a = 0;
  998. int b = 0;
  999. Matcher<int&> m = Ref(a);
  1000. EXPECT_TRUE(m.Matches(a));
  1001. EXPECT_FALSE(m.Matches(b));
  1002. }
  1003. // Tests that Ref(variable) describes itself properly.
  1004. TEST(RefTest, CanDescribeSelf) {
  1005. int n = 5;
  1006. Matcher<int&> m = Ref(n);
  1007. stringstream ss;
  1008. ss << "references the variable @" << &n << " 5";
  1009. EXPECT_EQ(ss.str(), Describe(m));
  1010. }
  1011. // Test that Ref(non_const_varialbe) can be used as a matcher for a
  1012. // const reference.
  1013. TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
  1014. int a = 0;
  1015. int b = 0;
  1016. Matcher<const int&> m = Ref(a);
  1017. EXPECT_TRUE(m.Matches(a));
  1018. EXPECT_FALSE(m.Matches(b));
  1019. }
  1020. // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
  1021. // used wherever Ref(base) can be used (Ref(derived) is a sub-type
  1022. // of Ref(base), but not vice versa.
  1023. TEST(RefTest, IsCovariant) {
  1024. Base base, base2;
  1025. Derived derived;
  1026. Matcher<const Base&> m1 = Ref(base);
  1027. EXPECT_TRUE(m1.Matches(base));
  1028. EXPECT_FALSE(m1.Matches(base2));
  1029. EXPECT_FALSE(m1.Matches(derived));
  1030. m1 = Ref(derived);
  1031. EXPECT_TRUE(m1.Matches(derived));
  1032. EXPECT_FALSE(m1.Matches(base));
  1033. EXPECT_FALSE(m1.Matches(base2));
  1034. }
  1035. TEST(RefTest, ExplainsResult) {
  1036. int n = 0;
  1037. EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
  1038. StartsWith("which is located @"));
  1039. int m = 0;
  1040. EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
  1041. StartsWith("which is located @"));
  1042. }
  1043. // Tests string comparison matchers.
  1044. template <typename T = std::string>
  1045. std::string FromStringLike(internal::StringLike<T> str) {
  1046. return std::string(str);
  1047. }
  1048. TEST(StringLike, TestConversions) {
  1049. EXPECT_EQ("foo", FromStringLike("foo"));
  1050. EXPECT_EQ("foo", FromStringLike(std::string("foo")));
  1051. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1052. EXPECT_EQ("foo", FromStringLike(internal::StringView("foo")));
  1053. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1054. // Non deducible types.
  1055. EXPECT_EQ("", FromStringLike({}));
  1056. EXPECT_EQ("foo", FromStringLike({'f', 'o', 'o'}));
  1057. const char buf[] = "foo";
  1058. EXPECT_EQ("foo", FromStringLike({buf, buf + 3}));
  1059. }
  1060. TEST(StrEqTest, MatchesEqualString) {
  1061. Matcher<const char*> m = StrEq(std::string("Hello"));
  1062. EXPECT_TRUE(m.Matches("Hello"));
  1063. EXPECT_FALSE(m.Matches("hello"));
  1064. EXPECT_FALSE(m.Matches(nullptr));
  1065. Matcher<const std::string&> m2 = StrEq("Hello");
  1066. EXPECT_TRUE(m2.Matches("Hello"));
  1067. EXPECT_FALSE(m2.Matches("Hi"));
  1068. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1069. Matcher<const internal::StringView&> m3 =
  1070. StrEq(internal::StringView("Hello"));
  1071. EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
  1072. EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
  1073. EXPECT_FALSE(m3.Matches(internal::StringView()));
  1074. Matcher<const internal::StringView&> m_empty = StrEq("");
  1075. EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
  1076. EXPECT_TRUE(m_empty.Matches(internal::StringView()));
  1077. EXPECT_FALSE(m_empty.Matches(internal::StringView("hello")));
  1078. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1079. }
  1080. TEST(StrEqTest, CanDescribeSelf) {
  1081. Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
  1082. EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
  1083. Describe(m));
  1084. std::string str("01204500800");
  1085. str[3] = '\0';
  1086. Matcher<std::string> m2 = StrEq(str);
  1087. EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
  1088. str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
  1089. Matcher<std::string> m3 = StrEq(str);
  1090. EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
  1091. }
  1092. TEST(StrNeTest, MatchesUnequalString) {
  1093. Matcher<const char*> m = StrNe("Hello");
  1094. EXPECT_TRUE(m.Matches(""));
  1095. EXPECT_TRUE(m.Matches(nullptr));
  1096. EXPECT_FALSE(m.Matches("Hello"));
  1097. Matcher<std::string> m2 = StrNe(std::string("Hello"));
  1098. EXPECT_TRUE(m2.Matches("hello"));
  1099. EXPECT_FALSE(m2.Matches("Hello"));
  1100. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1101. Matcher<const internal::StringView> m3 = StrNe(internal::StringView("Hello"));
  1102. EXPECT_TRUE(m3.Matches(internal::StringView("")));
  1103. EXPECT_TRUE(m3.Matches(internal::StringView()));
  1104. EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
  1105. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1106. }
  1107. TEST(StrNeTest, CanDescribeSelf) {
  1108. Matcher<const char*> m = StrNe("Hi");
  1109. EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
  1110. }
  1111. TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
  1112. Matcher<const char*> m = StrCaseEq(std::string("Hello"));
  1113. EXPECT_TRUE(m.Matches("Hello"));
  1114. EXPECT_TRUE(m.Matches("hello"));
  1115. EXPECT_FALSE(m.Matches("Hi"));
  1116. EXPECT_FALSE(m.Matches(nullptr));
  1117. Matcher<const std::string&> m2 = StrCaseEq("Hello");
  1118. EXPECT_TRUE(m2.Matches("hello"));
  1119. EXPECT_FALSE(m2.Matches("Hi"));
  1120. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1121. Matcher<const internal::StringView&> m3 =
  1122. StrCaseEq(internal::StringView("Hello"));
  1123. EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
  1124. EXPECT_TRUE(m3.Matches(internal::StringView("hello")));
  1125. EXPECT_FALSE(m3.Matches(internal::StringView("Hi")));
  1126. EXPECT_FALSE(m3.Matches(internal::StringView()));
  1127. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1128. }
  1129. TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
  1130. std::string str1("oabocdooeoo");
  1131. std::string str2("OABOCDOOEOO");
  1132. Matcher<const std::string&> m0 = StrCaseEq(str1);
  1133. EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
  1134. str1[3] = str2[3] = '\0';
  1135. Matcher<const std::string&> m1 = StrCaseEq(str1);
  1136. EXPECT_TRUE(m1.Matches(str2));
  1137. str1[0] = str1[6] = str1[7] = str1[10] = '\0';
  1138. str2[0] = str2[6] = str2[7] = str2[10] = '\0';
  1139. Matcher<const std::string&> m2 = StrCaseEq(str1);
  1140. str1[9] = str2[9] = '\0';
  1141. EXPECT_FALSE(m2.Matches(str2));
  1142. Matcher<const std::string&> m3 = StrCaseEq(str1);
  1143. EXPECT_TRUE(m3.Matches(str2));
  1144. EXPECT_FALSE(m3.Matches(str2 + "x"));
  1145. str2.append(1, '\0');
  1146. EXPECT_FALSE(m3.Matches(str2));
  1147. EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
  1148. }
  1149. TEST(StrCaseEqTest, CanDescribeSelf) {
  1150. Matcher<std::string> m = StrCaseEq("Hi");
  1151. EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
  1152. }
  1153. TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
  1154. Matcher<const char*> m = StrCaseNe("Hello");
  1155. EXPECT_TRUE(m.Matches("Hi"));
  1156. EXPECT_TRUE(m.Matches(nullptr));
  1157. EXPECT_FALSE(m.Matches("Hello"));
  1158. EXPECT_FALSE(m.Matches("hello"));
  1159. Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
  1160. EXPECT_TRUE(m2.Matches(""));
  1161. EXPECT_FALSE(m2.Matches("Hello"));
  1162. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1163. Matcher<const internal::StringView> m3 =
  1164. StrCaseNe(internal::StringView("Hello"));
  1165. EXPECT_TRUE(m3.Matches(internal::StringView("Hi")));
  1166. EXPECT_TRUE(m3.Matches(internal::StringView()));
  1167. EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
  1168. EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
  1169. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1170. }
  1171. TEST(StrCaseNeTest, CanDescribeSelf) {
  1172. Matcher<const char*> m = StrCaseNe("Hi");
  1173. EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
  1174. }
  1175. // Tests that HasSubstr() works for matching string-typed values.
  1176. TEST(HasSubstrTest, WorksForStringClasses) {
  1177. const Matcher<std::string> m1 = HasSubstr("foo");
  1178. EXPECT_TRUE(m1.Matches(std::string("I love food.")));
  1179. EXPECT_FALSE(m1.Matches(std::string("tofo")));
  1180. const Matcher<const std::string&> m2 = HasSubstr("foo");
  1181. EXPECT_TRUE(m2.Matches(std::string("I love food.")));
  1182. EXPECT_FALSE(m2.Matches(std::string("tofo")));
  1183. const Matcher<std::string> m_empty = HasSubstr("");
  1184. EXPECT_TRUE(m_empty.Matches(std::string()));
  1185. EXPECT_TRUE(m_empty.Matches(std::string("not empty")));
  1186. }
  1187. // Tests that HasSubstr() works for matching C-string-typed values.
  1188. TEST(HasSubstrTest, WorksForCStrings) {
  1189. const Matcher<char*> m1 = HasSubstr("foo");
  1190. EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
  1191. EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
  1192. EXPECT_FALSE(m1.Matches(nullptr));
  1193. const Matcher<const char*> m2 = HasSubstr("foo");
  1194. EXPECT_TRUE(m2.Matches("I love food."));
  1195. EXPECT_FALSE(m2.Matches("tofo"));
  1196. EXPECT_FALSE(m2.Matches(nullptr));
  1197. const Matcher<const char*> m_empty = HasSubstr("");
  1198. EXPECT_TRUE(m_empty.Matches("not empty"));
  1199. EXPECT_TRUE(m_empty.Matches(""));
  1200. EXPECT_FALSE(m_empty.Matches(nullptr));
  1201. }
  1202. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1203. // Tests that HasSubstr() works for matching StringView-typed values.
  1204. TEST(HasSubstrTest, WorksForStringViewClasses) {
  1205. const Matcher<internal::StringView> m1 =
  1206. HasSubstr(internal::StringView("foo"));
  1207. EXPECT_TRUE(m1.Matches(internal::StringView("I love food.")));
  1208. EXPECT_FALSE(m1.Matches(internal::StringView("tofo")));
  1209. EXPECT_FALSE(m1.Matches(internal::StringView()));
  1210. const Matcher<const internal::StringView&> m2 = HasSubstr("foo");
  1211. EXPECT_TRUE(m2.Matches(internal::StringView("I love food.")));
  1212. EXPECT_FALSE(m2.Matches(internal::StringView("tofo")));
  1213. EXPECT_FALSE(m2.Matches(internal::StringView()));
  1214. const Matcher<const internal::StringView&> m3 = HasSubstr("");
  1215. EXPECT_TRUE(m3.Matches(internal::StringView("foo")));
  1216. EXPECT_TRUE(m3.Matches(internal::StringView("")));
  1217. EXPECT_TRUE(m3.Matches(internal::StringView()));
  1218. }
  1219. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1220. // Tests that HasSubstr(s) describes itself properly.
  1221. TEST(HasSubstrTest, CanDescribeSelf) {
  1222. Matcher<std::string> m = HasSubstr("foo\n\"");
  1223. EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
  1224. }
  1225. TEST(KeyTest, CanDescribeSelf) {
  1226. Matcher<const pair<std::string, int>&> m = Key("foo");
  1227. EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
  1228. EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
  1229. }
  1230. TEST(KeyTest, ExplainsResult) {
  1231. Matcher<pair<int, bool> > m = Key(GreaterThan(10));
  1232. EXPECT_EQ("whose first field is a value which is 5 less than 10",
  1233. Explain(m, make_pair(5, true)));
  1234. EXPECT_EQ("whose first field is a value which is 5 more than 10",
  1235. Explain(m, make_pair(15, true)));
  1236. }
  1237. TEST(KeyTest, MatchesCorrectly) {
  1238. pair<int, std::string> p(25, "foo");
  1239. EXPECT_THAT(p, Key(25));
  1240. EXPECT_THAT(p, Not(Key(42)));
  1241. EXPECT_THAT(p, Key(Ge(20)));
  1242. EXPECT_THAT(p, Not(Key(Lt(25))));
  1243. }
  1244. TEST(KeyTest, WorksWithMoveOnly) {
  1245. pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
  1246. EXPECT_THAT(p, Key(Eq(nullptr)));
  1247. }
  1248. template <size_t I>
  1249. struct Tag {};
  1250. struct PairWithGet {
  1251. int member_1;
  1252. std::string member_2;
  1253. using first_type = int;
  1254. using second_type = std::string;
  1255. const int& GetImpl(Tag<0>) const { return member_1; }
  1256. const std::string& GetImpl(Tag<1>) const { return member_2; }
  1257. };
  1258. template <size_t I>
  1259. auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
  1260. return value.GetImpl(Tag<I>());
  1261. }
  1262. TEST(PairTest, MatchesPairWithGetCorrectly) {
  1263. PairWithGet p{25, "foo"};
  1264. EXPECT_THAT(p, Key(25));
  1265. EXPECT_THAT(p, Not(Key(42)));
  1266. EXPECT_THAT(p, Key(Ge(20)));
  1267. EXPECT_THAT(p, Not(Key(Lt(25))));
  1268. std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
  1269. EXPECT_THAT(v, Contains(Key(29)));
  1270. }
  1271. TEST(KeyTest, SafelyCastsInnerMatcher) {
  1272. Matcher<int> is_positive = Gt(0);
  1273. Matcher<int> is_negative = Lt(0);
  1274. pair<char, bool> p('a', true);
  1275. EXPECT_THAT(p, Key(is_positive));
  1276. EXPECT_THAT(p, Not(Key(is_negative)));
  1277. }
  1278. TEST(KeyTest, InsideContainsUsingMap) {
  1279. map<int, char> container;
  1280. container.insert(make_pair(1, 'a'));
  1281. container.insert(make_pair(2, 'b'));
  1282. container.insert(make_pair(4, 'c'));
  1283. EXPECT_THAT(container, Contains(Key(1)));
  1284. EXPECT_THAT(container, Not(Contains(Key(3))));
  1285. }
  1286. TEST(KeyTest, InsideContainsUsingMultimap) {
  1287. multimap<int, char> container;
  1288. container.insert(make_pair(1, 'a'));
  1289. container.insert(make_pair(2, 'b'));
  1290. container.insert(make_pair(4, 'c'));
  1291. EXPECT_THAT(container, Not(Contains(Key(25))));
  1292. container.insert(make_pair(25, 'd'));
  1293. EXPECT_THAT(container, Contains(Key(25)));
  1294. container.insert(make_pair(25, 'e'));
  1295. EXPECT_THAT(container, Contains(Key(25)));
  1296. EXPECT_THAT(container, Contains(Key(1)));
  1297. EXPECT_THAT(container, Not(Contains(Key(3))));
  1298. }
  1299. TEST(PairTest, Typing) {
  1300. // Test verifies the following type conversions can be compiled.
  1301. Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
  1302. Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
  1303. Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
  1304. Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
  1305. Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
  1306. }
  1307. TEST(PairTest, CanDescribeSelf) {
  1308. Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
  1309. EXPECT_EQ("has a first field that is equal to \"foo\""
  1310. ", and has a second field that is equal to 42",
  1311. Describe(m1));
  1312. EXPECT_EQ("has a first field that isn't equal to \"foo\""
  1313. ", or has a second field that isn't equal to 42",
  1314. DescribeNegation(m1));
  1315. // Double and triple negation (1 or 2 times not and description of negation).
  1316. Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
  1317. EXPECT_EQ("has a first field that isn't equal to 13"
  1318. ", and has a second field that is equal to 42",
  1319. DescribeNegation(m2));
  1320. }
  1321. TEST(PairTest, CanExplainMatchResultTo) {
  1322. // If neither field matches, Pair() should explain about the first
  1323. // field.
  1324. const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
  1325. EXPECT_EQ("whose first field does not match, which is 1 less than 0",
  1326. Explain(m, make_pair(-1, -2)));
  1327. // If the first field matches but the second doesn't, Pair() should
  1328. // explain about the second field.
  1329. EXPECT_EQ("whose second field does not match, which is 2 less than 0",
  1330. Explain(m, make_pair(1, -2)));
  1331. // If the first field doesn't match but the second does, Pair()
  1332. // should explain about the first field.
  1333. EXPECT_EQ("whose first field does not match, which is 1 less than 0",
  1334. Explain(m, make_pair(-1, 2)));
  1335. // If both fields match, Pair() should explain about them both.
  1336. EXPECT_EQ("whose both fields match, where the first field is a value "
  1337. "which is 1 more than 0, and the second field is a value "
  1338. "which is 2 more than 0",
  1339. Explain(m, make_pair(1, 2)));
  1340. // If only the first match has an explanation, only this explanation should
  1341. // be printed.
  1342. const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
  1343. EXPECT_EQ("whose both fields match, where the first field is a value "
  1344. "which is 1 more than 0",
  1345. Explain(explain_first, make_pair(1, 0)));
  1346. // If only the second match has an explanation, only this explanation should
  1347. // be printed.
  1348. const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
  1349. EXPECT_EQ("whose both fields match, where the second field is a value "
  1350. "which is 1 more than 0",
  1351. Explain(explain_second, make_pair(0, 1)));
  1352. }
  1353. TEST(PairTest, MatchesCorrectly) {
  1354. pair<int, std::string> p(25, "foo");
  1355. // Both fields match.
  1356. EXPECT_THAT(p, Pair(25, "foo"));
  1357. EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
  1358. // 'first' doesnt' match, but 'second' matches.
  1359. EXPECT_THAT(p, Not(Pair(42, "foo")));
  1360. EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
  1361. // 'first' matches, but 'second' doesn't match.
  1362. EXPECT_THAT(p, Not(Pair(25, "bar")));
  1363. EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
  1364. // Neither field matches.
  1365. EXPECT_THAT(p, Not(Pair(13, "bar")));
  1366. EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
  1367. }
  1368. TEST(PairTest, WorksWithMoveOnly) {
  1369. pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
  1370. p.second.reset(new int(7));
  1371. EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
  1372. }
  1373. TEST(PairTest, SafelyCastsInnerMatchers) {
  1374. Matcher<int> is_positive = Gt(0);
  1375. Matcher<int> is_negative = Lt(0);
  1376. pair<char, bool> p('a', true);
  1377. EXPECT_THAT(p, Pair(is_positive, _));
  1378. EXPECT_THAT(p, Not(Pair(is_negative, _)));
  1379. EXPECT_THAT(p, Pair(_, is_positive));
  1380. EXPECT_THAT(p, Not(Pair(_, is_negative)));
  1381. }
  1382. TEST(PairTest, InsideContainsUsingMap) {
  1383. map<int, char> container;
  1384. container.insert(make_pair(1, 'a'));
  1385. container.insert(make_pair(2, 'b'));
  1386. container.insert(make_pair(4, 'c'));
  1387. EXPECT_THAT(container, Contains(Pair(1, 'a')));
  1388. EXPECT_THAT(container, Contains(Pair(1, _)));
  1389. EXPECT_THAT(container, Contains(Pair(_, 'a')));
  1390. EXPECT_THAT(container, Not(Contains(Pair(3, _))));
  1391. }
  1392. TEST(FieldsAreTest, MatchesCorrectly) {
  1393. std::tuple<int, std::string, double> p(25, "foo", .5);
  1394. // All fields match.
  1395. EXPECT_THAT(p, FieldsAre(25, "foo", .5));
  1396. EXPECT_THAT(p, FieldsAre(Ge(20), HasSubstr("o"), DoubleEq(.5)));
  1397. // Some don't match.
  1398. EXPECT_THAT(p, Not(FieldsAre(26, "foo", .5)));
  1399. EXPECT_THAT(p, Not(FieldsAre(25, "fo", .5)));
  1400. EXPECT_THAT(p, Not(FieldsAre(25, "foo", .6)));
  1401. }
  1402. TEST(FieldsAreTest, CanDescribeSelf) {
  1403. Matcher<const pair<std::string, int>&> m1 = FieldsAre("foo", 42);
  1404. EXPECT_EQ(
  1405. "has field #0 that is equal to \"foo\""
  1406. ", and has field #1 that is equal to 42",
  1407. Describe(m1));
  1408. EXPECT_EQ(
  1409. "has field #0 that isn't equal to \"foo\""
  1410. ", or has field #1 that isn't equal to 42",
  1411. DescribeNegation(m1));
  1412. }
  1413. TEST(FieldsAreTest, CanExplainMatchResultTo) {
  1414. // The first one that fails is the one that gives the error.
  1415. Matcher<std::tuple<int, int, int>> m =
  1416. FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0));
  1417. EXPECT_EQ("whose field #0 does not match, which is 1 less than 0",
  1418. Explain(m, std::make_tuple(-1, -2, -3)));
  1419. EXPECT_EQ("whose field #1 does not match, which is 2 less than 0",
  1420. Explain(m, std::make_tuple(1, -2, -3)));
  1421. EXPECT_EQ("whose field #2 does not match, which is 3 less than 0",
  1422. Explain(m, std::make_tuple(1, 2, -3)));
  1423. // If they all match, we get a long explanation of success.
  1424. EXPECT_EQ(
  1425. "whose all elements match, "
  1426. "where field #0 is a value which is 1 more than 0"
  1427. ", and field #1 is a value which is 2 more than 0"
  1428. ", and field #2 is a value which is 3 more than 0",
  1429. Explain(m, std::make_tuple(1, 2, 3)));
  1430. // Only print those that have an explanation.
  1431. m = FieldsAre(GreaterThan(0), 0, GreaterThan(0));
  1432. EXPECT_EQ(
  1433. "whose all elements match, "
  1434. "where field #0 is a value which is 1 more than 0"
  1435. ", and field #2 is a value which is 3 more than 0",
  1436. Explain(m, std::make_tuple(1, 0, 3)));
  1437. // If only one has an explanation, then print that one.
  1438. m = FieldsAre(0, GreaterThan(0), 0);
  1439. EXPECT_EQ(
  1440. "whose all elements match, "
  1441. "where field #1 is a value which is 1 more than 0",
  1442. Explain(m, std::make_tuple(0, 1, 0)));
  1443. }
  1444. #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
  1445. TEST(FieldsAreTest, StructuredBindings) {
  1446. // testing::FieldsAre can also match aggregates and such with C++17 and up.
  1447. struct MyType {
  1448. int i;
  1449. std::string str;
  1450. };
  1451. EXPECT_THAT((MyType{17, "foo"}), FieldsAre(Eq(17), HasSubstr("oo")));
  1452. // Test all the supported arities.
  1453. struct MyVarType1 {
  1454. int a;
  1455. };
  1456. EXPECT_THAT(MyVarType1{}, FieldsAre(0));
  1457. struct MyVarType2 {
  1458. int a, b;
  1459. };
  1460. EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0));
  1461. struct MyVarType3 {
  1462. int a, b, c;
  1463. };
  1464. EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0));
  1465. struct MyVarType4 {
  1466. int a, b, c, d;
  1467. };
  1468. EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0));
  1469. struct MyVarType5 {
  1470. int a, b, c, d, e;
  1471. };
  1472. EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0));
  1473. struct MyVarType6 {
  1474. int a, b, c, d, e, f;
  1475. };
  1476. EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0));
  1477. struct MyVarType7 {
  1478. int a, b, c, d, e, f, g;
  1479. };
  1480. EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0));
  1481. struct MyVarType8 {
  1482. int a, b, c, d, e, f, g, h;
  1483. };
  1484. EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0));
  1485. struct MyVarType9 {
  1486. int a, b, c, d, e, f, g, h, i;
  1487. };
  1488. EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0));
  1489. struct MyVarType10 {
  1490. int a, b, c, d, e, f, g, h, i, j;
  1491. };
  1492. EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1493. struct MyVarType11 {
  1494. int a, b, c, d, e, f, g, h, i, j, k;
  1495. };
  1496. EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1497. struct MyVarType12 {
  1498. int a, b, c, d, e, f, g, h, i, j, k, l;
  1499. };
  1500. EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1501. struct MyVarType13 {
  1502. int a, b, c, d, e, f, g, h, i, j, k, l, m;
  1503. };
  1504. EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1505. struct MyVarType14 {
  1506. int a, b, c, d, e, f, g, h, i, j, k, l, m, n;
  1507. };
  1508. EXPECT_THAT(MyVarType14{},
  1509. FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1510. struct MyVarType15 {
  1511. int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
  1512. };
  1513. EXPECT_THAT(MyVarType15{},
  1514. FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1515. struct MyVarType16 {
  1516. int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p;
  1517. };
  1518. EXPECT_THAT(MyVarType16{},
  1519. FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  1520. }
  1521. #endif
  1522. TEST(ContainsTest, WorksWithMoveOnly) {
  1523. ContainerHelper helper;
  1524. EXPECT_CALL(helper, Call(Contains(Pointee(2))));
  1525. helper.Call(MakeUniquePtrs({1, 2}));
  1526. }
  1527. TEST(PairTest, UseGetInsteadOfMembers) {
  1528. PairWithGet pair{7, "ABC"};
  1529. EXPECT_THAT(pair, Pair(7, "ABC"));
  1530. EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
  1531. EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
  1532. std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
  1533. EXPECT_THAT(v,
  1534. ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not(""))));
  1535. }
  1536. // Tests StartsWith(s).
  1537. TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
  1538. const Matcher<const char*> m1 = StartsWith(std::string(""));
  1539. EXPECT_TRUE(m1.Matches("Hi"));
  1540. EXPECT_TRUE(m1.Matches(""));
  1541. EXPECT_FALSE(m1.Matches(nullptr));
  1542. const Matcher<const std::string&> m2 = StartsWith("Hi");
  1543. EXPECT_TRUE(m2.Matches("Hi"));
  1544. EXPECT_TRUE(m2.Matches("Hi Hi!"));
  1545. EXPECT_TRUE(m2.Matches("High"));
  1546. EXPECT_FALSE(m2.Matches("H"));
  1547. EXPECT_FALSE(m2.Matches(" Hi"));
  1548. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1549. const Matcher<internal::StringView> m_empty =
  1550. StartsWith(internal::StringView(""));
  1551. EXPECT_TRUE(m_empty.Matches(internal::StringView()));
  1552. EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
  1553. EXPECT_TRUE(m_empty.Matches(internal::StringView("not empty")));
  1554. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1555. }
  1556. TEST(StartsWithTest, CanDescribeSelf) {
  1557. Matcher<const std::string> m = StartsWith("Hi");
  1558. EXPECT_EQ("starts with \"Hi\"", Describe(m));
  1559. }
  1560. // Tests EndsWith(s).
  1561. TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
  1562. const Matcher<const char*> m1 = EndsWith("");
  1563. EXPECT_TRUE(m1.Matches("Hi"));
  1564. EXPECT_TRUE(m1.Matches(""));
  1565. EXPECT_FALSE(m1.Matches(nullptr));
  1566. const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
  1567. EXPECT_TRUE(m2.Matches("Hi"));
  1568. EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
  1569. EXPECT_TRUE(m2.Matches("Super Hi"));
  1570. EXPECT_FALSE(m2.Matches("i"));
  1571. EXPECT_FALSE(m2.Matches("Hi "));
  1572. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1573. const Matcher<const internal::StringView&> m4 =
  1574. EndsWith(internal::StringView(""));
  1575. EXPECT_TRUE(m4.Matches("Hi"));
  1576. EXPECT_TRUE(m4.Matches(""));
  1577. EXPECT_TRUE(m4.Matches(internal::StringView()));
  1578. EXPECT_TRUE(m4.Matches(internal::StringView("")));
  1579. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1580. }
  1581. TEST(EndsWithTest, CanDescribeSelf) {
  1582. Matcher<const std::string> m = EndsWith("Hi");
  1583. EXPECT_EQ("ends with \"Hi\"", Describe(m));
  1584. }
  1585. // Tests MatchesRegex().
  1586. TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
  1587. const Matcher<const char*> m1 = MatchesRegex("a.*z");
  1588. EXPECT_TRUE(m1.Matches("az"));
  1589. EXPECT_TRUE(m1.Matches("abcz"));
  1590. EXPECT_FALSE(m1.Matches(nullptr));
  1591. const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
  1592. EXPECT_TRUE(m2.Matches("azbz"));
  1593. EXPECT_FALSE(m2.Matches("az1"));
  1594. EXPECT_FALSE(m2.Matches("1az"));
  1595. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1596. const Matcher<const internal::StringView&> m3 = MatchesRegex("a.*z");
  1597. EXPECT_TRUE(m3.Matches(internal::StringView("az")));
  1598. EXPECT_TRUE(m3.Matches(internal::StringView("abcz")));
  1599. EXPECT_FALSE(m3.Matches(internal::StringView("1az")));
  1600. EXPECT_FALSE(m3.Matches(internal::StringView()));
  1601. const Matcher<const internal::StringView&> m4 =
  1602. MatchesRegex(internal::StringView(""));
  1603. EXPECT_TRUE(m4.Matches(internal::StringView("")));
  1604. EXPECT_TRUE(m4.Matches(internal::StringView()));
  1605. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1606. }
  1607. TEST(MatchesRegexTest, CanDescribeSelf) {
  1608. Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
  1609. EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
  1610. Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
  1611. EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
  1612. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1613. Matcher<const internal::StringView> m3 = MatchesRegex(new RE("0.*"));
  1614. EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
  1615. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1616. }
  1617. // Tests ContainsRegex().
  1618. TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
  1619. const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
  1620. EXPECT_TRUE(m1.Matches("az"));
  1621. EXPECT_TRUE(m1.Matches("0abcz1"));
  1622. EXPECT_FALSE(m1.Matches(nullptr));
  1623. const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
  1624. EXPECT_TRUE(m2.Matches("azbz"));
  1625. EXPECT_TRUE(m2.Matches("az1"));
  1626. EXPECT_FALSE(m2.Matches("1a"));
  1627. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1628. const Matcher<const internal::StringView&> m3 =
  1629. ContainsRegex(new RE("a.*z"));
  1630. EXPECT_TRUE(m3.Matches(internal::StringView("azbz")));
  1631. EXPECT_TRUE(m3.Matches(internal::StringView("az1")));
  1632. EXPECT_FALSE(m3.Matches(internal::StringView("1a")));
  1633. EXPECT_FALSE(m3.Matches(internal::StringView()));
  1634. const Matcher<const internal::StringView&> m4 =
  1635. ContainsRegex(internal::StringView(""));
  1636. EXPECT_TRUE(m4.Matches(internal::StringView("")));
  1637. EXPECT_TRUE(m4.Matches(internal::StringView()));
  1638. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1639. }
  1640. TEST(ContainsRegexTest, CanDescribeSelf) {
  1641. Matcher<const std::string> m1 = ContainsRegex("Hi.*");
  1642. EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
  1643. Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
  1644. EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
  1645. #if GTEST_INTERNAL_HAS_STRING_VIEW
  1646. Matcher<const internal::StringView> m3 = ContainsRegex(new RE("0.*"));
  1647. EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
  1648. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  1649. }
  1650. // Tests for wide strings.
  1651. #if GTEST_HAS_STD_WSTRING
  1652. TEST(StdWideStrEqTest, MatchesEqual) {
  1653. Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
  1654. EXPECT_TRUE(m.Matches(L"Hello"));
  1655. EXPECT_FALSE(m.Matches(L"hello"));
  1656. EXPECT_FALSE(m.Matches(nullptr));
  1657. Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
  1658. EXPECT_TRUE(m2.Matches(L"Hello"));
  1659. EXPECT_FALSE(m2.Matches(L"Hi"));
  1660. Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1661. EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
  1662. EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
  1663. ::std::wstring str(L"01204500800");
  1664. str[3] = L'\0';
  1665. Matcher<const ::std::wstring&> m4 = StrEq(str);
  1666. EXPECT_TRUE(m4.Matches(str));
  1667. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1668. Matcher<const ::std::wstring&> m5 = StrEq(str);
  1669. EXPECT_TRUE(m5.Matches(str));
  1670. }
  1671. TEST(StdWideStrEqTest, CanDescribeSelf) {
  1672. Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
  1673. EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
  1674. Describe(m));
  1675. Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1676. EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
  1677. Describe(m2));
  1678. ::std::wstring str(L"01204500800");
  1679. str[3] = L'\0';
  1680. Matcher<const ::std::wstring&> m4 = StrEq(str);
  1681. EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
  1682. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1683. Matcher<const ::std::wstring&> m5 = StrEq(str);
  1684. EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
  1685. }
  1686. TEST(StdWideStrNeTest, MatchesUnequalString) {
  1687. Matcher<const wchar_t*> m = StrNe(L"Hello");
  1688. EXPECT_TRUE(m.Matches(L""));
  1689. EXPECT_TRUE(m.Matches(nullptr));
  1690. EXPECT_FALSE(m.Matches(L"Hello"));
  1691. Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
  1692. EXPECT_TRUE(m2.Matches(L"hello"));
  1693. EXPECT_FALSE(m2.Matches(L"Hello"));
  1694. }
  1695. TEST(StdWideStrNeTest, CanDescribeSelf) {
  1696. Matcher<const wchar_t*> m = StrNe(L"Hi");
  1697. EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
  1698. }
  1699. TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
  1700. Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
  1701. EXPECT_TRUE(m.Matches(L"Hello"));
  1702. EXPECT_TRUE(m.Matches(L"hello"));
  1703. EXPECT_FALSE(m.Matches(L"Hi"));
  1704. EXPECT_FALSE(m.Matches(nullptr));
  1705. Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
  1706. EXPECT_TRUE(m2.Matches(L"hello"));
  1707. EXPECT_FALSE(m2.Matches(L"Hi"));
  1708. }
  1709. TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
  1710. ::std::wstring str1(L"oabocdooeoo");
  1711. ::std::wstring str2(L"OABOCDOOEOO");
  1712. Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
  1713. EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
  1714. str1[3] = str2[3] = L'\0';
  1715. Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
  1716. EXPECT_TRUE(m1.Matches(str2));
  1717. str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
  1718. str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
  1719. Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
  1720. str1[9] = str2[9] = L'\0';
  1721. EXPECT_FALSE(m2.Matches(str2));
  1722. Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
  1723. EXPECT_TRUE(m3.Matches(str2));
  1724. EXPECT_FALSE(m3.Matches(str2 + L"x"));
  1725. str2.append(1, L'\0');
  1726. EXPECT_FALSE(m3.Matches(str2));
  1727. EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
  1728. }
  1729. TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
  1730. Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
  1731. EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
  1732. }
  1733. TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
  1734. Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
  1735. EXPECT_TRUE(m.Matches(L"Hi"));
  1736. EXPECT_TRUE(m.Matches(nullptr));
  1737. EXPECT_FALSE(m.Matches(L"Hello"));
  1738. EXPECT_FALSE(m.Matches(L"hello"));
  1739. Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
  1740. EXPECT_TRUE(m2.Matches(L""));
  1741. EXPECT_FALSE(m2.Matches(L"Hello"));
  1742. }
  1743. TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
  1744. Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
  1745. EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
  1746. }
  1747. // Tests that HasSubstr() works for matching wstring-typed values.
  1748. TEST(StdWideHasSubstrTest, WorksForStringClasses) {
  1749. const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
  1750. EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
  1751. EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
  1752. const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
  1753. EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
  1754. EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
  1755. }
  1756. // Tests that HasSubstr() works for matching C-wide-string-typed values.
  1757. TEST(StdWideHasSubstrTest, WorksForCStrings) {
  1758. const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
  1759. EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
  1760. EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
  1761. EXPECT_FALSE(m1.Matches(nullptr));
  1762. const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
  1763. EXPECT_TRUE(m2.Matches(L"I love food."));
  1764. EXPECT_FALSE(m2.Matches(L"tofo"));
  1765. EXPECT_FALSE(m2.Matches(nullptr));
  1766. }
  1767. // Tests that HasSubstr(s) describes itself properly.
  1768. TEST(StdWideHasSubstrTest, CanDescribeSelf) {
  1769. Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
  1770. EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
  1771. }
  1772. // Tests StartsWith(s).
  1773. TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
  1774. const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
  1775. EXPECT_TRUE(m1.Matches(L"Hi"));
  1776. EXPECT_TRUE(m1.Matches(L""));
  1777. EXPECT_FALSE(m1.Matches(nullptr));
  1778. const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
  1779. EXPECT_TRUE(m2.Matches(L"Hi"));
  1780. EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
  1781. EXPECT_TRUE(m2.Matches(L"High"));
  1782. EXPECT_FALSE(m2.Matches(L"H"));
  1783. EXPECT_FALSE(m2.Matches(L" Hi"));
  1784. }
  1785. TEST(StdWideStartsWithTest, CanDescribeSelf) {
  1786. Matcher<const ::std::wstring> m = StartsWith(L"Hi");
  1787. EXPECT_EQ("starts with L\"Hi\"", Describe(m));
  1788. }
  1789. // Tests EndsWith(s).
  1790. TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
  1791. const Matcher<const wchar_t*> m1 = EndsWith(L"");
  1792. EXPECT_TRUE(m1.Matches(L"Hi"));
  1793. EXPECT_TRUE(m1.Matches(L""));
  1794. EXPECT_FALSE(m1.Matches(nullptr));
  1795. const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
  1796. EXPECT_TRUE(m2.Matches(L"Hi"));
  1797. EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
  1798. EXPECT_TRUE(m2.Matches(L"Super Hi"));
  1799. EXPECT_FALSE(m2.Matches(L"i"));
  1800. EXPECT_FALSE(m2.Matches(L"Hi "));
  1801. }
  1802. TEST(StdWideEndsWithTest, CanDescribeSelf) {
  1803. Matcher<const ::std::wstring> m = EndsWith(L"Hi");
  1804. EXPECT_EQ("ends with L\"Hi\"", Describe(m));
  1805. }
  1806. #endif // GTEST_HAS_STD_WSTRING
  1807. typedef ::std::tuple<long, int> Tuple2; // NOLINT
  1808. // Tests that Eq() matches a 2-tuple where the first field == the
  1809. // second field.
  1810. TEST(Eq2Test, MatchesEqualArguments) {
  1811. Matcher<const Tuple2&> m = Eq();
  1812. EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
  1813. EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
  1814. }
  1815. // Tests that Eq() describes itself properly.
  1816. TEST(Eq2Test, CanDescribeSelf) {
  1817. Matcher<const Tuple2&> m = Eq();
  1818. EXPECT_EQ("are an equal pair", Describe(m));
  1819. }
  1820. // Tests that Ge() matches a 2-tuple where the first field >= the
  1821. // second field.
  1822. TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
  1823. Matcher<const Tuple2&> m = Ge();
  1824. EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
  1825. EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
  1826. EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
  1827. }
  1828. // Tests that Ge() describes itself properly.
  1829. TEST(Ge2Test, CanDescribeSelf) {
  1830. Matcher<const Tuple2&> m = Ge();
  1831. EXPECT_EQ("are a pair where the first >= the second", Describe(m));
  1832. }
  1833. // Tests that Gt() matches a 2-tuple where the first field > the
  1834. // second field.
  1835. TEST(Gt2Test, MatchesGreaterThanArguments) {
  1836. Matcher<const Tuple2&> m = Gt();
  1837. EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
  1838. EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
  1839. EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
  1840. }
  1841. // Tests that Gt() describes itself properly.
  1842. TEST(Gt2Test, CanDescribeSelf) {
  1843. Matcher<const Tuple2&> m = Gt();
  1844. EXPECT_EQ("are a pair where the first > the second", Describe(m));
  1845. }
  1846. // Tests that Le() matches a 2-tuple where the first field <= the
  1847. // second field.
  1848. TEST(Le2Test, MatchesLessThanOrEqualArguments) {
  1849. Matcher<const Tuple2&> m = Le();
  1850. EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
  1851. EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
  1852. EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
  1853. }
  1854. // Tests that Le() describes itself properly.
  1855. TEST(Le2Test, CanDescribeSelf) {
  1856. Matcher<const Tuple2&> m = Le();
  1857. EXPECT_EQ("are a pair where the first <= the second", Describe(m));
  1858. }
  1859. // Tests that Lt() matches a 2-tuple where the first field < the
  1860. // second field.
  1861. TEST(Lt2Test, MatchesLessThanArguments) {
  1862. Matcher<const Tuple2&> m = Lt();
  1863. EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
  1864. EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
  1865. EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
  1866. }
  1867. // Tests that Lt() describes itself properly.
  1868. TEST(Lt2Test, CanDescribeSelf) {
  1869. Matcher<const Tuple2&> m = Lt();
  1870. EXPECT_EQ("are a pair where the first < the second", Describe(m));
  1871. }
  1872. // Tests that Ne() matches a 2-tuple where the first field != the
  1873. // second field.
  1874. TEST(Ne2Test, MatchesUnequalArguments) {
  1875. Matcher<const Tuple2&> m = Ne();
  1876. EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
  1877. EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
  1878. EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
  1879. }
  1880. // Tests that Ne() describes itself properly.
  1881. TEST(Ne2Test, CanDescribeSelf) {
  1882. Matcher<const Tuple2&> m = Ne();
  1883. EXPECT_EQ("are an unequal pair", Describe(m));
  1884. }
  1885. TEST(PairMatchBaseTest, WorksWithMoveOnly) {
  1886. using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>;
  1887. Matcher<Pointers> matcher = Eq();
  1888. Pointers pointers;
  1889. // Tested values don't matter; the point is that matcher does not copy the
  1890. // matched values.
  1891. EXPECT_TRUE(matcher.Matches(pointers));
  1892. }
  1893. // Tests that IsNan() matches a NaN, with float.
  1894. TEST(IsNan, FloatMatchesNan) {
  1895. float quiet_nan = std::numeric_limits<float>::quiet_NaN();
  1896. float other_nan = std::nanf("1");
  1897. float real_value = 1.0f;
  1898. Matcher<float> m = IsNan();
  1899. EXPECT_TRUE(m.Matches(quiet_nan));
  1900. EXPECT_TRUE(m.Matches(other_nan));
  1901. EXPECT_FALSE(m.Matches(real_value));
  1902. Matcher<float&> m_ref = IsNan();
  1903. EXPECT_TRUE(m_ref.Matches(quiet_nan));
  1904. EXPECT_TRUE(m_ref.Matches(other_nan));
  1905. EXPECT_FALSE(m_ref.Matches(real_value));
  1906. Matcher<const float&> m_cref = IsNan();
  1907. EXPECT_TRUE(m_cref.Matches(quiet_nan));
  1908. EXPECT_TRUE(m_cref.Matches(other_nan));
  1909. EXPECT_FALSE(m_cref.Matches(real_value));
  1910. }
  1911. // Tests that IsNan() matches a NaN, with double.
  1912. TEST(IsNan, DoubleMatchesNan) {
  1913. double quiet_nan = std::numeric_limits<double>::quiet_NaN();
  1914. double other_nan = std::nan("1");
  1915. double real_value = 1.0;
  1916. Matcher<double> m = IsNan();
  1917. EXPECT_TRUE(m.Matches(quiet_nan));
  1918. EXPECT_TRUE(m.Matches(other_nan));
  1919. EXPECT_FALSE(m.Matches(real_value));
  1920. Matcher<double&> m_ref = IsNan();
  1921. EXPECT_TRUE(m_ref.Matches(quiet_nan));
  1922. EXPECT_TRUE(m_ref.Matches(other_nan));
  1923. EXPECT_FALSE(m_ref.Matches(real_value));
  1924. Matcher<const double&> m_cref = IsNan();
  1925. EXPECT_TRUE(m_cref.Matches(quiet_nan));
  1926. EXPECT_TRUE(m_cref.Matches(other_nan));
  1927. EXPECT_FALSE(m_cref.Matches(real_value));
  1928. }
  1929. // Tests that IsNan() matches a NaN, with long double.
  1930. TEST(IsNan, LongDoubleMatchesNan) {
  1931. long double quiet_nan = std::numeric_limits<long double>::quiet_NaN();
  1932. long double other_nan = std::nan("1");
  1933. long double real_value = 1.0;
  1934. Matcher<long double> m = IsNan();
  1935. EXPECT_TRUE(m.Matches(quiet_nan));
  1936. EXPECT_TRUE(m.Matches(other_nan));
  1937. EXPECT_FALSE(m.Matches(real_value));
  1938. Matcher<long double&> m_ref = IsNan();
  1939. EXPECT_TRUE(m_ref.Matches(quiet_nan));
  1940. EXPECT_TRUE(m_ref.Matches(other_nan));
  1941. EXPECT_FALSE(m_ref.Matches(real_value));
  1942. Matcher<const long double&> m_cref = IsNan();
  1943. EXPECT_TRUE(m_cref.Matches(quiet_nan));
  1944. EXPECT_TRUE(m_cref.Matches(other_nan));
  1945. EXPECT_FALSE(m_cref.Matches(real_value));
  1946. }
  1947. // Tests that IsNan() works with Not.
  1948. TEST(IsNan, NotMatchesNan) {
  1949. Matcher<float> mf = Not(IsNan());
  1950. EXPECT_FALSE(mf.Matches(std::numeric_limits<float>::quiet_NaN()));
  1951. EXPECT_FALSE(mf.Matches(std::nanf("1")));
  1952. EXPECT_TRUE(mf.Matches(1.0));
  1953. Matcher<double> md = Not(IsNan());
  1954. EXPECT_FALSE(md.Matches(std::numeric_limits<double>::quiet_NaN()));
  1955. EXPECT_FALSE(md.Matches(std::nan("1")));
  1956. EXPECT_TRUE(md.Matches(1.0));
  1957. Matcher<long double> mld = Not(IsNan());
  1958. EXPECT_FALSE(mld.Matches(std::numeric_limits<long double>::quiet_NaN()));
  1959. EXPECT_FALSE(mld.Matches(std::nanl("1")));
  1960. EXPECT_TRUE(mld.Matches(1.0));
  1961. }
  1962. // Tests that IsNan() can describe itself.
  1963. TEST(IsNan, CanDescribeSelf) {
  1964. Matcher<float> mf = IsNan();
  1965. EXPECT_EQ("is NaN", Describe(mf));
  1966. Matcher<double> md = IsNan();
  1967. EXPECT_EQ("is NaN", Describe(md));
  1968. Matcher<long double> mld = IsNan();
  1969. EXPECT_EQ("is NaN", Describe(mld));
  1970. }
  1971. // Tests that IsNan() can describe itself with Not.
  1972. TEST(IsNan, CanDescribeSelfWithNot) {
  1973. Matcher<float> mf = Not(IsNan());
  1974. EXPECT_EQ("isn't NaN", Describe(mf));
  1975. Matcher<double> md = Not(IsNan());
  1976. EXPECT_EQ("isn't NaN", Describe(md));
  1977. Matcher<long double> mld = Not(IsNan());
  1978. EXPECT_EQ("isn't NaN", Describe(mld));
  1979. }
  1980. // Tests that FloatEq() matches a 2-tuple where
  1981. // FloatEq(first field) matches the second field.
  1982. TEST(FloatEq2Test, MatchesEqualArguments) {
  1983. typedef ::std::tuple<float, float> Tpl;
  1984. Matcher<const Tpl&> m = FloatEq();
  1985. EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
  1986. EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));
  1987. EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
  1988. }
  1989. // Tests that FloatEq() describes itself properly.
  1990. TEST(FloatEq2Test, CanDescribeSelf) {
  1991. Matcher<const ::std::tuple<float, float>&> m = FloatEq();
  1992. EXPECT_EQ("are an almost-equal pair", Describe(m));
  1993. }
  1994. // Tests that NanSensitiveFloatEq() matches a 2-tuple where
  1995. // NanSensitiveFloatEq(first field) matches the second field.
  1996. TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
  1997. typedef ::std::tuple<float, float> Tpl;
  1998. Matcher<const Tpl&> m = NanSensitiveFloatEq();
  1999. EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
  2000. EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
  2001. std::numeric_limits<float>::quiet_NaN())));
  2002. EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
  2003. EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
  2004. EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
  2005. }
  2006. // Tests that NanSensitiveFloatEq() describes itself properly.
  2007. TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
  2008. Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq();
  2009. EXPECT_EQ("are an almost-equal pair", Describe(m));
  2010. }
  2011. // Tests that DoubleEq() matches a 2-tuple where
  2012. // DoubleEq(first field) matches the second field.
  2013. TEST(DoubleEq2Test, MatchesEqualArguments) {
  2014. typedef ::std::tuple<double, double> Tpl;
  2015. Matcher<const Tpl&> m = DoubleEq();
  2016. EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
  2017. EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
  2018. EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0)));
  2019. }
  2020. // Tests that DoubleEq() describes itself properly.
  2021. TEST(DoubleEq2Test, CanDescribeSelf) {
  2022. Matcher<const ::std::tuple<double, double>&> m = DoubleEq();
  2023. EXPECT_EQ("are an almost-equal pair", Describe(m));
  2024. }
  2025. // Tests that NanSensitiveDoubleEq() matches a 2-tuple where
  2026. // NanSensitiveDoubleEq(first field) matches the second field.
  2027. TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
  2028. typedef ::std::tuple<double, double> Tpl;
  2029. Matcher<const Tpl&> m = NanSensitiveDoubleEq();
  2030. EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
  2031. EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
  2032. std::numeric_limits<double>::quiet_NaN())));
  2033. EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
  2034. EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
  2035. EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
  2036. }
  2037. // Tests that DoubleEq() describes itself properly.
  2038. TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
  2039. Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq();
  2040. EXPECT_EQ("are an almost-equal pair", Describe(m));
  2041. }
  2042. // Tests that FloatEq() matches a 2-tuple where
  2043. // FloatNear(first field, max_abs_error) matches the second field.
  2044. TEST(FloatNear2Test, MatchesEqualArguments) {
  2045. typedef ::std::tuple<float, float> Tpl;
  2046. Matcher<const Tpl&> m = FloatNear(0.5f);
  2047. EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
  2048. EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f)));
  2049. EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f)));
  2050. }
  2051. // Tests that FloatNear() describes itself properly.
  2052. TEST(FloatNear2Test, CanDescribeSelf) {
  2053. Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f);
  2054. EXPECT_EQ("are an almost-equal pair", Describe(m));
  2055. }
  2056. // Tests that NanSensitiveFloatNear() matches a 2-tuple where
  2057. // NanSensitiveFloatNear(first field) matches the second field.
  2058. TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
  2059. typedef ::std::tuple<float, float> Tpl;
  2060. Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);
  2061. EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
  2062. EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
  2063. EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
  2064. std::numeric_limits<float>::quiet_NaN())));
  2065. EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
  2066. EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
  2067. EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
  2068. }
  2069. // Tests that NanSensitiveFloatNear() describes itself properly.
  2070. TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
  2071. Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f);
  2072. EXPECT_EQ("are an almost-equal pair", Describe(m));
  2073. }
  2074. // Tests that FloatEq() matches a 2-tuple where
  2075. // DoubleNear(first field, max_abs_error) matches the second field.
  2076. TEST(DoubleNear2Test, MatchesEqualArguments) {
  2077. typedef ::std::tuple<double, double> Tpl;
  2078. Matcher<const Tpl&> m = DoubleNear(0.5);
  2079. EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
  2080. EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0)));
  2081. EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0)));
  2082. }
  2083. // Tests that DoubleNear() describes itself properly.
  2084. TEST(DoubleNear2Test, CanDescribeSelf) {
  2085. Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5);
  2086. EXPECT_EQ("are an almost-equal pair", Describe(m));
  2087. }
  2088. // Tests that NanSensitiveDoubleNear() matches a 2-tuple where
  2089. // NanSensitiveDoubleNear(first field) matches the second field.
  2090. TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
  2091. typedef ::std::tuple<double, double> Tpl;
  2092. Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);
  2093. EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
  2094. EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
  2095. EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
  2096. std::numeric_limits<double>::quiet_NaN())));
  2097. EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
  2098. EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
  2099. EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
  2100. }
  2101. // Tests that NanSensitiveDoubleNear() describes itself properly.
  2102. TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
  2103. Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f);
  2104. EXPECT_EQ("are an almost-equal pair", Describe(m));
  2105. }
  2106. // Tests that Not(m) matches any value that doesn't match m.
  2107. TEST(NotTest, NegatesMatcher) {
  2108. Matcher<int> m;
  2109. m = Not(Eq(2));
  2110. EXPECT_TRUE(m.Matches(3));
  2111. EXPECT_FALSE(m.Matches(2));
  2112. }
  2113. // Tests that Not(m) describes itself properly.
  2114. TEST(NotTest, CanDescribeSelf) {
  2115. Matcher<int> m = Not(Eq(5));
  2116. EXPECT_EQ("isn't equal to 5", Describe(m));
  2117. }
  2118. // Tests that monomorphic matchers are safely cast by the Not matcher.
  2119. TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
  2120. // greater_than_5 is a monomorphic matcher.
  2121. Matcher<int> greater_than_5 = Gt(5);
  2122. Matcher<const int&> m = Not(greater_than_5);
  2123. Matcher<int&> m2 = Not(greater_than_5);
  2124. Matcher<int&> m3 = Not(m);
  2125. }
  2126. // Helper to allow easy testing of AllOf matchers with num parameters.
  2127. void AllOfMatches(int num, const Matcher<int>& m) {
  2128. SCOPED_TRACE(Describe(m));
  2129. EXPECT_TRUE(m.Matches(0));
  2130. for (int i = 1; i <= num; ++i) {
  2131. EXPECT_FALSE(m.Matches(i));
  2132. }
  2133. EXPECT_TRUE(m.Matches(num + 1));
  2134. }
  2135. // Tests that AllOf(m1, ..., mn) matches any value that matches all of
  2136. // the given matchers.
  2137. TEST(AllOfTest, MatchesWhenAllMatch) {
  2138. Matcher<int> m;
  2139. m = AllOf(Le(2), Ge(1));
  2140. EXPECT_TRUE(m.Matches(1));
  2141. EXPECT_TRUE(m.Matches(2));
  2142. EXPECT_FALSE(m.Matches(0));
  2143. EXPECT_FALSE(m.Matches(3));
  2144. m = AllOf(Gt(0), Ne(1), Ne(2));
  2145. EXPECT_TRUE(m.Matches(3));
  2146. EXPECT_FALSE(m.Matches(2));
  2147. EXPECT_FALSE(m.Matches(1));
  2148. EXPECT_FALSE(m.Matches(0));
  2149. m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
  2150. EXPECT_TRUE(m.Matches(4));
  2151. EXPECT_FALSE(m.Matches(3));
  2152. EXPECT_FALSE(m.Matches(2));
  2153. EXPECT_FALSE(m.Matches(1));
  2154. EXPECT_FALSE(m.Matches(0));
  2155. m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
  2156. EXPECT_TRUE(m.Matches(0));
  2157. EXPECT_TRUE(m.Matches(1));
  2158. EXPECT_FALSE(m.Matches(3));
  2159. // The following tests for varying number of sub-matchers. Due to the way
  2160. // the sub-matchers are handled it is enough to test every sub-matcher once
  2161. // with sub-matchers using the same matcher type. Varying matcher types are
  2162. // checked for above.
  2163. AllOfMatches(2, AllOf(Ne(1), Ne(2)));
  2164. AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
  2165. AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
  2166. AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
  2167. AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
  2168. AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
  2169. AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
  2170. Ne(8)));
  2171. AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
  2172. Ne(8), Ne(9)));
  2173. AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
  2174. Ne(9), Ne(10)));
  2175. AllOfMatches(
  2176. 50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
  2177. Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17),
  2178. Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25),
  2179. Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33),
  2180. Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41),
  2181. Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
  2182. Ne(50)));
  2183. }
  2184. // Tests that AllOf(m1, ..., mn) describes itself properly.
  2185. TEST(AllOfTest, CanDescribeSelf) {
  2186. Matcher<int> m;
  2187. m = AllOf(Le(2), Ge(1));
  2188. EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
  2189. m = AllOf(Gt(0), Ne(1), Ne(2));
  2190. std::string expected_descr1 =
  2191. "(is > 0) and (isn't equal to 1) and (isn't equal to 2)";
  2192. EXPECT_EQ(expected_descr1, Describe(m));
  2193. m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
  2194. std::string expected_descr2 =
  2195. "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal "
  2196. "to 3)";
  2197. EXPECT_EQ(expected_descr2, Describe(m));
  2198. m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
  2199. std::string expected_descr3 =
  2200. "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) "
  2201. "and (isn't equal to 7)";
  2202. EXPECT_EQ(expected_descr3, Describe(m));
  2203. }
  2204. // Tests that AllOf(m1, ..., mn) describes its negation properly.
  2205. TEST(AllOfTest, CanDescribeNegation) {
  2206. Matcher<int> m;
  2207. m = AllOf(Le(2), Ge(1));
  2208. std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)";
  2209. EXPECT_EQ(expected_descr4, DescribeNegation(m));
  2210. m = AllOf(Gt(0), Ne(1), Ne(2));
  2211. std::string expected_descr5 =
  2212. "(isn't > 0) or (is equal to 1) or (is equal to 2)";
  2213. EXPECT_EQ(expected_descr5, DescribeNegation(m));
  2214. m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
  2215. std::string expected_descr6 =
  2216. "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)";
  2217. EXPECT_EQ(expected_descr6, DescribeNegation(m));
  2218. m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
  2219. std::string expected_desr7 =
  2220. "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or "
  2221. "(is equal to 7)";
  2222. EXPECT_EQ(expected_desr7, DescribeNegation(m));
  2223. m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
  2224. Ne(10), Ne(11));
  2225. AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
  2226. EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
  2227. AllOfMatches(11, m);
  2228. }
  2229. // Tests that monomorphic matchers are safely cast by the AllOf matcher.
  2230. TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
  2231. // greater_than_5 and less_than_10 are monomorphic matchers.
  2232. Matcher<int> greater_than_5 = Gt(5);
  2233. Matcher<int> less_than_10 = Lt(10);
  2234. Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
  2235. Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
  2236. Matcher<int&> m3 = AllOf(greater_than_5, m2);
  2237. // Tests that BothOf works when composing itself.
  2238. Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
  2239. Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
  2240. }
  2241. TEST(AllOfTest, ExplainsResult) {
  2242. Matcher<int> m;
  2243. // Successful match. Both matchers need to explain. The second
  2244. // matcher doesn't give an explanation, so only the first matcher's
  2245. // explanation is printed.
  2246. m = AllOf(GreaterThan(10), Lt(30));
  2247. EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
  2248. // Successful match. Both matchers need to explain.
  2249. m = AllOf(GreaterThan(10), GreaterThan(20));
  2250. EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
  2251. Explain(m, 30));
  2252. // Successful match. All matchers need to explain. The second
  2253. // matcher doesn't given an explanation.
  2254. m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
  2255. EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
  2256. Explain(m, 25));
  2257. // Successful match. All matchers need to explain.
  2258. m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
  2259. EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
  2260. "and which is 10 more than 30",
  2261. Explain(m, 40));
  2262. // Failed match. The first matcher, which failed, needs to
  2263. // explain.
  2264. m = AllOf(GreaterThan(10), GreaterThan(20));
  2265. EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
  2266. // Failed match. The second matcher, which failed, needs to
  2267. // explain. Since it doesn't given an explanation, nothing is
  2268. // printed.
  2269. m = AllOf(GreaterThan(10), Lt(30));
  2270. EXPECT_EQ("", Explain(m, 40));
  2271. // Failed match. The second matcher, which failed, needs to
  2272. // explain.
  2273. m = AllOf(GreaterThan(10), GreaterThan(20));
  2274. EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
  2275. }
  2276. // Helper to allow easy testing of AnyOf matchers with num parameters.
  2277. static void AnyOfMatches(int num, const Matcher<int>& m) {
  2278. SCOPED_TRACE(Describe(m));
  2279. EXPECT_FALSE(m.Matches(0));
  2280. for (int i = 1; i <= num; ++i) {
  2281. EXPECT_TRUE(m.Matches(i));
  2282. }
  2283. EXPECT_FALSE(m.Matches(num + 1));
  2284. }
  2285. static void AnyOfStringMatches(int num, const Matcher<std::string>& m) {
  2286. SCOPED_TRACE(Describe(m));
  2287. EXPECT_FALSE(m.Matches(std::to_string(0)));
  2288. for (int i = 1; i <= num; ++i) {
  2289. EXPECT_TRUE(m.Matches(std::to_string(i)));
  2290. }
  2291. EXPECT_FALSE(m.Matches(std::to_string(num + 1)));
  2292. }
  2293. // Tests that AnyOf(m1, ..., mn) matches any value that matches at
  2294. // least one of the given matchers.
  2295. TEST(AnyOfTest, MatchesWhenAnyMatches) {
  2296. Matcher<int> m;
  2297. m = AnyOf(Le(1), Ge(3));
  2298. EXPECT_TRUE(m.Matches(1));
  2299. EXPECT_TRUE(m.Matches(4));
  2300. EXPECT_FALSE(m.Matches(2));
  2301. m = AnyOf(Lt(0), Eq(1), Eq(2));
  2302. EXPECT_TRUE(m.Matches(-1));
  2303. EXPECT_TRUE(m.Matches(1));
  2304. EXPECT_TRUE(m.Matches(2));
  2305. EXPECT_FALSE(m.Matches(0));
  2306. m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
  2307. EXPECT_TRUE(m.Matches(-1));
  2308. EXPECT_TRUE(m.Matches(1));
  2309. EXPECT_TRUE(m.Matches(2));
  2310. EXPECT_TRUE(m.Matches(3));
  2311. EXPECT_FALSE(m.Matches(0));
  2312. m = AnyOf(Le(0), Gt(10), 3, 5, 7);
  2313. EXPECT_TRUE(m.Matches(0));
  2314. EXPECT_TRUE(m.Matches(11));
  2315. EXPECT_TRUE(m.Matches(3));
  2316. EXPECT_FALSE(m.Matches(2));
  2317. // The following tests for varying number of sub-matchers. Due to the way
  2318. // the sub-matchers are handled it is enough to test every sub-matcher once
  2319. // with sub-matchers using the same matcher type. Varying matcher types are
  2320. // checked for above.
  2321. AnyOfMatches(2, AnyOf(1, 2));
  2322. AnyOfMatches(3, AnyOf(1, 2, 3));
  2323. AnyOfMatches(4, AnyOf(1, 2, 3, 4));
  2324. AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
  2325. AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
  2326. AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
  2327. AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
  2328. AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
  2329. AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
  2330. }
  2331. // Tests the variadic version of the AnyOfMatcher.
  2332. TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
  2333. // Also make sure AnyOf is defined in the right namespace and does not depend
  2334. // on ADL.
  2335. Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
  2336. EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)"));
  2337. AnyOfMatches(11, m);
  2338. AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  2339. 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  2340. 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
  2341. 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  2342. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
  2343. AnyOfStringMatches(
  2344. 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
  2345. "13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
  2346. "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
  2347. "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
  2348. "43", "44", "45", "46", "47", "48", "49", "50"));
  2349. }
  2350. // Tests the variadic version of the ElementsAreMatcher
  2351. TEST(ElementsAreTest, HugeMatcher) {
  2352. vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
  2353. EXPECT_THAT(test_vector,
  2354. ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
  2355. Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
  2356. }
  2357. // Tests the variadic version of the UnorderedElementsAreMatcher
  2358. TEST(ElementsAreTest, HugeMatcherStr) {
  2359. vector<std::string> test_vector{
  2360. "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
  2361. EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
  2362. _, _, _, _, _, _));
  2363. }
  2364. // Tests the variadic version of the UnorderedElementsAreMatcher
  2365. TEST(ElementsAreTest, HugeMatcherUnordered) {
  2366. vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
  2367. EXPECT_THAT(test_vector, UnorderedElementsAre(
  2368. Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
  2369. Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
  2370. }
  2371. // Tests that AnyOf(m1, ..., mn) describes itself properly.
  2372. TEST(AnyOfTest, CanDescribeSelf) {
  2373. Matcher<int> m;
  2374. m = AnyOf(Le(1), Ge(3));
  2375. EXPECT_EQ("(is <= 1) or (is >= 3)",
  2376. Describe(m));
  2377. m = AnyOf(Lt(0), Eq(1), Eq(2));
  2378. EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m));
  2379. m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
  2380. EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)",
  2381. Describe(m));
  2382. m = AnyOf(Le(0), Gt(10), 3, 5, 7);
  2383. EXPECT_EQ(
  2384. "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is "
  2385. "equal to 7)",
  2386. Describe(m));
  2387. }
  2388. // Tests that AnyOf(m1, ..., mn) describes its negation properly.
  2389. TEST(AnyOfTest, CanDescribeNegation) {
  2390. Matcher<int> m;
  2391. m = AnyOf(Le(1), Ge(3));
  2392. EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
  2393. DescribeNegation(m));
  2394. m = AnyOf(Lt(0), Eq(1), Eq(2));
  2395. EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)",
  2396. DescribeNegation(m));
  2397. m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
  2398. EXPECT_EQ(
  2399. "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't "
  2400. "equal to 3)",
  2401. DescribeNegation(m));
  2402. m = AnyOf(Le(0), Gt(10), 3, 5, 7);
  2403. EXPECT_EQ(
  2404. "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal "
  2405. "to 5) and (isn't equal to 7)",
  2406. DescribeNegation(m));
  2407. }
  2408. // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
  2409. TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
  2410. // greater_than_5 and less_than_10 are monomorphic matchers.
  2411. Matcher<int> greater_than_5 = Gt(5);
  2412. Matcher<int> less_than_10 = Lt(10);
  2413. Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
  2414. Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
  2415. Matcher<int&> m3 = AnyOf(greater_than_5, m2);
  2416. // Tests that EitherOf works when composing itself.
  2417. Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
  2418. Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
  2419. }
  2420. TEST(AnyOfTest, ExplainsResult) {
  2421. Matcher<int> m;
  2422. // Failed match. Both matchers need to explain. The second
  2423. // matcher doesn't give an explanation, so only the first matcher's
  2424. // explanation is printed.
  2425. m = AnyOf(GreaterThan(10), Lt(0));
  2426. EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
  2427. // Failed match. Both matchers need to explain.
  2428. m = AnyOf(GreaterThan(10), GreaterThan(20));
  2429. EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
  2430. Explain(m, 5));
  2431. // Failed match. All matchers need to explain. The second
  2432. // matcher doesn't given an explanation.
  2433. m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
  2434. EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
  2435. Explain(m, 5));
  2436. // Failed match. All matchers need to explain.
  2437. m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
  2438. EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
  2439. "and which is 25 less than 30",
  2440. Explain(m, 5));
  2441. // Successful match. The first matcher, which succeeded, needs to
  2442. // explain.
  2443. m = AnyOf(GreaterThan(10), GreaterThan(20));
  2444. EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
  2445. // Successful match. The second matcher, which succeeded, needs to
  2446. // explain. Since it doesn't given an explanation, nothing is
  2447. // printed.
  2448. m = AnyOf(GreaterThan(10), Lt(30));
  2449. EXPECT_EQ("", Explain(m, 0));
  2450. // Successful match. The second matcher, which succeeded, needs to
  2451. // explain.
  2452. m = AnyOf(GreaterThan(30), GreaterThan(20));
  2453. EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
  2454. }
  2455. // The following predicate function and predicate functor are for
  2456. // testing the Truly(predicate) matcher.
  2457. // Returns non-zero if the input is positive. Note that the return
  2458. // type of this function is not bool. It's OK as Truly() accepts any
  2459. // unary function or functor whose return type can be implicitly
  2460. // converted to bool.
  2461. int IsPositive(double x) {
  2462. return x > 0 ? 1 : 0;
  2463. }
  2464. // This functor returns true if the input is greater than the given
  2465. // number.
  2466. class IsGreaterThan {
  2467. public:
  2468. explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
  2469. bool operator()(int n) const { return n > threshold_; }
  2470. private:
  2471. int threshold_;
  2472. };
  2473. // For testing Truly().
  2474. const int foo = 0;
  2475. // This predicate returns true if and only if the argument references foo and
  2476. // has a zero value.
  2477. bool ReferencesFooAndIsZero(const int& n) {
  2478. return (&n == &foo) && (n == 0);
  2479. }
  2480. // Tests that Truly(predicate) matches what satisfies the given
  2481. // predicate.
  2482. TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
  2483. Matcher<double> m = Truly(IsPositive);
  2484. EXPECT_TRUE(m.Matches(2.0));
  2485. EXPECT_FALSE(m.Matches(-1.5));
  2486. }
  2487. // Tests that Truly(predicate_functor) works too.
  2488. TEST(TrulyTest, CanBeUsedWithFunctor) {
  2489. Matcher<int> m = Truly(IsGreaterThan(5));
  2490. EXPECT_TRUE(m.Matches(6));
  2491. EXPECT_FALSE(m.Matches(4));
  2492. }
  2493. // A class that can be implicitly converted to bool.
  2494. class ConvertibleToBool {
  2495. public:
  2496. explicit ConvertibleToBool(int number) : number_(number) {}
  2497. operator bool() const { return number_ != 0; }
  2498. private:
  2499. int number_;
  2500. };
  2501. ConvertibleToBool IsNotZero(int number) {
  2502. return ConvertibleToBool(number);
  2503. }
  2504. // Tests that the predicate used in Truly() may return a class that's
  2505. // implicitly convertible to bool, even when the class has no
  2506. // operator!().
  2507. TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
  2508. Matcher<int> m = Truly(IsNotZero);
  2509. EXPECT_TRUE(m.Matches(1));
  2510. EXPECT_FALSE(m.Matches(0));
  2511. }
  2512. // Tests that Truly(predicate) can describe itself properly.
  2513. TEST(TrulyTest, CanDescribeSelf) {
  2514. Matcher<double> m = Truly(IsPositive);
  2515. EXPECT_EQ("satisfies the given predicate",
  2516. Describe(m));
  2517. }
  2518. // Tests that Truly(predicate) works when the matcher takes its
  2519. // argument by reference.
  2520. TEST(TrulyTest, WorksForByRefArguments) {
  2521. Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
  2522. EXPECT_TRUE(m.Matches(foo));
  2523. int n = 0;
  2524. EXPECT_FALSE(m.Matches(n));
  2525. }
  2526. // Tests that Truly(predicate) provides a helpful reason when it fails.
  2527. TEST(TrulyTest, ExplainsFailures) {
  2528. StringMatchResultListener listener;
  2529. EXPECT_FALSE(ExplainMatchResult(Truly(IsPositive), -1, &listener));
  2530. EXPECT_EQ(listener.str(), "didn't satisfy the given predicate");
  2531. }
  2532. // Tests that Matches(m) is a predicate satisfied by whatever that
  2533. // matches matcher m.
  2534. TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
  2535. EXPECT_TRUE(Matches(Ge(0))(1));
  2536. EXPECT_FALSE(Matches(Eq('a'))('b'));
  2537. }
  2538. // Tests that Matches(m) works when the matcher takes its argument by
  2539. // reference.
  2540. TEST(MatchesTest, WorksOnByRefArguments) {
  2541. int m = 0, n = 0;
  2542. EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
  2543. EXPECT_FALSE(Matches(Ref(m))(n));
  2544. }
  2545. // Tests that a Matcher on non-reference type can be used in
  2546. // Matches().
  2547. TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
  2548. Matcher<int> eq5 = Eq(5);
  2549. EXPECT_TRUE(Matches(eq5)(5));
  2550. EXPECT_FALSE(Matches(eq5)(2));
  2551. }
  2552. // Tests Value(value, matcher). Since Value() is a simple wrapper for
  2553. // Matches(), which has been tested already, we don't spend a lot of
  2554. // effort on testing Value().
  2555. TEST(ValueTest, WorksWithPolymorphicMatcher) {
  2556. EXPECT_TRUE(Value("hi", StartsWith("h")));
  2557. EXPECT_FALSE(Value(5, Gt(10)));
  2558. }
  2559. TEST(ValueTest, WorksWithMonomorphicMatcher) {
  2560. const Matcher<int> is_zero = Eq(0);
  2561. EXPECT_TRUE(Value(0, is_zero));
  2562. EXPECT_FALSE(Value('a', is_zero));
  2563. int n = 0;
  2564. const Matcher<const int&> ref_n = Ref(n);
  2565. EXPECT_TRUE(Value(n, ref_n));
  2566. EXPECT_FALSE(Value(1, ref_n));
  2567. }
  2568. TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
  2569. StringMatchResultListener listener1;
  2570. EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
  2571. EXPECT_EQ("% 2 == 0", listener1.str());
  2572. StringMatchResultListener listener2;
  2573. EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
  2574. EXPECT_EQ("", listener2.str());
  2575. }
  2576. TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
  2577. const Matcher<int> is_even = PolymorphicIsEven();
  2578. StringMatchResultListener listener1;
  2579. EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
  2580. EXPECT_EQ("% 2 == 0", listener1.str());
  2581. const Matcher<const double&> is_zero = Eq(0);
  2582. StringMatchResultListener listener2;
  2583. EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
  2584. EXPECT_EQ("", listener2.str());
  2585. }
  2586. MATCHER(ConstructNoArg, "") { return true; }
  2587. MATCHER_P(Construct1Arg, arg1, "") { return true; }
  2588. MATCHER_P2(Construct2Args, arg1, arg2, "") { return true; }
  2589. TEST(MatcherConstruct, ExplicitVsImplicit) {
  2590. {
  2591. // No arg constructor can be constructed with empty brace.
  2592. ConstructNoArgMatcher m = {};
  2593. (void)m;
  2594. // And with no args
  2595. ConstructNoArgMatcher m2;
  2596. (void)m2;
  2597. }
  2598. {
  2599. // The one arg constructor has an explicit constructor.
  2600. // This is to prevent the implicit conversion.
  2601. using M = Construct1ArgMatcherP<int>;
  2602. EXPECT_TRUE((std::is_constructible<M, int>::value));
  2603. EXPECT_FALSE((std::is_convertible<int, M>::value));
  2604. }
  2605. {
  2606. // Multiple arg matchers can be constructed with an implicit construction.
  2607. Construct2ArgsMatcherP2<int, double> m = {1, 2.2};
  2608. (void)m;
  2609. }
  2610. }
  2611. MATCHER_P(Really, inner_matcher, "") {
  2612. return ExplainMatchResult(inner_matcher, arg, result_listener);
  2613. }
  2614. TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
  2615. EXPECT_THAT(0, Really(Eq(0)));
  2616. }
  2617. TEST(DescribeMatcherTest, WorksWithValue) {
  2618. EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
  2619. EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
  2620. }
  2621. TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
  2622. const Matcher<int> monomorphic = Le(0);
  2623. EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
  2624. EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
  2625. }
  2626. TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
  2627. EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
  2628. EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
  2629. }
  2630. TEST(AllArgsTest, WorksForTuple) {
  2631. EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt()));
  2632. EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt())));
  2633. }
  2634. TEST(AllArgsTest, WorksForNonTuple) {
  2635. EXPECT_THAT(42, AllArgs(Gt(0)));
  2636. EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
  2637. }
  2638. class AllArgsHelper {
  2639. public:
  2640. AllArgsHelper() {}
  2641. MOCK_METHOD2(Helper, int(char x, int y));
  2642. private:
  2643. GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
  2644. };
  2645. TEST(AllArgsTest, WorksInWithClause) {
  2646. AllArgsHelper helper;
  2647. ON_CALL(helper, Helper(_, _))
  2648. .With(AllArgs(Lt()))
  2649. .WillByDefault(Return(1));
  2650. EXPECT_CALL(helper, Helper(_, _));
  2651. EXPECT_CALL(helper, Helper(_, _))
  2652. .With(AllArgs(Gt()))
  2653. .WillOnce(Return(2));
  2654. EXPECT_EQ(1, helper.Helper('\1', 2));
  2655. EXPECT_EQ(2, helper.Helper('a', 1));
  2656. }
  2657. class OptionalMatchersHelper {
  2658. public:
  2659. OptionalMatchersHelper() {}
  2660. MOCK_METHOD0(NoArgs, int());
  2661. MOCK_METHOD1(OneArg, int(int y));
  2662. MOCK_METHOD2(TwoArgs, int(char x, int y));
  2663. MOCK_METHOD1(Overloaded, int(char x));
  2664. MOCK_METHOD2(Overloaded, int(char x, int y));
  2665. private:
  2666. GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper);
  2667. };
  2668. TEST(AllArgsTest, WorksWithoutMatchers) {
  2669. OptionalMatchersHelper helper;
  2670. ON_CALL(helper, NoArgs).WillByDefault(Return(10));
  2671. ON_CALL(helper, OneArg).WillByDefault(Return(20));
  2672. ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
  2673. EXPECT_EQ(10, helper.NoArgs());
  2674. EXPECT_EQ(20, helper.OneArg(1));
  2675. EXPECT_EQ(30, helper.TwoArgs('\1', 2));
  2676. EXPECT_CALL(helper, NoArgs).Times(1);
  2677. EXPECT_CALL(helper, OneArg).WillOnce(Return(100));
  2678. EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));
  2679. EXPECT_CALL(helper, TwoArgs).Times(0);
  2680. EXPECT_EQ(10, helper.NoArgs());
  2681. EXPECT_EQ(100, helper.OneArg(1));
  2682. EXPECT_EQ(200, helper.OneArg(17));
  2683. }
  2684. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
  2685. // matches the matcher.
  2686. TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
  2687. ASSERT_THAT(5, Ge(2)) << "This should succeed.";
  2688. ASSERT_THAT("Foo", EndsWith("oo"));
  2689. EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
  2690. EXPECT_THAT("Hello", StartsWith("Hell"));
  2691. }
  2692. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
  2693. // doesn't match the matcher.
  2694. TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
  2695. // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
  2696. // which cannot reference auto variables.
  2697. static unsigned short n; // NOLINT
  2698. n = 5;
  2699. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),
  2700. "Value of: n\n"
  2701. "Expected: is > 10\n"
  2702. " Actual: 5" + OfType("unsigned short"));
  2703. n = 0;
  2704. EXPECT_NONFATAL_FAILURE(
  2705. EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
  2706. "Value of: n\n"
  2707. "Expected: (is <= 7) and (is >= 5)\n"
  2708. " Actual: 0" + OfType("unsigned short"));
  2709. }
  2710. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
  2711. // has a reference type.
  2712. TEST(MatcherAssertionTest, WorksForByRefArguments) {
  2713. // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
  2714. // reference auto variables.
  2715. static int n;
  2716. n = 0;
  2717. EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
  2718. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
  2719. "Value of: n\n"
  2720. "Expected: does not reference the variable @");
  2721. // Tests the "Actual" part.
  2722. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
  2723. "Actual: 0" + OfType("int") + ", which is located @");
  2724. }
  2725. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
  2726. // monomorphic.
  2727. TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
  2728. Matcher<const char*> starts_with_he = StartsWith("he");
  2729. ASSERT_THAT("hello", starts_with_he);
  2730. Matcher<const std::string&> ends_with_ok = EndsWith("ok");
  2731. ASSERT_THAT("book", ends_with_ok);
  2732. const std::string bad = "bad";
  2733. EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
  2734. "Value of: bad\n"
  2735. "Expected: ends with \"ok\"\n"
  2736. " Actual: \"bad\"");
  2737. Matcher<int> is_greater_than_5 = Gt(5);
  2738. EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
  2739. "Value of: 5\n"
  2740. "Expected: is > 5\n"
  2741. " Actual: 5" + OfType("int"));
  2742. }
  2743. // Tests floating-point matchers.
  2744. template <typename RawType>
  2745. class FloatingPointTest : public testing::Test {
  2746. protected:
  2747. typedef testing::internal::FloatingPoint<RawType> Floating;
  2748. typedef typename Floating::Bits Bits;
  2749. FloatingPointTest()
  2750. : max_ulps_(Floating::kMaxUlps),
  2751. zero_bits_(Floating(0).bits()),
  2752. one_bits_(Floating(1).bits()),
  2753. infinity_bits_(Floating(Floating::Infinity()).bits()),
  2754. close_to_positive_zero_(
  2755. Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
  2756. close_to_negative_zero_(
  2757. -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
  2758. further_from_negative_zero_(-Floating::ReinterpretBits(
  2759. zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
  2760. close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
  2761. further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
  2762. infinity_(Floating::Infinity()),
  2763. close_to_infinity_(
  2764. Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
  2765. further_from_infinity_(
  2766. Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
  2767. max_(Floating::Max()),
  2768. nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
  2769. nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
  2770. }
  2771. void TestSize() {
  2772. EXPECT_EQ(sizeof(RawType), sizeof(Bits));
  2773. }
  2774. // A battery of tests for FloatingEqMatcher::Matches.
  2775. // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
  2776. void TestMatches(
  2777. testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
  2778. Matcher<RawType> m1 = matcher_maker(0.0);
  2779. EXPECT_TRUE(m1.Matches(-0.0));
  2780. EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
  2781. EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
  2782. EXPECT_FALSE(m1.Matches(1.0));
  2783. Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
  2784. EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
  2785. Matcher<RawType> m3 = matcher_maker(1.0);
  2786. EXPECT_TRUE(m3.Matches(close_to_one_));
  2787. EXPECT_FALSE(m3.Matches(further_from_one_));
  2788. // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
  2789. EXPECT_FALSE(m3.Matches(0.0));
  2790. Matcher<RawType> m4 = matcher_maker(-infinity_);
  2791. EXPECT_TRUE(m4.Matches(-close_to_infinity_));
  2792. Matcher<RawType> m5 = matcher_maker(infinity_);
  2793. EXPECT_TRUE(m5.Matches(close_to_infinity_));
  2794. // This is interesting as the representations of infinity_ and nan1_
  2795. // are only 1 DLP apart.
  2796. EXPECT_FALSE(m5.Matches(nan1_));
  2797. // matcher_maker can produce a Matcher<const RawType&>, which is needed in
  2798. // some cases.
  2799. Matcher<const RawType&> m6 = matcher_maker(0.0);
  2800. EXPECT_TRUE(m6.Matches(-0.0));
  2801. EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
  2802. EXPECT_FALSE(m6.Matches(1.0));
  2803. // matcher_maker can produce a Matcher<RawType&>, which is needed in some
  2804. // cases.
  2805. Matcher<RawType&> m7 = matcher_maker(0.0);
  2806. RawType x = 0.0;
  2807. EXPECT_TRUE(m7.Matches(x));
  2808. x = 0.01f;
  2809. EXPECT_FALSE(m7.Matches(x));
  2810. }
  2811. // Pre-calculated numbers to be used by the tests.
  2812. const Bits max_ulps_;
  2813. const Bits zero_bits_; // The bits that represent 0.0.
  2814. const Bits one_bits_; // The bits that represent 1.0.
  2815. const Bits infinity_bits_; // The bits that represent +infinity.
  2816. // Some numbers close to 0.0.
  2817. const RawType close_to_positive_zero_;
  2818. const RawType close_to_negative_zero_;
  2819. const RawType further_from_negative_zero_;
  2820. // Some numbers close to 1.0.
  2821. const RawType close_to_one_;
  2822. const RawType further_from_one_;
  2823. // Some numbers close to +infinity.
  2824. const RawType infinity_;
  2825. const RawType close_to_infinity_;
  2826. const RawType further_from_infinity_;
  2827. // Maximum representable value that's not infinity.
  2828. const RawType max_;
  2829. // Some NaNs.
  2830. const RawType nan1_;
  2831. const RawType nan2_;
  2832. };
  2833. // Tests floating-point matchers with fixed epsilons.
  2834. template <typename RawType>
  2835. class FloatingPointNearTest : public FloatingPointTest<RawType> {
  2836. protected:
  2837. typedef FloatingPointTest<RawType> ParentType;
  2838. // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
  2839. // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
  2840. void TestNearMatches(
  2841. testing::internal::FloatingEqMatcher<RawType>
  2842. (*matcher_maker)(RawType, RawType)) {
  2843. Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
  2844. EXPECT_TRUE(m1.Matches(0.0));
  2845. EXPECT_TRUE(m1.Matches(-0.0));
  2846. EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
  2847. EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
  2848. EXPECT_FALSE(m1.Matches(1.0));
  2849. Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
  2850. EXPECT_TRUE(m2.Matches(0.0));
  2851. EXPECT_TRUE(m2.Matches(-0.0));
  2852. EXPECT_TRUE(m2.Matches(1.0));
  2853. EXPECT_TRUE(m2.Matches(-1.0));
  2854. EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
  2855. EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
  2856. // Check that inf matches inf, regardless of the of the specified max
  2857. // absolute error.
  2858. Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
  2859. EXPECT_TRUE(m3.Matches(ParentType::infinity_));
  2860. EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
  2861. EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
  2862. Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
  2863. EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
  2864. EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
  2865. EXPECT_FALSE(m4.Matches(ParentType::infinity_));
  2866. // Test various overflow scenarios.
  2867. Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
  2868. EXPECT_TRUE(m5.Matches(ParentType::max_));
  2869. EXPECT_FALSE(m5.Matches(-ParentType::max_));
  2870. Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
  2871. EXPECT_FALSE(m6.Matches(ParentType::max_));
  2872. EXPECT_TRUE(m6.Matches(-ParentType::max_));
  2873. Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
  2874. EXPECT_TRUE(m7.Matches(ParentType::max_));
  2875. EXPECT_FALSE(m7.Matches(-ParentType::max_));
  2876. Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
  2877. EXPECT_FALSE(m8.Matches(ParentType::max_));
  2878. EXPECT_TRUE(m8.Matches(-ParentType::max_));
  2879. // The difference between max() and -max() normally overflows to infinity,
  2880. // but it should still match if the max_abs_error is also infinity.
  2881. Matcher<RawType> m9 = matcher_maker(
  2882. ParentType::max_, ParentType::infinity_);
  2883. EXPECT_TRUE(m8.Matches(-ParentType::max_));
  2884. // matcher_maker can produce a Matcher<const RawType&>, which is needed in
  2885. // some cases.
  2886. Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
  2887. EXPECT_TRUE(m10.Matches(-0.0));
  2888. EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
  2889. EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
  2890. // matcher_maker can produce a Matcher<RawType&>, which is needed in some
  2891. // cases.
  2892. Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
  2893. RawType x = 0.0;
  2894. EXPECT_TRUE(m11.Matches(x));
  2895. x = 1.0f;
  2896. EXPECT_TRUE(m11.Matches(x));
  2897. x = -1.0f;
  2898. EXPECT_TRUE(m11.Matches(x));
  2899. x = 1.1f;
  2900. EXPECT_FALSE(m11.Matches(x));
  2901. x = -1.1f;
  2902. EXPECT_FALSE(m11.Matches(x));
  2903. }
  2904. };
  2905. // Instantiate FloatingPointTest for testing floats.
  2906. typedef FloatingPointTest<float> FloatTest;
  2907. TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
  2908. TestMatches(&FloatEq);
  2909. }
  2910. TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
  2911. TestMatches(&NanSensitiveFloatEq);
  2912. }
  2913. TEST_F(FloatTest, FloatEqCannotMatchNaN) {
  2914. // FloatEq never matches NaN.
  2915. Matcher<float> m = FloatEq(nan1_);
  2916. EXPECT_FALSE(m.Matches(nan1_));
  2917. EXPECT_FALSE(m.Matches(nan2_));
  2918. EXPECT_FALSE(m.Matches(1.0));
  2919. }
  2920. TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
  2921. // NanSensitiveFloatEq will match NaN.
  2922. Matcher<float> m = NanSensitiveFloatEq(nan1_);
  2923. EXPECT_TRUE(m.Matches(nan1_));
  2924. EXPECT_TRUE(m.Matches(nan2_));
  2925. EXPECT_FALSE(m.Matches(1.0));
  2926. }
  2927. TEST_F(FloatTest, FloatEqCanDescribeSelf) {
  2928. Matcher<float> m1 = FloatEq(2.0f);
  2929. EXPECT_EQ("is approximately 2", Describe(m1));
  2930. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2931. Matcher<float> m2 = FloatEq(0.5f);
  2932. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2933. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2934. Matcher<float> m3 = FloatEq(nan1_);
  2935. EXPECT_EQ("never matches", Describe(m3));
  2936. EXPECT_EQ("is anything", DescribeNegation(m3));
  2937. }
  2938. TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
  2939. Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
  2940. EXPECT_EQ("is approximately 2", Describe(m1));
  2941. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2942. Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
  2943. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2944. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2945. Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
  2946. EXPECT_EQ("is NaN", Describe(m3));
  2947. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2948. }
  2949. // Instantiate FloatingPointTest for testing floats with a user-specified
  2950. // max absolute error.
  2951. typedef FloatingPointNearTest<float> FloatNearTest;
  2952. TEST_F(FloatNearTest, FloatNearMatches) {
  2953. TestNearMatches(&FloatNear);
  2954. }
  2955. TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
  2956. TestNearMatches(&NanSensitiveFloatNear);
  2957. }
  2958. TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
  2959. Matcher<float> m1 = FloatNear(2.0f, 0.5f);
  2960. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2961. EXPECT_EQ(
  2962. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2963. Matcher<float> m2 = FloatNear(0.5f, 0.5f);
  2964. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2965. EXPECT_EQ(
  2966. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2967. Matcher<float> m3 = FloatNear(nan1_, 0.0);
  2968. EXPECT_EQ("never matches", Describe(m3));
  2969. EXPECT_EQ("is anything", DescribeNegation(m3));
  2970. }
  2971. TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
  2972. Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
  2973. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2974. EXPECT_EQ(
  2975. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2976. Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
  2977. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2978. EXPECT_EQ(
  2979. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2980. Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
  2981. EXPECT_EQ("is NaN", Describe(m3));
  2982. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2983. }
  2984. TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
  2985. // FloatNear never matches NaN.
  2986. Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
  2987. EXPECT_FALSE(m.Matches(nan1_));
  2988. EXPECT_FALSE(m.Matches(nan2_));
  2989. EXPECT_FALSE(m.Matches(1.0));
  2990. }
  2991. TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
  2992. // NanSensitiveFloatNear will match NaN.
  2993. Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
  2994. EXPECT_TRUE(m.Matches(nan1_));
  2995. EXPECT_TRUE(m.Matches(nan2_));
  2996. EXPECT_FALSE(m.Matches(1.0));
  2997. }
  2998. // Instantiate FloatingPointTest for testing doubles.
  2999. typedef FloatingPointTest<double> DoubleTest;
  3000. TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
  3001. TestMatches(&DoubleEq);
  3002. }
  3003. TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
  3004. TestMatches(&NanSensitiveDoubleEq);
  3005. }
  3006. TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
  3007. // DoubleEq never matches NaN.
  3008. Matcher<double> m = DoubleEq(nan1_);
  3009. EXPECT_FALSE(m.Matches(nan1_));
  3010. EXPECT_FALSE(m.Matches(nan2_));
  3011. EXPECT_FALSE(m.Matches(1.0));
  3012. }
  3013. TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
  3014. // NanSensitiveDoubleEq will match NaN.
  3015. Matcher<double> m = NanSensitiveDoubleEq(nan1_);
  3016. EXPECT_TRUE(m.Matches(nan1_));
  3017. EXPECT_TRUE(m.Matches(nan2_));
  3018. EXPECT_FALSE(m.Matches(1.0));
  3019. }
  3020. TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
  3021. Matcher<double> m1 = DoubleEq(2.0);
  3022. EXPECT_EQ("is approximately 2", Describe(m1));
  3023. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  3024. Matcher<double> m2 = DoubleEq(0.5);
  3025. EXPECT_EQ("is approximately 0.5", Describe(m2));
  3026. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  3027. Matcher<double> m3 = DoubleEq(nan1_);
  3028. EXPECT_EQ("never matches", Describe(m3));
  3029. EXPECT_EQ("is anything", DescribeNegation(m3));
  3030. }
  3031. TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
  3032. Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
  3033. EXPECT_EQ("is approximately 2", Describe(m1));
  3034. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  3035. Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
  3036. EXPECT_EQ("is approximately 0.5", Describe(m2));
  3037. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  3038. Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
  3039. EXPECT_EQ("is NaN", Describe(m3));
  3040. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  3041. }
  3042. // Instantiate FloatingPointTest for testing floats with a user-specified
  3043. // max absolute error.
  3044. typedef FloatingPointNearTest<double> DoubleNearTest;
  3045. TEST_F(DoubleNearTest, DoubleNearMatches) {
  3046. TestNearMatches(&DoubleNear);
  3047. }
  3048. TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
  3049. TestNearMatches(&NanSensitiveDoubleNear);
  3050. }
  3051. TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
  3052. Matcher<double> m1 = DoubleNear(2.0, 0.5);
  3053. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  3054. EXPECT_EQ(
  3055. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  3056. Matcher<double> m2 = DoubleNear(0.5, 0.5);
  3057. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  3058. EXPECT_EQ(
  3059. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  3060. Matcher<double> m3 = DoubleNear(nan1_, 0.0);
  3061. EXPECT_EQ("never matches", Describe(m3));
  3062. EXPECT_EQ("is anything", DescribeNegation(m3));
  3063. }
  3064. TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
  3065. EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
  3066. EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
  3067. EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
  3068. const std::string explanation =
  3069. Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
  3070. // Different C++ implementations may print floating-point numbers
  3071. // slightly differently.
  3072. EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
  3073. explanation == "which is 1.2e-010 from 2.1") // MSVC
  3074. << " where explanation is \"" << explanation << "\".";
  3075. }
  3076. TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
  3077. Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
  3078. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  3079. EXPECT_EQ(
  3080. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  3081. Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
  3082. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  3083. EXPECT_EQ(
  3084. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  3085. Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
  3086. EXPECT_EQ("is NaN", Describe(m3));
  3087. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  3088. }
  3089. TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
  3090. // DoubleNear never matches NaN.
  3091. Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
  3092. EXPECT_FALSE(m.Matches(nan1_));
  3093. EXPECT_FALSE(m.Matches(nan2_));
  3094. EXPECT_FALSE(m.Matches(1.0));
  3095. }
  3096. TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
  3097. // NanSensitiveDoubleNear will match NaN.
  3098. Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
  3099. EXPECT_TRUE(m.Matches(nan1_));
  3100. EXPECT_TRUE(m.Matches(nan2_));
  3101. EXPECT_FALSE(m.Matches(1.0));
  3102. }
  3103. TEST(PointeeTest, RawPointer) {
  3104. const Matcher<int*> m = Pointee(Ge(0));
  3105. int n = 1;
  3106. EXPECT_TRUE(m.Matches(&n));
  3107. n = -1;
  3108. EXPECT_FALSE(m.Matches(&n));
  3109. EXPECT_FALSE(m.Matches(nullptr));
  3110. }
  3111. TEST(PointeeTest, RawPointerToConst) {
  3112. const Matcher<const double*> m = Pointee(Ge(0));
  3113. double x = 1;
  3114. EXPECT_TRUE(m.Matches(&x));
  3115. x = -1;
  3116. EXPECT_FALSE(m.Matches(&x));
  3117. EXPECT_FALSE(m.Matches(nullptr));
  3118. }
  3119. TEST(PointeeTest, ReferenceToConstRawPointer) {
  3120. const Matcher<int* const &> m = Pointee(Ge(0));
  3121. int n = 1;
  3122. EXPECT_TRUE(m.Matches(&n));
  3123. n = -1;
  3124. EXPECT_FALSE(m.Matches(&n));
  3125. EXPECT_FALSE(m.Matches(nullptr));
  3126. }
  3127. TEST(PointeeTest, ReferenceToNonConstRawPointer) {
  3128. const Matcher<double* &> m = Pointee(Ge(0));
  3129. double x = 1.0;
  3130. double* p = &x;
  3131. EXPECT_TRUE(m.Matches(p));
  3132. x = -1;
  3133. EXPECT_FALSE(m.Matches(p));
  3134. p = nullptr;
  3135. EXPECT_FALSE(m.Matches(p));
  3136. }
  3137. TEST(PointeeTest, SmartPointer) {
  3138. const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
  3139. std::unique_ptr<int> n(new int(1));
  3140. EXPECT_TRUE(m.Matches(n));
  3141. }
  3142. TEST(PointeeTest, SmartPointerToConst) {
  3143. const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));
  3144. // There's no implicit conversion from unique_ptr<int> to const
  3145. // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
  3146. // matcher.
  3147. std::unique_ptr<const int> n(new int(1));
  3148. EXPECT_TRUE(m.Matches(n));
  3149. }
  3150. TEST(PointerTest, RawPointer) {
  3151. int n = 1;
  3152. const Matcher<int*> m = Pointer(Eq(&n));
  3153. EXPECT_TRUE(m.Matches(&n));
  3154. int* p = nullptr;
  3155. EXPECT_FALSE(m.Matches(p));
  3156. EXPECT_FALSE(m.Matches(nullptr));
  3157. }
  3158. TEST(PointerTest, RawPointerToConst) {
  3159. int n = 1;
  3160. const Matcher<const int*> m = Pointer(Eq(&n));
  3161. EXPECT_TRUE(m.Matches(&n));
  3162. int* p = nullptr;
  3163. EXPECT_FALSE(m.Matches(p));
  3164. EXPECT_FALSE(m.Matches(nullptr));
  3165. }
  3166. TEST(PointerTest, SmartPointer) {
  3167. std::unique_ptr<int> n(new int(10));
  3168. int* raw_n = n.get();
  3169. const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
  3170. EXPECT_TRUE(m.Matches(n));
  3171. }
  3172. TEST(PointerTest, SmartPointerToConst) {
  3173. std::unique_ptr<const int> n(new int(10));
  3174. const int* raw_n = n.get();
  3175. const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n));
  3176. // There's no implicit conversion from unique_ptr<int> to const
  3177. // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
  3178. // matcher.
  3179. std::unique_ptr<const int> p(new int(10));
  3180. EXPECT_FALSE(m.Matches(p));
  3181. }
  3182. TEST(AddressTest, NonConst) {
  3183. int n = 1;
  3184. const Matcher<int> m = Address(Eq(&n));
  3185. EXPECT_TRUE(m.Matches(n));
  3186. int other = 5;
  3187. EXPECT_FALSE(m.Matches(other));
  3188. int& n_ref = n;
  3189. EXPECT_TRUE(m.Matches(n_ref));
  3190. }
  3191. TEST(AddressTest, Const) {
  3192. const int n = 1;
  3193. const Matcher<int> m = Address(Eq(&n));
  3194. EXPECT_TRUE(m.Matches(n));
  3195. int other = 5;
  3196. EXPECT_FALSE(m.Matches(other));
  3197. }
  3198. TEST(AddressTest, MatcherDoesntCopy) {
  3199. std::unique_ptr<int> n(new int(1));
  3200. const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));
  3201. EXPECT_TRUE(m.Matches(n));
  3202. }
  3203. TEST(AddressTest, Describe) {
  3204. Matcher<int> matcher = Address(_);
  3205. EXPECT_EQ("has address that is anything", Describe(matcher));
  3206. EXPECT_EQ("does not have address that is anything",
  3207. DescribeNegation(matcher));
  3208. }
  3209. MATCHER_P(FieldIIs, inner_matcher, "") {
  3210. return ExplainMatchResult(inner_matcher, arg.i, result_listener);
  3211. }
  3212. #if GTEST_HAS_RTTI
  3213. TEST(WhenDynamicCastToTest, SameType) {
  3214. Derived derived;
  3215. derived.i = 4;
  3216. // Right type. A pointer is passed down.
  3217. Base* as_base_ptr = &derived;
  3218. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
  3219. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
  3220. EXPECT_THAT(as_base_ptr,
  3221. Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
  3222. }
  3223. TEST(WhenDynamicCastToTest, WrongTypes) {
  3224. Base base;
  3225. Derived derived;
  3226. OtherDerived other_derived;
  3227. // Wrong types. NULL is passed.
  3228. EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
  3229. EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
  3230. Base* as_base_ptr = &derived;
  3231. EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
  3232. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
  3233. as_base_ptr = &other_derived;
  3234. EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
  3235. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
  3236. }
  3237. TEST(WhenDynamicCastToTest, AlreadyNull) {
  3238. // Already NULL.
  3239. Base* as_base_ptr = nullptr;
  3240. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
  3241. }
  3242. struct AmbiguousCastTypes {
  3243. class VirtualDerived : public virtual Base {};
  3244. class DerivedSub1 : public VirtualDerived {};
  3245. class DerivedSub2 : public VirtualDerived {};
  3246. class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
  3247. };
  3248. TEST(WhenDynamicCastToTest, AmbiguousCast) {
  3249. AmbiguousCastTypes::DerivedSub1 sub1;
  3250. AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
  3251. // Multiply derived from Base. dynamic_cast<> returns NULL.
  3252. Base* as_base_ptr =
  3253. static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
  3254. EXPECT_THAT(as_base_ptr,
  3255. WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
  3256. as_base_ptr = &sub1;
  3257. EXPECT_THAT(
  3258. as_base_ptr,
  3259. WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
  3260. }
  3261. TEST(WhenDynamicCastToTest, Describe) {
  3262. Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
  3263. const std::string prefix =
  3264. "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
  3265. EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
  3266. EXPECT_EQ(prefix + "does not point to a value that is anything",
  3267. DescribeNegation(matcher));
  3268. }
  3269. TEST(WhenDynamicCastToTest, Explain) {
  3270. Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
  3271. Base* null = nullptr;
  3272. EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
  3273. Derived derived;
  3274. EXPECT_TRUE(matcher.Matches(&derived));
  3275. EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
  3276. // With references, the matcher itself can fail. Test for that one.
  3277. Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
  3278. EXPECT_THAT(Explain(ref_matcher, derived),
  3279. HasSubstr("which cannot be dynamic_cast"));
  3280. }
  3281. TEST(WhenDynamicCastToTest, GoodReference) {
  3282. Derived derived;
  3283. derived.i = 4;
  3284. Base& as_base_ref = derived;
  3285. EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
  3286. EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
  3287. }
  3288. TEST(WhenDynamicCastToTest, BadReference) {
  3289. Derived derived;
  3290. Base& as_base_ref = derived;
  3291. EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
  3292. }
  3293. #endif // GTEST_HAS_RTTI
  3294. // Minimal const-propagating pointer.
  3295. template <typename T>
  3296. class ConstPropagatingPtr {
  3297. public:
  3298. typedef T element_type;
  3299. ConstPropagatingPtr() : val_() {}
  3300. explicit ConstPropagatingPtr(T* t) : val_(t) {}
  3301. ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
  3302. T* get() { return val_; }
  3303. T& operator*() { return *val_; }
  3304. // Most smart pointers return non-const T* and T& from the next methods.
  3305. const T* get() const { return val_; }
  3306. const T& operator*() const { return *val_; }
  3307. private:
  3308. T* val_;
  3309. };
  3310. TEST(PointeeTest, WorksWithConstPropagatingPointers) {
  3311. const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
  3312. int three = 3;
  3313. const ConstPropagatingPtr<int> co(&three);
  3314. ConstPropagatingPtr<int> o(&three);
  3315. EXPECT_TRUE(m.Matches(o));
  3316. EXPECT_TRUE(m.Matches(co));
  3317. *o = 6;
  3318. EXPECT_FALSE(m.Matches(o));
  3319. EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
  3320. }
  3321. TEST(PointeeTest, NeverMatchesNull) {
  3322. const Matcher<const char*> m = Pointee(_);
  3323. EXPECT_FALSE(m.Matches(nullptr));
  3324. }
  3325. // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
  3326. TEST(PointeeTest, MatchesAgainstAValue) {
  3327. const Matcher<int*> m = Pointee(5);
  3328. int n = 5;
  3329. EXPECT_TRUE(m.Matches(&n));
  3330. n = -1;
  3331. EXPECT_FALSE(m.Matches(&n));
  3332. EXPECT_FALSE(m.Matches(nullptr));
  3333. }
  3334. TEST(PointeeTest, CanDescribeSelf) {
  3335. const Matcher<int*> m = Pointee(Gt(3));
  3336. EXPECT_EQ("points to a value that is > 3", Describe(m));
  3337. EXPECT_EQ("does not point to a value that is > 3",
  3338. DescribeNegation(m));
  3339. }
  3340. TEST(PointeeTest, CanExplainMatchResult) {
  3341. const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
  3342. EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
  3343. const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
  3344. long n = 3; // NOLINT
  3345. EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
  3346. Explain(m2, &n));
  3347. }
  3348. TEST(PointeeTest, AlwaysExplainsPointee) {
  3349. const Matcher<int*> m = Pointee(0);
  3350. int n = 42;
  3351. EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
  3352. }
  3353. // An uncopyable class.
  3354. class Uncopyable {
  3355. public:
  3356. Uncopyable() : value_(-1) {}
  3357. explicit Uncopyable(int a_value) : value_(a_value) {}
  3358. int value() const { return value_; }
  3359. void set_value(int i) { value_ = i; }
  3360. private:
  3361. int value_;
  3362. GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
  3363. };
  3364. // Returns true if and only if x.value() is positive.
  3365. bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
  3366. MATCHER_P(UncopyableIs, inner_matcher, "") {
  3367. return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
  3368. }
  3369. // A user-defined struct for testing Field().
  3370. struct AStruct {
  3371. AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
  3372. AStruct(const AStruct& rhs)
  3373. : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
  3374. int x; // A non-const field.
  3375. const double y; // A const field.
  3376. Uncopyable z; // An uncopyable field.
  3377. const char* p; // A pointer field.
  3378. };
  3379. // A derived struct for testing Field().
  3380. struct DerivedStruct : public AStruct {
  3381. char ch;
  3382. };
  3383. // Tests that Field(&Foo::field, ...) works when field is non-const.
  3384. TEST(FieldTest, WorksForNonConstField) {
  3385. Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
  3386. Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
  3387. AStruct a;
  3388. EXPECT_TRUE(m.Matches(a));
  3389. EXPECT_TRUE(m_with_name.Matches(a));
  3390. a.x = -1;
  3391. EXPECT_FALSE(m.Matches(a));
  3392. EXPECT_FALSE(m_with_name.Matches(a));
  3393. }
  3394. // Tests that Field(&Foo::field, ...) works when field is const.
  3395. TEST(FieldTest, WorksForConstField) {
  3396. AStruct a;
  3397. Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
  3398. Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
  3399. EXPECT_TRUE(m.Matches(a));
  3400. EXPECT_TRUE(m_with_name.Matches(a));
  3401. m = Field(&AStruct::y, Le(0.0));
  3402. m_with_name = Field("y", &AStruct::y, Le(0.0));
  3403. EXPECT_FALSE(m.Matches(a));
  3404. EXPECT_FALSE(m_with_name.Matches(a));
  3405. }
  3406. // Tests that Field(&Foo::field, ...) works when field is not copyable.
  3407. TEST(FieldTest, WorksForUncopyableField) {
  3408. AStruct a;
  3409. Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
  3410. EXPECT_TRUE(m.Matches(a));
  3411. m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
  3412. EXPECT_FALSE(m.Matches(a));
  3413. }
  3414. // Tests that Field(&Foo::field, ...) works when field is a pointer.
  3415. TEST(FieldTest, WorksForPointerField) {
  3416. // Matching against NULL.
  3417. Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
  3418. AStruct a;
  3419. EXPECT_TRUE(m.Matches(a));
  3420. a.p = "hi";
  3421. EXPECT_FALSE(m.Matches(a));
  3422. // Matching a pointer that is not NULL.
  3423. m = Field(&AStruct::p, StartsWith("hi"));
  3424. a.p = "hill";
  3425. EXPECT_TRUE(m.Matches(a));
  3426. a.p = "hole";
  3427. EXPECT_FALSE(m.Matches(a));
  3428. }
  3429. // Tests that Field() works when the object is passed by reference.
  3430. TEST(FieldTest, WorksForByRefArgument) {
  3431. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  3432. AStruct a;
  3433. EXPECT_TRUE(m.Matches(a));
  3434. a.x = -1;
  3435. EXPECT_FALSE(m.Matches(a));
  3436. }
  3437. // Tests that Field(&Foo::field, ...) works when the argument's type
  3438. // is a sub-type of Foo.
  3439. TEST(FieldTest, WorksForArgumentOfSubType) {
  3440. // Note that the matcher expects DerivedStruct but we say AStruct
  3441. // inside Field().
  3442. Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
  3443. DerivedStruct d;
  3444. EXPECT_TRUE(m.Matches(d));
  3445. d.x = -1;
  3446. EXPECT_FALSE(m.Matches(d));
  3447. }
  3448. // Tests that Field(&Foo::field, m) works when field's type and m's
  3449. // argument type are compatible but not the same.
  3450. TEST(FieldTest, WorksForCompatibleMatcherType) {
  3451. // The field is an int, but the inner matcher expects a signed char.
  3452. Matcher<const AStruct&> m = Field(&AStruct::x,
  3453. Matcher<signed char>(Ge(0)));
  3454. AStruct a;
  3455. EXPECT_TRUE(m.Matches(a));
  3456. a.x = -1;
  3457. EXPECT_FALSE(m.Matches(a));
  3458. }
  3459. // Tests that Field() can describe itself.
  3460. TEST(FieldTest, CanDescribeSelf) {
  3461. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  3462. EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
  3463. EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
  3464. }
  3465. TEST(FieldTest, CanDescribeSelfWithFieldName) {
  3466. Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
  3467. EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
  3468. EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
  3469. DescribeNegation(m));
  3470. }
  3471. // Tests that Field() can explain the match result.
  3472. TEST(FieldTest, CanExplainMatchResult) {
  3473. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  3474. AStruct a;
  3475. a.x = 1;
  3476. EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
  3477. m = Field(&AStruct::x, GreaterThan(0));
  3478. EXPECT_EQ(
  3479. "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
  3480. Explain(m, a));
  3481. }
  3482. TEST(FieldTest, CanExplainMatchResultWithFieldName) {
  3483. Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
  3484. AStruct a;
  3485. a.x = 1;
  3486. EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
  3487. m = Field("field_name", &AStruct::x, GreaterThan(0));
  3488. EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
  3489. ", which is 1 more than 0",
  3490. Explain(m, a));
  3491. }
  3492. // Tests that Field() works when the argument is a pointer to const.
  3493. TEST(FieldForPointerTest, WorksForPointerToConst) {
  3494. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  3495. AStruct a;
  3496. EXPECT_TRUE(m.Matches(&a));
  3497. a.x = -1;
  3498. EXPECT_FALSE(m.Matches(&a));
  3499. }
  3500. // Tests that Field() works when the argument is a pointer to non-const.
  3501. TEST(FieldForPointerTest, WorksForPointerToNonConst) {
  3502. Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
  3503. AStruct a;
  3504. EXPECT_TRUE(m.Matches(&a));
  3505. a.x = -1;
  3506. EXPECT_FALSE(m.Matches(&a));
  3507. }
  3508. // Tests that Field() works when the argument is a reference to a const pointer.
  3509. TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
  3510. Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
  3511. AStruct a;
  3512. EXPECT_TRUE(m.Matches(&a));
  3513. a.x = -1;
  3514. EXPECT_FALSE(m.Matches(&a));
  3515. }
  3516. // Tests that Field() does not match the NULL pointer.
  3517. TEST(FieldForPointerTest, DoesNotMatchNull) {
  3518. Matcher<const AStruct*> m = Field(&AStruct::x, _);
  3519. EXPECT_FALSE(m.Matches(nullptr));
  3520. }
  3521. // Tests that Field(&Foo::field, ...) works when the argument's type
  3522. // is a sub-type of const Foo*.
  3523. TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
  3524. // Note that the matcher expects DerivedStruct but we say AStruct
  3525. // inside Field().
  3526. Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
  3527. DerivedStruct d;
  3528. EXPECT_TRUE(m.Matches(&d));
  3529. d.x = -1;
  3530. EXPECT_FALSE(m.Matches(&d));
  3531. }
  3532. // Tests that Field() can describe itself when used to match a pointer.
  3533. TEST(FieldForPointerTest, CanDescribeSelf) {
  3534. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  3535. EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
  3536. EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
  3537. }
  3538. TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
  3539. Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
  3540. EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
  3541. EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
  3542. DescribeNegation(m));
  3543. }
  3544. // Tests that Field() can explain the result of matching a pointer.
  3545. TEST(FieldForPointerTest, CanExplainMatchResult) {
  3546. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  3547. AStruct a;
  3548. a.x = 1;
  3549. EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
  3550. EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
  3551. Explain(m, &a));
  3552. m = Field(&AStruct::x, GreaterThan(0));
  3553. EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
  3554. ", which is 1 more than 0", Explain(m, &a));
  3555. }
  3556. TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) {
  3557. Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
  3558. AStruct a;
  3559. a.x = 1;
  3560. EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
  3561. EXPECT_EQ(
  3562. "which points to an object whose field `field_name` is 1" + OfType("int"),
  3563. Explain(m, &a));
  3564. m = Field("field_name", &AStruct::x, GreaterThan(0));
  3565. EXPECT_EQ("which points to an object whose field `field_name` is 1" +
  3566. OfType("int") + ", which is 1 more than 0",
  3567. Explain(m, &a));
  3568. }
  3569. // A user-defined class for testing Property().
  3570. class AClass {
  3571. public:
  3572. AClass() : n_(0) {}
  3573. // A getter that returns a non-reference.
  3574. int n() const { return n_; }
  3575. void set_n(int new_n) { n_ = new_n; }
  3576. // A getter that returns a reference to const.
  3577. const std::string& s() const { return s_; }
  3578. const std::string& s_ref() const & { return s_; }
  3579. void set_s(const std::string& new_s) { s_ = new_s; }
  3580. // A getter that returns a reference to non-const.
  3581. double& x() const { return x_; }
  3582. private:
  3583. int n_;
  3584. std::string s_;
  3585. static double x_;
  3586. };
  3587. double AClass::x_ = 0.0;
  3588. // A derived class for testing Property().
  3589. class DerivedClass : public AClass {
  3590. public:
  3591. int k() const { return k_; }
  3592. private:
  3593. int k_;
  3594. };
  3595. // Tests that Property(&Foo::property, ...) works when property()
  3596. // returns a non-reference.
  3597. TEST(PropertyTest, WorksForNonReferenceProperty) {
  3598. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  3599. Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
  3600. AClass a;
  3601. a.set_n(1);
  3602. EXPECT_TRUE(m.Matches(a));
  3603. EXPECT_TRUE(m_with_name.Matches(a));
  3604. a.set_n(-1);
  3605. EXPECT_FALSE(m.Matches(a));
  3606. EXPECT_FALSE(m_with_name.Matches(a));
  3607. }
  3608. // Tests that Property(&Foo::property, ...) works when property()
  3609. // returns a reference to const.
  3610. TEST(PropertyTest, WorksForReferenceToConstProperty) {
  3611. Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
  3612. Matcher<const AClass&> m_with_name =
  3613. Property("s", &AClass::s, StartsWith("hi"));
  3614. AClass a;
  3615. a.set_s("hill");
  3616. EXPECT_TRUE(m.Matches(a));
  3617. EXPECT_TRUE(m_with_name.Matches(a));
  3618. a.set_s("hole");
  3619. EXPECT_FALSE(m.Matches(a));
  3620. EXPECT_FALSE(m_with_name.Matches(a));
  3621. }
  3622. // Tests that Property(&Foo::property, ...) works when property() is
  3623. // ref-qualified.
  3624. TEST(PropertyTest, WorksForRefQualifiedProperty) {
  3625. Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
  3626. Matcher<const AClass&> m_with_name =
  3627. Property("s", &AClass::s_ref, StartsWith("hi"));
  3628. AClass a;
  3629. a.set_s("hill");
  3630. EXPECT_TRUE(m.Matches(a));
  3631. EXPECT_TRUE(m_with_name.Matches(a));
  3632. a.set_s("hole");
  3633. EXPECT_FALSE(m.Matches(a));
  3634. EXPECT_FALSE(m_with_name.Matches(a));
  3635. }
  3636. // Tests that Property(&Foo::property, ...) works when property()
  3637. // returns a reference to non-const.
  3638. TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
  3639. double x = 0.0;
  3640. AClass a;
  3641. Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
  3642. EXPECT_FALSE(m.Matches(a));
  3643. m = Property(&AClass::x, Not(Ref(x)));
  3644. EXPECT_TRUE(m.Matches(a));
  3645. }
  3646. // Tests that Property(&Foo::property, ...) works when the argument is
  3647. // passed by value.
  3648. TEST(PropertyTest, WorksForByValueArgument) {
  3649. Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
  3650. AClass a;
  3651. a.set_s("hill");
  3652. EXPECT_TRUE(m.Matches(a));
  3653. a.set_s("hole");
  3654. EXPECT_FALSE(m.Matches(a));
  3655. }
  3656. // Tests that Property(&Foo::property, ...) works when the argument's
  3657. // type is a sub-type of Foo.
  3658. TEST(PropertyTest, WorksForArgumentOfSubType) {
  3659. // The matcher expects a DerivedClass, but inside the Property() we
  3660. // say AClass.
  3661. Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
  3662. DerivedClass d;
  3663. d.set_n(1);
  3664. EXPECT_TRUE(m.Matches(d));
  3665. d.set_n(-1);
  3666. EXPECT_FALSE(m.Matches(d));
  3667. }
  3668. // Tests that Property(&Foo::property, m) works when property()'s type
  3669. // and m's argument type are compatible but different.
  3670. TEST(PropertyTest, WorksForCompatibleMatcherType) {
  3671. // n() returns an int but the inner matcher expects a signed char.
  3672. Matcher<const AClass&> m = Property(&AClass::n,
  3673. Matcher<signed char>(Ge(0)));
  3674. Matcher<const AClass&> m_with_name =
  3675. Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
  3676. AClass a;
  3677. EXPECT_TRUE(m.Matches(a));
  3678. EXPECT_TRUE(m_with_name.Matches(a));
  3679. a.set_n(-1);
  3680. EXPECT_FALSE(m.Matches(a));
  3681. EXPECT_FALSE(m_with_name.Matches(a));
  3682. }
  3683. // Tests that Property() can describe itself.
  3684. TEST(PropertyTest, CanDescribeSelf) {
  3685. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  3686. EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
  3687. EXPECT_EQ("is an object whose given property isn't >= 0",
  3688. DescribeNegation(m));
  3689. }
  3690. TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
  3691. Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
  3692. EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
  3693. EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
  3694. DescribeNegation(m));
  3695. }
  3696. // Tests that Property() can explain the match result.
  3697. TEST(PropertyTest, CanExplainMatchResult) {
  3698. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  3699. AClass a;
  3700. a.set_n(1);
  3701. EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
  3702. m = Property(&AClass::n, GreaterThan(0));
  3703. EXPECT_EQ(
  3704. "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
  3705. Explain(m, a));
  3706. }
  3707. TEST(PropertyTest, CanExplainMatchResultWithPropertyName) {
  3708. Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
  3709. AClass a;
  3710. a.set_n(1);
  3711. EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
  3712. m = Property("fancy_name", &AClass::n, GreaterThan(0));
  3713. EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
  3714. ", which is 1 more than 0",
  3715. Explain(m, a));
  3716. }
  3717. // Tests that Property() works when the argument is a pointer to const.
  3718. TEST(PropertyForPointerTest, WorksForPointerToConst) {
  3719. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  3720. AClass a;
  3721. a.set_n(1);
  3722. EXPECT_TRUE(m.Matches(&a));
  3723. a.set_n(-1);
  3724. EXPECT_FALSE(m.Matches(&a));
  3725. }
  3726. // Tests that Property() works when the argument is a pointer to non-const.
  3727. TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
  3728. Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
  3729. AClass a;
  3730. a.set_s("hill");
  3731. EXPECT_TRUE(m.Matches(&a));
  3732. a.set_s("hole");
  3733. EXPECT_FALSE(m.Matches(&a));
  3734. }
  3735. // Tests that Property() works when the argument is a reference to a
  3736. // const pointer.
  3737. TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
  3738. Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
  3739. AClass a;
  3740. a.set_s("hill");
  3741. EXPECT_TRUE(m.Matches(&a));
  3742. a.set_s("hole");
  3743. EXPECT_FALSE(m.Matches(&a));
  3744. }
  3745. // Tests that Property() does not match the NULL pointer.
  3746. TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
  3747. Matcher<const AClass*> m = Property(&AClass::x, _);
  3748. EXPECT_FALSE(m.Matches(nullptr));
  3749. }
  3750. // Tests that Property(&Foo::property, ...) works when the argument's
  3751. // type is a sub-type of const Foo*.
  3752. TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
  3753. // The matcher expects a DerivedClass, but inside the Property() we
  3754. // say AClass.
  3755. Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
  3756. DerivedClass d;
  3757. d.set_n(1);
  3758. EXPECT_TRUE(m.Matches(&d));
  3759. d.set_n(-1);
  3760. EXPECT_FALSE(m.Matches(&d));
  3761. }
  3762. // Tests that Property() can describe itself when used to match a pointer.
  3763. TEST(PropertyForPointerTest, CanDescribeSelf) {
  3764. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  3765. EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
  3766. EXPECT_EQ("is an object whose given property isn't >= 0",
  3767. DescribeNegation(m));
  3768. }
  3769. TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
  3770. Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
  3771. EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
  3772. EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
  3773. DescribeNegation(m));
  3774. }
  3775. // Tests that Property() can explain the result of matching a pointer.
  3776. TEST(PropertyForPointerTest, CanExplainMatchResult) {
  3777. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  3778. AClass a;
  3779. a.set_n(1);
  3780. EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
  3781. EXPECT_EQ(
  3782. "which points to an object whose given property is 1" + OfType("int"),
  3783. Explain(m, &a));
  3784. m = Property(&AClass::n, GreaterThan(0));
  3785. EXPECT_EQ("which points to an object whose given property is 1" +
  3786. OfType("int") + ", which is 1 more than 0",
  3787. Explain(m, &a));
  3788. }
  3789. TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) {
  3790. Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
  3791. AClass a;
  3792. a.set_n(1);
  3793. EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
  3794. EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
  3795. OfType("int"),
  3796. Explain(m, &a));
  3797. m = Property("fancy_name", &AClass::n, GreaterThan(0));
  3798. EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
  3799. OfType("int") + ", which is 1 more than 0",
  3800. Explain(m, &a));
  3801. }
  3802. // Tests ResultOf.
  3803. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3804. // function pointer.
  3805. std::string IntToStringFunction(int input) {
  3806. return input == 1 ? "foo" : "bar";
  3807. }
  3808. TEST(ResultOfTest, WorksForFunctionPointers) {
  3809. Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
  3810. EXPECT_TRUE(matcher.Matches(1));
  3811. EXPECT_FALSE(matcher.Matches(2));
  3812. }
  3813. // Tests that ResultOf() can describe itself.
  3814. TEST(ResultOfTest, CanDescribeItself) {
  3815. Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
  3816. EXPECT_EQ("is mapped by the given callable to a value that "
  3817. "is equal to \"foo\"", Describe(matcher));
  3818. EXPECT_EQ("is mapped by the given callable to a value that "
  3819. "isn't equal to \"foo\"", DescribeNegation(matcher));
  3820. }
  3821. // Tests that ResultOf() can explain the match result.
  3822. int IntFunction(int input) { return input == 42 ? 80 : 90; }
  3823. TEST(ResultOfTest, CanExplainMatchResult) {
  3824. Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
  3825. EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
  3826. Explain(matcher, 36));
  3827. matcher = ResultOf(&IntFunction, GreaterThan(85));
  3828. EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
  3829. ", which is 5 more than 85", Explain(matcher, 36));
  3830. }
  3831. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  3832. // returns a non-reference.
  3833. TEST(ResultOfTest, WorksForNonReferenceResults) {
  3834. Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
  3835. EXPECT_TRUE(matcher.Matches(42));
  3836. EXPECT_FALSE(matcher.Matches(36));
  3837. }
  3838. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  3839. // returns a reference to non-const.
  3840. double& DoubleFunction(double& input) { return input; } // NOLINT
  3841. Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
  3842. return obj;
  3843. }
  3844. TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
  3845. double x = 3.14;
  3846. double x2 = x;
  3847. Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
  3848. EXPECT_TRUE(matcher.Matches(x));
  3849. EXPECT_FALSE(matcher.Matches(x2));
  3850. // Test that ResultOf works with uncopyable objects
  3851. Uncopyable obj(0);
  3852. Uncopyable obj2(0);
  3853. Matcher<Uncopyable&> matcher2 =
  3854. ResultOf(&RefUncopyableFunction, Ref(obj));
  3855. EXPECT_TRUE(matcher2.Matches(obj));
  3856. EXPECT_FALSE(matcher2.Matches(obj2));
  3857. }
  3858. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  3859. // returns a reference to const.
  3860. const std::string& StringFunction(const std::string& input) { return input; }
  3861. TEST(ResultOfTest, WorksForReferenceToConstResults) {
  3862. std::string s = "foo";
  3863. std::string s2 = s;
  3864. Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
  3865. EXPECT_TRUE(matcher.Matches(s));
  3866. EXPECT_FALSE(matcher.Matches(s2));
  3867. }
  3868. // Tests that ResultOf(f, m) works when f(x) and m's
  3869. // argument types are compatible but different.
  3870. TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
  3871. // IntFunction() returns int but the inner matcher expects a signed char.
  3872. Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
  3873. EXPECT_TRUE(matcher.Matches(36));
  3874. EXPECT_FALSE(matcher.Matches(42));
  3875. }
  3876. // Tests that the program aborts when ResultOf is passed
  3877. // a NULL function pointer.
  3878. TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
  3879. EXPECT_DEATH_IF_SUPPORTED(
  3880. ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
  3881. Eq(std::string("foo"))),
  3882. "NULL function pointer is passed into ResultOf\\(\\)\\.");
  3883. }
  3884. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3885. // function reference.
  3886. TEST(ResultOfTest, WorksForFunctionReferences) {
  3887. Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
  3888. EXPECT_TRUE(matcher.Matches(1));
  3889. EXPECT_FALSE(matcher.Matches(2));
  3890. }
  3891. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3892. // function object.
  3893. struct Functor {
  3894. std::string operator()(int input) const {
  3895. return IntToStringFunction(input);
  3896. }
  3897. };
  3898. TEST(ResultOfTest, WorksForFunctors) {
  3899. Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
  3900. EXPECT_TRUE(matcher.Matches(1));
  3901. EXPECT_FALSE(matcher.Matches(2));
  3902. }
  3903. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3904. // functor with more than one operator() defined. ResultOf() must work
  3905. // for each defined operator().
  3906. struct PolymorphicFunctor {
  3907. typedef int result_type;
  3908. int operator()(int n) { return n; }
  3909. int operator()(const char* s) { return static_cast<int>(strlen(s)); }
  3910. std::string operator()(int *p) { return p ? "good ptr" : "null"; }
  3911. };
  3912. TEST(ResultOfTest, WorksForPolymorphicFunctors) {
  3913. Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
  3914. EXPECT_TRUE(matcher_int.Matches(10));
  3915. EXPECT_FALSE(matcher_int.Matches(2));
  3916. Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
  3917. EXPECT_TRUE(matcher_string.Matches("long string"));
  3918. EXPECT_FALSE(matcher_string.Matches("shrt"));
  3919. }
  3920. TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
  3921. Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
  3922. int n = 0;
  3923. EXPECT_TRUE(matcher.Matches(&n));
  3924. EXPECT_FALSE(matcher.Matches(nullptr));
  3925. }
  3926. TEST(ResultOfTest, WorksForLambdas) {
  3927. Matcher<int> matcher = ResultOf(
  3928. [](int str_len) {
  3929. return std::string(static_cast<size_t>(str_len), 'x');
  3930. },
  3931. "xxx");
  3932. EXPECT_TRUE(matcher.Matches(3));
  3933. EXPECT_FALSE(matcher.Matches(1));
  3934. }
  3935. TEST(ResultOfTest, WorksForNonCopyableArguments) {
  3936. Matcher<std::unique_ptr<int>> matcher = ResultOf(
  3937. [](const std::unique_ptr<int>& str_len) {
  3938. return std::string(static_cast<size_t>(*str_len), 'x');
  3939. },
  3940. "xxx");
  3941. EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
  3942. EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
  3943. }
  3944. const int* ReferencingFunction(const int& n) { return &n; }
  3945. struct ReferencingFunctor {
  3946. typedef const int* result_type;
  3947. result_type operator()(const int& n) { return &n; }
  3948. };
  3949. TEST(ResultOfTest, WorksForReferencingCallables) {
  3950. const int n = 1;
  3951. const int n2 = 1;
  3952. Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
  3953. EXPECT_TRUE(matcher2.Matches(n));
  3954. EXPECT_FALSE(matcher2.Matches(n2));
  3955. Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
  3956. EXPECT_TRUE(matcher3.Matches(n));
  3957. EXPECT_FALSE(matcher3.Matches(n2));
  3958. }
  3959. class DivisibleByImpl {
  3960. public:
  3961. explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
  3962. // For testing using ExplainMatchResultTo() with polymorphic matchers.
  3963. template <typename T>
  3964. bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
  3965. *listener << "which is " << (n % divider_) << " modulo "
  3966. << divider_;
  3967. return (n % divider_) == 0;
  3968. }
  3969. void DescribeTo(ostream* os) const {
  3970. *os << "is divisible by " << divider_;
  3971. }
  3972. void DescribeNegationTo(ostream* os) const {
  3973. *os << "is not divisible by " << divider_;
  3974. }
  3975. void set_divider(int a_divider) { divider_ = a_divider; }
  3976. int divider() const { return divider_; }
  3977. private:
  3978. int divider_;
  3979. };
  3980. PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
  3981. return MakePolymorphicMatcher(DivisibleByImpl(n));
  3982. }
  3983. // Tests that when AllOf() fails, only the first failing matcher is
  3984. // asked to explain why.
  3985. TEST(ExplainMatchResultTest, AllOf_False_False) {
  3986. const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
  3987. EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
  3988. }
  3989. // Tests that when AllOf() fails, only the first failing matcher is
  3990. // asked to explain why.
  3991. TEST(ExplainMatchResultTest, AllOf_False_True) {
  3992. const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
  3993. EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
  3994. }
  3995. // Tests that when AllOf() fails, only the first failing matcher is
  3996. // asked to explain why.
  3997. TEST(ExplainMatchResultTest, AllOf_True_False) {
  3998. const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
  3999. EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
  4000. }
  4001. // Tests that when AllOf() succeeds, all matchers are asked to explain
  4002. // why.
  4003. TEST(ExplainMatchResultTest, AllOf_True_True) {
  4004. const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
  4005. EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
  4006. }
  4007. TEST(ExplainMatchResultTest, AllOf_True_True_2) {
  4008. const Matcher<int> m = AllOf(Ge(2), Le(3));
  4009. EXPECT_EQ("", Explain(m, 2));
  4010. }
  4011. TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
  4012. const Matcher<int> m = GreaterThan(5);
  4013. EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
  4014. }
  4015. // The following two tests verify that values without a public copy
  4016. // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
  4017. // with the help of ByRef().
  4018. class NotCopyable {
  4019. public:
  4020. explicit NotCopyable(int a_value) : value_(a_value) {}
  4021. int value() const { return value_; }
  4022. bool operator==(const NotCopyable& rhs) const {
  4023. return value() == rhs.value();
  4024. }
  4025. bool operator>=(const NotCopyable& rhs) const {
  4026. return value() >= rhs.value();
  4027. }
  4028. private:
  4029. int value_;
  4030. GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
  4031. };
  4032. TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
  4033. const NotCopyable const_value1(1);
  4034. const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
  4035. const NotCopyable n1(1), n2(2);
  4036. EXPECT_TRUE(m.Matches(n1));
  4037. EXPECT_FALSE(m.Matches(n2));
  4038. }
  4039. TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
  4040. NotCopyable value2(2);
  4041. const Matcher<NotCopyable&> m = Ge(ByRef(value2));
  4042. NotCopyable n1(1), n2(2);
  4043. EXPECT_FALSE(m.Matches(n1));
  4044. EXPECT_TRUE(m.Matches(n2));
  4045. }
  4046. TEST(IsEmptyTest, ImplementsIsEmpty) {
  4047. vector<int> container;
  4048. EXPECT_THAT(container, IsEmpty());
  4049. container.push_back(0);
  4050. EXPECT_THAT(container, Not(IsEmpty()));
  4051. container.push_back(1);
  4052. EXPECT_THAT(container, Not(IsEmpty()));
  4053. }
  4054. TEST(IsEmptyTest, WorksWithString) {
  4055. std::string text;
  4056. EXPECT_THAT(text, IsEmpty());
  4057. text = "foo";
  4058. EXPECT_THAT(text, Not(IsEmpty()));
  4059. text = std::string("\0", 1);
  4060. EXPECT_THAT(text, Not(IsEmpty()));
  4061. }
  4062. TEST(IsEmptyTest, CanDescribeSelf) {
  4063. Matcher<vector<int> > m = IsEmpty();
  4064. EXPECT_EQ("is empty", Describe(m));
  4065. EXPECT_EQ("isn't empty", DescribeNegation(m));
  4066. }
  4067. TEST(IsEmptyTest, ExplainsResult) {
  4068. Matcher<vector<int> > m = IsEmpty();
  4069. vector<int> container;
  4070. EXPECT_EQ("", Explain(m, container));
  4071. container.push_back(0);
  4072. EXPECT_EQ("whose size is 1", Explain(m, container));
  4073. }
  4074. TEST(IsEmptyTest, WorksWithMoveOnly) {
  4075. ContainerHelper helper;
  4076. EXPECT_CALL(helper, Call(IsEmpty()));
  4077. helper.Call({});
  4078. }
  4079. TEST(IsTrueTest, IsTrueIsFalse) {
  4080. EXPECT_THAT(true, IsTrue());
  4081. EXPECT_THAT(false, IsFalse());
  4082. EXPECT_THAT(true, Not(IsFalse()));
  4083. EXPECT_THAT(false, Not(IsTrue()));
  4084. EXPECT_THAT(0, Not(IsTrue()));
  4085. EXPECT_THAT(0, IsFalse());
  4086. EXPECT_THAT(nullptr, Not(IsTrue()));
  4087. EXPECT_THAT(nullptr, IsFalse());
  4088. EXPECT_THAT(-1, IsTrue());
  4089. EXPECT_THAT(-1, Not(IsFalse()));
  4090. EXPECT_THAT(1, IsTrue());
  4091. EXPECT_THAT(1, Not(IsFalse()));
  4092. EXPECT_THAT(2, IsTrue());
  4093. EXPECT_THAT(2, Not(IsFalse()));
  4094. int a = 42;
  4095. EXPECT_THAT(a, IsTrue());
  4096. EXPECT_THAT(a, Not(IsFalse()));
  4097. EXPECT_THAT(&a, IsTrue());
  4098. EXPECT_THAT(&a, Not(IsFalse()));
  4099. EXPECT_THAT(false, Not(IsTrue()));
  4100. EXPECT_THAT(true, Not(IsFalse()));
  4101. EXPECT_THAT(std::true_type(), IsTrue());
  4102. EXPECT_THAT(std::true_type(), Not(IsFalse()));
  4103. EXPECT_THAT(std::false_type(), IsFalse());
  4104. EXPECT_THAT(std::false_type(), Not(IsTrue()));
  4105. EXPECT_THAT(nullptr, Not(IsTrue()));
  4106. EXPECT_THAT(nullptr, IsFalse());
  4107. std::unique_ptr<int> null_unique;
  4108. std::unique_ptr<int> nonnull_unique(new int(0));
  4109. EXPECT_THAT(null_unique, Not(IsTrue()));
  4110. EXPECT_THAT(null_unique, IsFalse());
  4111. EXPECT_THAT(nonnull_unique, IsTrue());
  4112. EXPECT_THAT(nonnull_unique, Not(IsFalse()));
  4113. }
  4114. TEST(SizeIsTest, ImplementsSizeIs) {
  4115. vector<int> container;
  4116. EXPECT_THAT(container, SizeIs(0));
  4117. EXPECT_THAT(container, Not(SizeIs(1)));
  4118. container.push_back(0);
  4119. EXPECT_THAT(container, Not(SizeIs(0)));
  4120. EXPECT_THAT(container, SizeIs(1));
  4121. container.push_back(0);
  4122. EXPECT_THAT(container, Not(SizeIs(0)));
  4123. EXPECT_THAT(container, SizeIs(2));
  4124. }
  4125. TEST(SizeIsTest, WorksWithMap) {
  4126. map<std::string, int> container;
  4127. EXPECT_THAT(container, SizeIs(0));
  4128. EXPECT_THAT(container, Not(SizeIs(1)));
  4129. container.insert(make_pair("foo", 1));
  4130. EXPECT_THAT(container, Not(SizeIs(0)));
  4131. EXPECT_THAT(container, SizeIs(1));
  4132. container.insert(make_pair("bar", 2));
  4133. EXPECT_THAT(container, Not(SizeIs(0)));
  4134. EXPECT_THAT(container, SizeIs(2));
  4135. }
  4136. TEST(SizeIsTest, WorksWithReferences) {
  4137. vector<int> container;
  4138. Matcher<const vector<int>&> m = SizeIs(1);
  4139. EXPECT_THAT(container, Not(m));
  4140. container.push_back(0);
  4141. EXPECT_THAT(container, m);
  4142. }
  4143. TEST(SizeIsTest, WorksWithMoveOnly) {
  4144. ContainerHelper helper;
  4145. EXPECT_CALL(helper, Call(SizeIs(3)));
  4146. helper.Call(MakeUniquePtrs({1, 2, 3}));
  4147. }
  4148. // SizeIs should work for any type that provides a size() member function.
  4149. // For example, a size_type member type should not need to be provided.
  4150. struct MinimalistCustomType {
  4151. int size() const { return 1; }
  4152. };
  4153. TEST(SizeIsTest, WorksWithMinimalistCustomType) {
  4154. MinimalistCustomType container;
  4155. EXPECT_THAT(container, SizeIs(1));
  4156. EXPECT_THAT(container, Not(SizeIs(0)));
  4157. }
  4158. TEST(SizeIsTest, CanDescribeSelf) {
  4159. Matcher<vector<int> > m = SizeIs(2);
  4160. EXPECT_EQ("size is equal to 2", Describe(m));
  4161. EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
  4162. }
  4163. TEST(SizeIsTest, ExplainsResult) {
  4164. Matcher<vector<int> > m1 = SizeIs(2);
  4165. Matcher<vector<int> > m2 = SizeIs(Lt(2u));
  4166. Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
  4167. Matcher<vector<int> > m4 = SizeIs(Gt(1u));
  4168. vector<int> container;
  4169. EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
  4170. EXPECT_EQ("whose size 0 matches", Explain(m2, container));
  4171. EXPECT_EQ("whose size 0 matches", Explain(m3, container));
  4172. EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
  4173. container.push_back(0);
  4174. container.push_back(0);
  4175. EXPECT_EQ("whose size 2 matches", Explain(m1, container));
  4176. EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
  4177. EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
  4178. EXPECT_EQ("whose size 2 matches", Explain(m4, container));
  4179. }
  4180. #if GTEST_HAS_TYPED_TEST
  4181. // Tests ContainerEq with different container types, and
  4182. // different element types.
  4183. template <typename T>
  4184. class ContainerEqTest : public testing::Test {};
  4185. typedef testing::Types<
  4186. set<int>,
  4187. vector<size_t>,
  4188. multiset<size_t>,
  4189. list<int> >
  4190. ContainerEqTestTypes;
  4191. TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);
  4192. // Tests that the filled container is equal to itself.
  4193. TYPED_TEST(ContainerEqTest, EqualsSelf) {
  4194. static const int vals[] = {1, 1, 2, 3, 5, 8};
  4195. TypeParam my_set(vals, vals + 6);
  4196. const Matcher<TypeParam> m = ContainerEq(my_set);
  4197. EXPECT_TRUE(m.Matches(my_set));
  4198. EXPECT_EQ("", Explain(m, my_set));
  4199. }
  4200. // Tests that missing values are reported.
  4201. TYPED_TEST(ContainerEqTest, ValueMissing) {
  4202. static const int vals[] = {1, 1, 2, 3, 5, 8};
  4203. static const int test_vals[] = {2, 1, 8, 5};
  4204. TypeParam my_set(vals, vals + 6);
  4205. TypeParam test_set(test_vals, test_vals + 4);
  4206. const Matcher<TypeParam> m = ContainerEq(my_set);
  4207. EXPECT_FALSE(m.Matches(test_set));
  4208. EXPECT_EQ("which doesn't have these expected elements: 3",
  4209. Explain(m, test_set));
  4210. }
  4211. // Tests that added values are reported.
  4212. TYPED_TEST(ContainerEqTest, ValueAdded) {
  4213. static const int vals[] = {1, 1, 2, 3, 5, 8};
  4214. static const int test_vals[] = {1, 2, 3, 5, 8, 46};
  4215. TypeParam my_set(vals, vals + 6);
  4216. TypeParam test_set(test_vals, test_vals + 6);
  4217. const Matcher<const TypeParam&> m = ContainerEq(my_set);
  4218. EXPECT_FALSE(m.Matches(test_set));
  4219. EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
  4220. }
  4221. // Tests that added and missing values are reported together.
  4222. TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
  4223. static const int vals[] = {1, 1, 2, 3, 5, 8};
  4224. static const int test_vals[] = {1, 2, 3, 8, 46};
  4225. TypeParam my_set(vals, vals + 6);
  4226. TypeParam test_set(test_vals, test_vals + 5);
  4227. const Matcher<TypeParam> m = ContainerEq(my_set);
  4228. EXPECT_FALSE(m.Matches(test_set));
  4229. EXPECT_EQ("which has these unexpected elements: 46,\n"
  4230. "and doesn't have these expected elements: 5",
  4231. Explain(m, test_set));
  4232. }
  4233. // Tests duplicated value -- expect no explanation.
  4234. TYPED_TEST(ContainerEqTest, DuplicateDifference) {
  4235. static const int vals[] = {1, 1, 2, 3, 5, 8};
  4236. static const int test_vals[] = {1, 2, 3, 5, 8};
  4237. TypeParam my_set(vals, vals + 6);
  4238. TypeParam test_set(test_vals, test_vals + 5);
  4239. const Matcher<const TypeParam&> m = ContainerEq(my_set);
  4240. // Depending on the container, match may be true or false
  4241. // But in any case there should be no explanation.
  4242. EXPECT_EQ("", Explain(m, test_set));
  4243. }
  4244. #endif // GTEST_HAS_TYPED_TEST
  4245. // Tests that multiple missing values are reported.
  4246. // Using just vector here, so order is predictable.
  4247. TEST(ContainerEqExtraTest, MultipleValuesMissing) {
  4248. static const int vals[] = {1, 1, 2, 3, 5, 8};
  4249. static const int test_vals[] = {2, 1, 5};
  4250. vector<int> my_set(vals, vals + 6);
  4251. vector<int> test_set(test_vals, test_vals + 3);
  4252. const Matcher<vector<int> > m = ContainerEq(my_set);
  4253. EXPECT_FALSE(m.Matches(test_set));
  4254. EXPECT_EQ("which doesn't have these expected elements: 3, 8",
  4255. Explain(m, test_set));
  4256. }
  4257. // Tests that added values are reported.
  4258. // Using just vector here, so order is predictable.
  4259. TEST(ContainerEqExtraTest, MultipleValuesAdded) {
  4260. static const int vals[] = {1, 1, 2, 3, 5, 8};
  4261. static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
  4262. list<size_t> my_set(vals, vals + 6);
  4263. list<size_t> test_set(test_vals, test_vals + 7);
  4264. const Matcher<const list<size_t>&> m = ContainerEq(my_set);
  4265. EXPECT_FALSE(m.Matches(test_set));
  4266. EXPECT_EQ("which has these unexpected elements: 92, 46",
  4267. Explain(m, test_set));
  4268. }
  4269. // Tests that added and missing values are reported together.
  4270. TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
  4271. static const int vals[] = {1, 1, 2, 3, 5, 8};
  4272. static const int test_vals[] = {1, 2, 3, 92, 46};
  4273. list<size_t> my_set(vals, vals + 6);
  4274. list<size_t> test_set(test_vals, test_vals + 5);
  4275. const Matcher<const list<size_t> > m = ContainerEq(my_set);
  4276. EXPECT_FALSE(m.Matches(test_set));
  4277. EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
  4278. "and doesn't have these expected elements: 5, 8",
  4279. Explain(m, test_set));
  4280. }
  4281. // Tests to see that duplicate elements are detected,
  4282. // but (as above) not reported in the explanation.
  4283. TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
  4284. static const int vals[] = {1, 1, 2, 3, 5, 8};
  4285. static const int test_vals[] = {1, 2, 3, 5, 8};
  4286. vector<int> my_set(vals, vals + 6);
  4287. vector<int> test_set(test_vals, test_vals + 5);
  4288. const Matcher<vector<int> > m = ContainerEq(my_set);
  4289. EXPECT_TRUE(m.Matches(my_set));
  4290. EXPECT_FALSE(m.Matches(test_set));
  4291. // There is nothing to report when both sets contain all the same values.
  4292. EXPECT_EQ("", Explain(m, test_set));
  4293. }
  4294. // Tests that ContainerEq works for non-trivial associative containers,
  4295. // like maps.
  4296. TEST(ContainerEqExtraTest, WorksForMaps) {
  4297. map<int, std::string> my_map;
  4298. my_map[0] = "a";
  4299. my_map[1] = "b";
  4300. map<int, std::string> test_map;
  4301. test_map[0] = "aa";
  4302. test_map[1] = "b";
  4303. const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
  4304. EXPECT_TRUE(m.Matches(my_map));
  4305. EXPECT_FALSE(m.Matches(test_map));
  4306. EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
  4307. "and doesn't have these expected elements: (0, \"a\")",
  4308. Explain(m, test_map));
  4309. }
  4310. TEST(ContainerEqExtraTest, WorksForNativeArray) {
  4311. int a1[] = {1, 2, 3};
  4312. int a2[] = {1, 2, 3};
  4313. int b[] = {1, 2, 4};
  4314. EXPECT_THAT(a1, ContainerEq(a2));
  4315. EXPECT_THAT(a1, Not(ContainerEq(b)));
  4316. }
  4317. TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
  4318. const char a1[][3] = {"hi", "lo"};
  4319. const char a2[][3] = {"hi", "lo"};
  4320. const char b[][3] = {"lo", "hi"};
  4321. // Tests using ContainerEq() in the first dimension.
  4322. EXPECT_THAT(a1, ContainerEq(a2));
  4323. EXPECT_THAT(a1, Not(ContainerEq(b)));
  4324. // Tests using ContainerEq() in the second dimension.
  4325. EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
  4326. EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
  4327. }
  4328. TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
  4329. const int a1[] = {1, 2, 3};
  4330. const int a2[] = {1, 2, 3};
  4331. const int b[] = {1, 2, 3, 4};
  4332. const int* const p1 = a1;
  4333. EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));
  4334. EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));
  4335. const int c[] = {1, 3, 2};
  4336. EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));
  4337. }
  4338. TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
  4339. std::string a1[][3] = {
  4340. {"hi", "hello", "ciao"},
  4341. {"bye", "see you", "ciao"}
  4342. };
  4343. std::string a2[][3] = {
  4344. {"hi", "hello", "ciao"},
  4345. {"bye", "see you", "ciao"}
  4346. };
  4347. const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
  4348. EXPECT_THAT(a1, m);
  4349. a2[0][0] = "ha";
  4350. EXPECT_THAT(a1, m);
  4351. }
  4352. TEST(WhenSortedByTest, WorksForEmptyContainer) {
  4353. const vector<int> numbers;
  4354. EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
  4355. EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
  4356. }
  4357. TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
  4358. vector<unsigned> numbers;
  4359. numbers.push_back(3);
  4360. numbers.push_back(1);
  4361. numbers.push_back(2);
  4362. numbers.push_back(2);
  4363. EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
  4364. ElementsAre(3, 2, 2, 1)));
  4365. EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
  4366. ElementsAre(1, 2, 2, 3))));
  4367. }
  4368. TEST(WhenSortedByTest, WorksForNonVectorContainer) {
  4369. list<std::string> words;
  4370. words.push_back("say");
  4371. words.push_back("hello");
  4372. words.push_back("world");
  4373. EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
  4374. ElementsAre("hello", "say", "world")));
  4375. EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
  4376. ElementsAre("say", "hello", "world"))));
  4377. }
  4378. TEST(WhenSortedByTest, WorksForNativeArray) {
  4379. const int numbers[] = {1, 3, 2, 4};
  4380. const int sorted_numbers[] = {1, 2, 3, 4};
  4381. EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
  4382. EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
  4383. ElementsAreArray(sorted_numbers)));
  4384. EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
  4385. }
  4386. TEST(WhenSortedByTest, CanDescribeSelf) {
  4387. const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
  4388. EXPECT_EQ("(when sorted) has 2 elements where\n"
  4389. "element #0 is equal to 1,\n"
  4390. "element #1 is equal to 2",
  4391. Describe(m));
  4392. EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
  4393. "element #0 isn't equal to 1, or\n"
  4394. "element #1 isn't equal to 2",
  4395. DescribeNegation(m));
  4396. }
  4397. TEST(WhenSortedByTest, ExplainsMatchResult) {
  4398. const int a[] = {2, 1};
  4399. EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
  4400. Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
  4401. EXPECT_EQ("which is { 1, 2 } when sorted",
  4402. Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
  4403. }
  4404. // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
  4405. // need to test it as exhaustively as we test the latter.
  4406. TEST(WhenSortedTest, WorksForEmptyContainer) {
  4407. const vector<int> numbers;
  4408. EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
  4409. EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
  4410. }
  4411. TEST(WhenSortedTest, WorksForNonEmptyContainer) {
  4412. list<std::string> words;
  4413. words.push_back("3");
  4414. words.push_back("1");
  4415. words.push_back("2");
  4416. words.push_back("2");
  4417. EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
  4418. EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
  4419. }
  4420. TEST(WhenSortedTest, WorksForMapTypes) {
  4421. map<std::string, int> word_counts;
  4422. word_counts["and"] = 1;
  4423. word_counts["the"] = 1;
  4424. word_counts["buffalo"] = 2;
  4425. EXPECT_THAT(word_counts,
  4426. WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
  4427. Pair("the", 1))));
  4428. EXPECT_THAT(word_counts,
  4429. Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
  4430. Pair("buffalo", 2)))));
  4431. }
  4432. TEST(WhenSortedTest, WorksForMultiMapTypes) {
  4433. multimap<int, int> ifib;
  4434. ifib.insert(make_pair(8, 6));
  4435. ifib.insert(make_pair(2, 3));
  4436. ifib.insert(make_pair(1, 1));
  4437. ifib.insert(make_pair(3, 4));
  4438. ifib.insert(make_pair(1, 2));
  4439. ifib.insert(make_pair(5, 5));
  4440. EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
  4441. Pair(1, 2),
  4442. Pair(2, 3),
  4443. Pair(3, 4),
  4444. Pair(5, 5),
  4445. Pair(8, 6))));
  4446. EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
  4447. Pair(2, 3),
  4448. Pair(1, 1),
  4449. Pair(3, 4),
  4450. Pair(1, 2),
  4451. Pair(5, 5)))));
  4452. }
  4453. TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
  4454. std::deque<int> d;
  4455. d.push_back(2);
  4456. d.push_back(1);
  4457. EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
  4458. EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
  4459. }
  4460. TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
  4461. std::deque<int> d;
  4462. d.push_back(2);
  4463. d.push_back(1);
  4464. Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
  4465. EXPECT_THAT(d, WhenSorted(vector_match));
  4466. Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
  4467. EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
  4468. }
  4469. // Deliberately bare pseudo-container.
  4470. // Offers only begin() and end() accessors, yielding InputIterator.
  4471. template <typename T>
  4472. class Streamlike {
  4473. private:
  4474. class ConstIter;
  4475. public:
  4476. typedef ConstIter const_iterator;
  4477. typedef T value_type;
  4478. template <typename InIter>
  4479. Streamlike(InIter first, InIter last) : remainder_(first, last) {}
  4480. const_iterator begin() const {
  4481. return const_iterator(this, remainder_.begin());
  4482. }
  4483. const_iterator end() const {
  4484. return const_iterator(this, remainder_.end());
  4485. }
  4486. private:
  4487. class ConstIter : public std::iterator<std::input_iterator_tag,
  4488. value_type,
  4489. ptrdiff_t,
  4490. const value_type*,
  4491. const value_type&> {
  4492. public:
  4493. ConstIter(const Streamlike* s,
  4494. typename std::list<value_type>::iterator pos)
  4495. : s_(s), pos_(pos) {}
  4496. const value_type& operator*() const { return *pos_; }
  4497. const value_type* operator->() const { return &*pos_; }
  4498. ConstIter& operator++() {
  4499. s_->remainder_.erase(pos_++);
  4500. return *this;
  4501. }
  4502. // *iter++ is required to work (see std::istreambuf_iterator).
  4503. // (void)iter++ is also required to work.
  4504. class PostIncrProxy {
  4505. public:
  4506. explicit PostIncrProxy(const value_type& value) : value_(value) {}
  4507. value_type operator*() const { return value_; }
  4508. private:
  4509. value_type value_;
  4510. };
  4511. PostIncrProxy operator++(int) {
  4512. PostIncrProxy proxy(**this);
  4513. ++(*this);
  4514. return proxy;
  4515. }
  4516. friend bool operator==(const ConstIter& a, const ConstIter& b) {
  4517. return a.s_ == b.s_ && a.pos_ == b.pos_;
  4518. }
  4519. friend bool operator!=(const ConstIter& a, const ConstIter& b) {
  4520. return !(a == b);
  4521. }
  4522. private:
  4523. const Streamlike* s_;
  4524. typename std::list<value_type>::iterator pos_;
  4525. };
  4526. friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
  4527. os << "[";
  4528. typedef typename std::list<value_type>::const_iterator Iter;
  4529. const char* sep = "";
  4530. for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
  4531. os << sep << *it;
  4532. sep = ",";
  4533. }
  4534. os << "]";
  4535. return os;
  4536. }
  4537. mutable std::list<value_type> remainder_; // modified by iteration
  4538. };
  4539. TEST(StreamlikeTest, Iteration) {
  4540. const int a[5] = {2, 1, 4, 5, 3};
  4541. Streamlike<int> s(a, a + 5);
  4542. Streamlike<int>::const_iterator it = s.begin();
  4543. const int* ip = a;
  4544. while (it != s.end()) {
  4545. SCOPED_TRACE(ip - a);
  4546. EXPECT_EQ(*ip++, *it++);
  4547. }
  4548. }
  4549. TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
  4550. std::forward_list<int> container;
  4551. EXPECT_THAT(container, BeginEndDistanceIs(0));
  4552. EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
  4553. container.push_front(0);
  4554. EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
  4555. EXPECT_THAT(container, BeginEndDistanceIs(1));
  4556. container.push_front(0);
  4557. EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
  4558. EXPECT_THAT(container, BeginEndDistanceIs(2));
  4559. }
  4560. TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
  4561. const int a[5] = {1, 2, 3, 4, 5};
  4562. Streamlike<int> s(a, a + 5);
  4563. EXPECT_THAT(s, BeginEndDistanceIs(5));
  4564. }
  4565. TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
  4566. Matcher<vector<int> > m = BeginEndDistanceIs(2);
  4567. EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
  4568. EXPECT_EQ("distance between begin() and end() isn't equal to 2",
  4569. DescribeNegation(m));
  4570. }
  4571. TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
  4572. ContainerHelper helper;
  4573. EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
  4574. helper.Call(MakeUniquePtrs({1, 2}));
  4575. }
  4576. TEST(BeginEndDistanceIsTest, ExplainsResult) {
  4577. Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
  4578. Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
  4579. Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
  4580. Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
  4581. vector<int> container;
  4582. EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
  4583. Explain(m1, container));
  4584. EXPECT_EQ("whose distance between begin() and end() 0 matches",
  4585. Explain(m2, container));
  4586. EXPECT_EQ("whose distance between begin() and end() 0 matches",
  4587. Explain(m3, container));
  4588. EXPECT_EQ(
  4589. "whose distance between begin() and end() 0 doesn't match, which is 1 "
  4590. "less than 1",
  4591. Explain(m4, container));
  4592. container.push_back(0);
  4593. container.push_back(0);
  4594. EXPECT_EQ("whose distance between begin() and end() 2 matches",
  4595. Explain(m1, container));
  4596. EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
  4597. Explain(m2, container));
  4598. EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
  4599. Explain(m3, container));
  4600. EXPECT_EQ(
  4601. "whose distance between begin() and end() 2 matches, which is 1 more "
  4602. "than 1",
  4603. Explain(m4, container));
  4604. }
  4605. TEST(WhenSortedTest, WorksForStreamlike) {
  4606. // Streamlike 'container' provides only minimal iterator support.
  4607. // Its iterators are tagged with input_iterator_tag.
  4608. const int a[5] = {2, 1, 4, 5, 3};
  4609. Streamlike<int> s(std::begin(a), std::end(a));
  4610. EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
  4611. EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
  4612. }
  4613. TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
  4614. const int a[] = {2, 1, 4, 5, 3};
  4615. Streamlike<int> s(std::begin(a), std::end(a));
  4616. Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
  4617. EXPECT_THAT(s, WhenSorted(vector_match));
  4618. EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
  4619. }
  4620. TEST(IsSupersetOfTest, WorksForNativeArray) {
  4621. const int subset[] = {1, 4};
  4622. const int superset[] = {1, 2, 4};
  4623. const int disjoint[] = {1, 0, 3};
  4624. EXPECT_THAT(subset, IsSupersetOf(subset));
  4625. EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
  4626. EXPECT_THAT(superset, IsSupersetOf(subset));
  4627. EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
  4628. EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
  4629. }
  4630. TEST(IsSupersetOfTest, WorksWithDuplicates) {
  4631. const int not_enough[] = {1, 2};
  4632. const int enough[] = {1, 1, 2};
  4633. const int expected[] = {1, 1};
  4634. EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
  4635. EXPECT_THAT(enough, IsSupersetOf(expected));
  4636. }
  4637. TEST(IsSupersetOfTest, WorksForEmpty) {
  4638. vector<int> numbers;
  4639. vector<int> expected;
  4640. EXPECT_THAT(numbers, IsSupersetOf(expected));
  4641. expected.push_back(1);
  4642. EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
  4643. expected.clear();
  4644. numbers.push_back(1);
  4645. numbers.push_back(2);
  4646. EXPECT_THAT(numbers, IsSupersetOf(expected));
  4647. expected.push_back(1);
  4648. EXPECT_THAT(numbers, IsSupersetOf(expected));
  4649. expected.push_back(2);
  4650. EXPECT_THAT(numbers, IsSupersetOf(expected));
  4651. expected.push_back(3);
  4652. EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
  4653. }
  4654. TEST(IsSupersetOfTest, WorksForStreamlike) {
  4655. const int a[5] = {1, 2, 3, 4, 5};
  4656. Streamlike<int> s(std::begin(a), std::end(a));
  4657. vector<int> expected;
  4658. expected.push_back(1);
  4659. expected.push_back(2);
  4660. expected.push_back(5);
  4661. EXPECT_THAT(s, IsSupersetOf(expected));
  4662. expected.push_back(0);
  4663. EXPECT_THAT(s, Not(IsSupersetOf(expected)));
  4664. }
  4665. TEST(IsSupersetOfTest, TakesStlContainer) {
  4666. const int actual[] = {3, 1, 2};
  4667. ::std::list<int> expected;
  4668. expected.push_back(1);
  4669. expected.push_back(3);
  4670. EXPECT_THAT(actual, IsSupersetOf(expected));
  4671. expected.push_back(4);
  4672. EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
  4673. }
  4674. TEST(IsSupersetOfTest, Describe) {
  4675. typedef std::vector<int> IntVec;
  4676. IntVec expected;
  4677. expected.push_back(111);
  4678. expected.push_back(222);
  4679. expected.push_back(333);
  4680. EXPECT_THAT(
  4681. Describe<IntVec>(IsSupersetOf(expected)),
  4682. Eq("a surjection from elements to requirements exists such that:\n"
  4683. " - an element is equal to 111\n"
  4684. " - an element is equal to 222\n"
  4685. " - an element is equal to 333"));
  4686. }
  4687. TEST(IsSupersetOfTest, DescribeNegation) {
  4688. typedef std::vector<int> IntVec;
  4689. IntVec expected;
  4690. expected.push_back(111);
  4691. expected.push_back(222);
  4692. expected.push_back(333);
  4693. EXPECT_THAT(
  4694. DescribeNegation<IntVec>(IsSupersetOf(expected)),
  4695. Eq("no surjection from elements to requirements exists such that:\n"
  4696. " - an element is equal to 111\n"
  4697. " - an element is equal to 222\n"
  4698. " - an element is equal to 333"));
  4699. }
  4700. TEST(IsSupersetOfTest, MatchAndExplain) {
  4701. std::vector<int> v;
  4702. v.push_back(2);
  4703. v.push_back(3);
  4704. std::vector<int> expected;
  4705. expected.push_back(1);
  4706. expected.push_back(2);
  4707. StringMatchResultListener listener;
  4708. ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
  4709. << listener.str();
  4710. EXPECT_THAT(listener.str(),
  4711. Eq("where the following matchers don't match any elements:\n"
  4712. "matcher #0: is equal to 1"));
  4713. v.push_back(1);
  4714. listener.Clear();
  4715. ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
  4716. << listener.str();
  4717. EXPECT_THAT(listener.str(), Eq("where:\n"
  4718. " - element #0 is matched by matcher #1,\n"
  4719. " - element #2 is matched by matcher #0"));
  4720. }
  4721. TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
  4722. const int numbers[] = {1, 3, 6, 2, 4, 5};
  4723. EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
  4724. EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
  4725. }
  4726. TEST(IsSupersetOfTest, WorksWithMoveOnly) {
  4727. ContainerHelper helper;
  4728. EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
  4729. helper.Call(MakeUniquePtrs({1, 2}));
  4730. EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
  4731. helper.Call(MakeUniquePtrs({2}));
  4732. }
  4733. TEST(IsSubsetOfTest, WorksForNativeArray) {
  4734. const int subset[] = {1, 4};
  4735. const int superset[] = {1, 2, 4};
  4736. const int disjoint[] = {1, 0, 3};
  4737. EXPECT_THAT(subset, IsSubsetOf(subset));
  4738. EXPECT_THAT(subset, IsSubsetOf(superset));
  4739. EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
  4740. EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
  4741. EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
  4742. }
  4743. TEST(IsSubsetOfTest, WorksWithDuplicates) {
  4744. const int not_enough[] = {1, 2};
  4745. const int enough[] = {1, 1, 2};
  4746. const int actual[] = {1, 1};
  4747. EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
  4748. EXPECT_THAT(actual, IsSubsetOf(enough));
  4749. }
  4750. TEST(IsSubsetOfTest, WorksForEmpty) {
  4751. vector<int> numbers;
  4752. vector<int> expected;
  4753. EXPECT_THAT(numbers, IsSubsetOf(expected));
  4754. expected.push_back(1);
  4755. EXPECT_THAT(numbers, IsSubsetOf(expected));
  4756. expected.clear();
  4757. numbers.push_back(1);
  4758. numbers.push_back(2);
  4759. EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
  4760. expected.push_back(1);
  4761. EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
  4762. expected.push_back(2);
  4763. EXPECT_THAT(numbers, IsSubsetOf(expected));
  4764. expected.push_back(3);
  4765. EXPECT_THAT(numbers, IsSubsetOf(expected));
  4766. }
  4767. TEST(IsSubsetOfTest, WorksForStreamlike) {
  4768. const int a[5] = {1, 2};
  4769. Streamlike<int> s(std::begin(a), std::end(a));
  4770. vector<int> expected;
  4771. expected.push_back(1);
  4772. EXPECT_THAT(s, Not(IsSubsetOf(expected)));
  4773. expected.push_back(2);
  4774. expected.push_back(5);
  4775. EXPECT_THAT(s, IsSubsetOf(expected));
  4776. }
  4777. TEST(IsSubsetOfTest, TakesStlContainer) {
  4778. const int actual[] = {3, 1, 2};
  4779. ::std::list<int> expected;
  4780. expected.push_back(1);
  4781. expected.push_back(3);
  4782. EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
  4783. expected.push_back(2);
  4784. expected.push_back(4);
  4785. EXPECT_THAT(actual, IsSubsetOf(expected));
  4786. }
  4787. TEST(IsSubsetOfTest, Describe) {
  4788. typedef std::vector<int> IntVec;
  4789. IntVec expected;
  4790. expected.push_back(111);
  4791. expected.push_back(222);
  4792. expected.push_back(333);
  4793. EXPECT_THAT(
  4794. Describe<IntVec>(IsSubsetOf(expected)),
  4795. Eq("an injection from elements to requirements exists such that:\n"
  4796. " - an element is equal to 111\n"
  4797. " - an element is equal to 222\n"
  4798. " - an element is equal to 333"));
  4799. }
  4800. TEST(IsSubsetOfTest, DescribeNegation) {
  4801. typedef std::vector<int> IntVec;
  4802. IntVec expected;
  4803. expected.push_back(111);
  4804. expected.push_back(222);
  4805. expected.push_back(333);
  4806. EXPECT_THAT(
  4807. DescribeNegation<IntVec>(IsSubsetOf(expected)),
  4808. Eq("no injection from elements to requirements exists such that:\n"
  4809. " - an element is equal to 111\n"
  4810. " - an element is equal to 222\n"
  4811. " - an element is equal to 333"));
  4812. }
  4813. TEST(IsSubsetOfTest, MatchAndExplain) {
  4814. std::vector<int> v;
  4815. v.push_back(2);
  4816. v.push_back(3);
  4817. std::vector<int> expected;
  4818. expected.push_back(1);
  4819. expected.push_back(2);
  4820. StringMatchResultListener listener;
  4821. ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
  4822. << listener.str();
  4823. EXPECT_THAT(listener.str(),
  4824. Eq("where the following elements don't match any matchers:\n"
  4825. "element #1: 3"));
  4826. expected.push_back(3);
  4827. listener.Clear();
  4828. ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
  4829. << listener.str();
  4830. EXPECT_THAT(listener.str(), Eq("where:\n"
  4831. " - element #0 is matched by matcher #1,\n"
  4832. " - element #1 is matched by matcher #2"));
  4833. }
  4834. TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
  4835. const int numbers[] = {1, 2, 3};
  4836. EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
  4837. EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
  4838. }
  4839. TEST(IsSubsetOfTest, WorksWithMoveOnly) {
  4840. ContainerHelper helper;
  4841. EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
  4842. helper.Call(MakeUniquePtrs({1}));
  4843. EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
  4844. helper.Call(MakeUniquePtrs({2}));
  4845. }
  4846. // Tests using ElementsAre() and ElementsAreArray() with stream-like
  4847. // "containers".
  4848. TEST(ElemensAreStreamTest, WorksForStreamlike) {
  4849. const int a[5] = {1, 2, 3, 4, 5};
  4850. Streamlike<int> s(std::begin(a), std::end(a));
  4851. EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
  4852. EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
  4853. }
  4854. TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
  4855. const int a[5] = {1, 2, 3, 4, 5};
  4856. Streamlike<int> s(std::begin(a), std::end(a));
  4857. vector<int> expected;
  4858. expected.push_back(1);
  4859. expected.push_back(2);
  4860. expected.push_back(3);
  4861. expected.push_back(4);
  4862. expected.push_back(5);
  4863. EXPECT_THAT(s, ElementsAreArray(expected));
  4864. expected[3] = 0;
  4865. EXPECT_THAT(s, Not(ElementsAreArray(expected)));
  4866. }
  4867. TEST(ElementsAreTest, WorksWithUncopyable) {
  4868. Uncopyable objs[2];
  4869. objs[0].set_value(-3);
  4870. objs[1].set_value(1);
  4871. EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
  4872. }
  4873. TEST(ElementsAreTest, WorksWithMoveOnly) {
  4874. ContainerHelper helper;
  4875. EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
  4876. helper.Call(MakeUniquePtrs({1, 2}));
  4877. EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
  4878. helper.Call(MakeUniquePtrs({3, 4}));
  4879. }
  4880. TEST(ElementsAreTest, TakesStlContainer) {
  4881. const int actual[] = {3, 1, 2};
  4882. ::std::list<int> expected;
  4883. expected.push_back(3);
  4884. expected.push_back(1);
  4885. expected.push_back(2);
  4886. EXPECT_THAT(actual, ElementsAreArray(expected));
  4887. expected.push_back(4);
  4888. EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
  4889. }
  4890. // Tests for UnorderedElementsAreArray()
  4891. TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
  4892. const int a[] = {0, 1, 2, 3, 4};
  4893. std::vector<int> s(std::begin(a), std::end(a));
  4894. do {
  4895. StringMatchResultListener listener;
  4896. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
  4897. s, &listener)) << listener.str();
  4898. } while (std::next_permutation(s.begin(), s.end()));
  4899. }
  4900. TEST(UnorderedElementsAreArrayTest, VectorBool) {
  4901. const bool a[] = {0, 1, 0, 1, 1};
  4902. const bool b[] = {1, 0, 1, 1, 0};
  4903. std::vector<bool> expected(std::begin(a), std::end(a));
  4904. std::vector<bool> actual(std::begin(b), std::end(b));
  4905. StringMatchResultListener listener;
  4906. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
  4907. actual, &listener)) << listener.str();
  4908. }
  4909. TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
  4910. // Streamlike 'container' provides only minimal iterator support.
  4911. // Its iterators are tagged with input_iterator_tag, and it has no
  4912. // size() or empty() methods.
  4913. const int a[5] = {2, 1, 4, 5, 3};
  4914. Streamlike<int> s(std::begin(a), std::end(a));
  4915. ::std::vector<int> expected;
  4916. expected.push_back(1);
  4917. expected.push_back(2);
  4918. expected.push_back(3);
  4919. expected.push_back(4);
  4920. expected.push_back(5);
  4921. EXPECT_THAT(s, UnorderedElementsAreArray(expected));
  4922. expected.push_back(6);
  4923. EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
  4924. }
  4925. TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
  4926. const int actual[] = {3, 1, 2};
  4927. ::std::list<int> expected;
  4928. expected.push_back(1);
  4929. expected.push_back(2);
  4930. expected.push_back(3);
  4931. EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
  4932. expected.push_back(4);
  4933. EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
  4934. }
  4935. TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
  4936. const int a[5] = {2, 1, 4, 5, 3};
  4937. EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
  4938. EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
  4939. }
  4940. TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
  4941. const std::string a[5] = {"a", "b", "c", "d", "e"};
  4942. EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
  4943. EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
  4944. }
  4945. TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
  4946. const int a[5] = {2, 1, 4, 5, 3};
  4947. EXPECT_THAT(a, UnorderedElementsAreArray(
  4948. {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
  4949. EXPECT_THAT(a, Not(UnorderedElementsAreArray(
  4950. {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
  4951. }
  4952. TEST(UnorderedElementsAreArrayTest,
  4953. TakesInitializerListOfDifferentTypedMatchers) {
  4954. const int a[5] = {2, 1, 4, 5, 3};
  4955. // The compiler cannot infer the type of the initializer list if its
  4956. // elements have different types. We must explicitly specify the
  4957. // unified element type in this case.
  4958. EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
  4959. {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
  4960. EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
  4961. {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
  4962. }
  4963. TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
  4964. ContainerHelper helper;
  4965. EXPECT_CALL(helper,
  4966. Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
  4967. helper.Call(MakeUniquePtrs({2, 1}));
  4968. }
  4969. class UnorderedElementsAreTest : public testing::Test {
  4970. protected:
  4971. typedef std::vector<int> IntVec;
  4972. };
  4973. TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
  4974. Uncopyable objs[2];
  4975. objs[0].set_value(-3);
  4976. objs[1].set_value(1);
  4977. EXPECT_THAT(objs,
  4978. UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
  4979. }
  4980. TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
  4981. const int a[] = {1, 2, 3};
  4982. std::vector<int> s(std::begin(a), std::end(a));
  4983. do {
  4984. StringMatchResultListener listener;
  4985. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
  4986. s, &listener)) << listener.str();
  4987. } while (std::next_permutation(s.begin(), s.end()));
  4988. }
  4989. TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
  4990. const int a[] = {1, 2, 3};
  4991. std::vector<int> s(std::begin(a), std::end(a));
  4992. std::vector<Matcher<int> > mv;
  4993. mv.push_back(1);
  4994. mv.push_back(2);
  4995. mv.push_back(2);
  4996. // The element with value '3' matches nothing: fail fast.
  4997. StringMatchResultListener listener;
  4998. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
  4999. s, &listener)) << listener.str();
  5000. }
  5001. TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
  5002. // Streamlike 'container' provides only minimal iterator support.
  5003. // Its iterators are tagged with input_iterator_tag, and it has no
  5004. // size() or empty() methods.
  5005. const int a[5] = {2, 1, 4, 5, 3};
  5006. Streamlike<int> s(std::begin(a), std::end(a));
  5007. EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
  5008. EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
  5009. }
  5010. TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
  5011. ContainerHelper helper;
  5012. EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
  5013. helper.Call(MakeUniquePtrs({2, 1}));
  5014. }
  5015. // One naive implementation of the matcher runs in O(N!) time, which is too
  5016. // slow for many real-world inputs. This test shows that our matcher can match
  5017. // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
  5018. // iterations and obviously effectively incomputable.
  5019. // [ RUN ] UnorderedElementsAreTest.Performance
  5020. // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
  5021. TEST_F(UnorderedElementsAreTest, Performance) {
  5022. std::vector<int> s;
  5023. std::vector<Matcher<int> > mv;
  5024. for (int i = 0; i < 100; ++i) {
  5025. s.push_back(i);
  5026. mv.push_back(_);
  5027. }
  5028. mv[50] = Eq(0);
  5029. StringMatchResultListener listener;
  5030. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
  5031. s, &listener)) << listener.str();
  5032. }
  5033. // Another variant of 'Performance' with similar expectations.
  5034. // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
  5035. // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
  5036. TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
  5037. std::vector<int> s;
  5038. std::vector<Matcher<int> > mv;
  5039. for (int i = 0; i < 100; ++i) {
  5040. s.push_back(i);
  5041. if (i & 1) {
  5042. mv.push_back(_);
  5043. } else {
  5044. mv.push_back(i);
  5045. }
  5046. }
  5047. StringMatchResultListener listener;
  5048. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
  5049. s, &listener)) << listener.str();
  5050. }
  5051. TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
  5052. std::vector<int> v;
  5053. v.push_back(4);
  5054. StringMatchResultListener listener;
  5055. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
  5056. v, &listener)) << listener.str();
  5057. EXPECT_THAT(listener.str(), Eq("which has 1 element"));
  5058. }
  5059. TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
  5060. std::vector<int> v;
  5061. StringMatchResultListener listener;
  5062. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
  5063. v, &listener)) << listener.str();
  5064. EXPECT_THAT(listener.str(), Eq(""));
  5065. }
  5066. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
  5067. std::vector<int> v;
  5068. v.push_back(1);
  5069. v.push_back(1);
  5070. StringMatchResultListener listener;
  5071. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
  5072. v, &listener)) << listener.str();
  5073. EXPECT_THAT(
  5074. listener.str(),
  5075. Eq("where the following matchers don't match any elements:\n"
  5076. "matcher #1: is equal to 2"));
  5077. }
  5078. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
  5079. std::vector<int> v;
  5080. v.push_back(1);
  5081. v.push_back(2);
  5082. StringMatchResultListener listener;
  5083. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
  5084. v, &listener)) << listener.str();
  5085. EXPECT_THAT(
  5086. listener.str(),
  5087. Eq("where the following elements don't match any matchers:\n"
  5088. "element #1: 2"));
  5089. }
  5090. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
  5091. std::vector<int> v;
  5092. v.push_back(2);
  5093. v.push_back(3);
  5094. StringMatchResultListener listener;
  5095. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
  5096. v, &listener)) << listener.str();
  5097. EXPECT_THAT(
  5098. listener.str(),
  5099. Eq("where"
  5100. " the following matchers don't match any elements:\n"
  5101. "matcher #0: is equal to 1\n"
  5102. "and"
  5103. " where"
  5104. " the following elements don't match any matchers:\n"
  5105. "element #1: 3"));
  5106. }
  5107. // Test helper for formatting element, matcher index pairs in expectations.
  5108. static std::string EMString(int element, int matcher) {
  5109. stringstream ss;
  5110. ss << "(element #" << element << ", matcher #" << matcher << ")";
  5111. return ss.str();
  5112. }
  5113. TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
  5114. // A situation where all elements and matchers have a match
  5115. // associated with them, but the max matching is not perfect.
  5116. std::vector<std::string> v;
  5117. v.push_back("a");
  5118. v.push_back("b");
  5119. v.push_back("c");
  5120. StringMatchResultListener listener;
  5121. EXPECT_FALSE(ExplainMatchResult(
  5122. UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
  5123. << listener.str();
  5124. std::string prefix =
  5125. "where no permutation of the elements can satisfy all matchers, "
  5126. "and the closest match is 2 of 3 matchers with the "
  5127. "pairings:\n";
  5128. // We have to be a bit loose here, because there are 4 valid max matches.
  5129. EXPECT_THAT(
  5130. listener.str(),
  5131. AnyOf(prefix + "{\n " + EMString(0, 0) +
  5132. ",\n " + EMString(1, 2) + "\n}",
  5133. prefix + "{\n " + EMString(0, 1) +
  5134. ",\n " + EMString(1, 2) + "\n}",
  5135. prefix + "{\n " + EMString(0, 0) +
  5136. ",\n " + EMString(2, 2) + "\n}",
  5137. prefix + "{\n " + EMString(0, 1) +
  5138. ",\n " + EMString(2, 2) + "\n}"));
  5139. }
  5140. TEST_F(UnorderedElementsAreTest, Describe) {
  5141. EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
  5142. Eq("is empty"));
  5143. EXPECT_THAT(
  5144. Describe<IntVec>(UnorderedElementsAre(345)),
  5145. Eq("has 1 element and that element is equal to 345"));
  5146. EXPECT_THAT(
  5147. Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
  5148. Eq("has 3 elements and there exists some permutation "
  5149. "of elements such that:\n"
  5150. " - element #0 is equal to 111, and\n"
  5151. " - element #1 is equal to 222, and\n"
  5152. " - element #2 is equal to 333"));
  5153. }
  5154. TEST_F(UnorderedElementsAreTest, DescribeNegation) {
  5155. EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
  5156. Eq("isn't empty"));
  5157. EXPECT_THAT(
  5158. DescribeNegation<IntVec>(UnorderedElementsAre(345)),
  5159. Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
  5160. EXPECT_THAT(
  5161. DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
  5162. Eq("doesn't have 3 elements, or there exists no permutation "
  5163. "of elements such that:\n"
  5164. " - element #0 is equal to 123, and\n"
  5165. " - element #1 is equal to 234, and\n"
  5166. " - element #2 is equal to 345"));
  5167. }
  5168. namespace {
  5169. // Used as a check on the more complex max flow method used in the
  5170. // real testing::internal::FindMaxBipartiteMatching. This method is
  5171. // compatible but runs in worst-case factorial time, so we only
  5172. // use it in testing for small problem sizes.
  5173. template <typename Graph>
  5174. class BacktrackingMaxBPMState {
  5175. public:
  5176. // Does not take ownership of 'g'.
  5177. explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
  5178. ElementMatcherPairs Compute() {
  5179. if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
  5180. return best_so_far_;
  5181. }
  5182. lhs_used_.assign(graph_->LhsSize(), kUnused);
  5183. rhs_used_.assign(graph_->RhsSize(), kUnused);
  5184. for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
  5185. matches_.clear();
  5186. RecurseInto(irhs);
  5187. if (best_so_far_.size() == graph_->RhsSize())
  5188. break;
  5189. }
  5190. return best_so_far_;
  5191. }
  5192. private:
  5193. static const size_t kUnused = static_cast<size_t>(-1);
  5194. void PushMatch(size_t lhs, size_t rhs) {
  5195. matches_.push_back(ElementMatcherPair(lhs, rhs));
  5196. lhs_used_[lhs] = rhs;
  5197. rhs_used_[rhs] = lhs;
  5198. if (matches_.size() > best_so_far_.size()) {
  5199. best_so_far_ = matches_;
  5200. }
  5201. }
  5202. void PopMatch() {
  5203. const ElementMatcherPair& back = matches_.back();
  5204. lhs_used_[back.first] = kUnused;
  5205. rhs_used_[back.second] = kUnused;
  5206. matches_.pop_back();
  5207. }
  5208. bool RecurseInto(size_t irhs) {
  5209. if (rhs_used_[irhs] != kUnused) {
  5210. return true;
  5211. }
  5212. for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
  5213. if (lhs_used_[ilhs] != kUnused) {
  5214. continue;
  5215. }
  5216. if (!graph_->HasEdge(ilhs, irhs)) {
  5217. continue;
  5218. }
  5219. PushMatch(ilhs, irhs);
  5220. if (best_so_far_.size() == graph_->RhsSize()) {
  5221. return false;
  5222. }
  5223. for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
  5224. if (!RecurseInto(mi)) return false;
  5225. }
  5226. PopMatch();
  5227. }
  5228. return true;
  5229. }
  5230. const Graph* graph_; // not owned
  5231. std::vector<size_t> lhs_used_;
  5232. std::vector<size_t> rhs_used_;
  5233. ElementMatcherPairs matches_;
  5234. ElementMatcherPairs best_so_far_;
  5235. };
  5236. template <typename Graph>
  5237. const size_t BacktrackingMaxBPMState<Graph>::kUnused;
  5238. } // namespace
  5239. // Implement a simple backtracking algorithm to determine if it is possible
  5240. // to find one element per matcher, without reusing elements.
  5241. template <typename Graph>
  5242. ElementMatcherPairs
  5243. FindBacktrackingMaxBPM(const Graph& g) {
  5244. return BacktrackingMaxBPMState<Graph>(&g).Compute();
  5245. }
  5246. class BacktrackingBPMTest : public ::testing::Test { };
  5247. // Tests the MaxBipartiteMatching algorithm with square matrices.
  5248. // The single int param is the # of nodes on each of the left and right sides.
  5249. class BipartiteTest : public ::testing::TestWithParam<size_t> {};
  5250. // Verify all match graphs up to some moderate number of edges.
  5251. TEST_P(BipartiteTest, Exhaustive) {
  5252. size_t nodes = GetParam();
  5253. MatchMatrix graph(nodes, nodes);
  5254. do {
  5255. ElementMatcherPairs matches =
  5256. internal::FindMaxBipartiteMatching(graph);
  5257. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
  5258. << "graph: " << graph.DebugString();
  5259. // Check that all elements of matches are in the graph.
  5260. // Check that elements of first and second are unique.
  5261. std::vector<bool> seen_element(graph.LhsSize());
  5262. std::vector<bool> seen_matcher(graph.RhsSize());
  5263. SCOPED_TRACE(PrintToString(matches));
  5264. for (size_t i = 0; i < matches.size(); ++i) {
  5265. size_t ilhs = matches[i].first;
  5266. size_t irhs = matches[i].second;
  5267. EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
  5268. EXPECT_FALSE(seen_element[ilhs]);
  5269. EXPECT_FALSE(seen_matcher[irhs]);
  5270. seen_element[ilhs] = true;
  5271. seen_matcher[irhs] = true;
  5272. }
  5273. } while (graph.NextGraph());
  5274. }
  5275. INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,
  5276. ::testing::Range(size_t{0}, size_t{5}));
  5277. // Parameterized by a pair interpreted as (LhsSize, RhsSize).
  5278. class BipartiteNonSquareTest
  5279. : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
  5280. };
  5281. TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
  5282. // .......
  5283. // 0:-----\ :
  5284. // 1:---\ | :
  5285. // 2:---\ | :
  5286. // 3:-\ | | :
  5287. // :.......:
  5288. // 0 1 2
  5289. MatchMatrix g(4, 3);
  5290. constexpr std::array<std::array<size_t, 2>, 4> kEdges = {
  5291. {{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}};
  5292. for (size_t i = 0; i < kEdges.size(); ++i) {
  5293. g.SetEdge(kEdges[i][0], kEdges[i][1], true);
  5294. }
  5295. EXPECT_THAT(FindBacktrackingMaxBPM(g),
  5296. ElementsAre(Pair(3, 0),
  5297. Pair(AnyOf(1, 2), 1),
  5298. Pair(0, 2))) << g.DebugString();
  5299. }
  5300. // Verify a few nonsquare matrices.
  5301. TEST_P(BipartiteNonSquareTest, Exhaustive) {
  5302. size_t nlhs = GetParam().first;
  5303. size_t nrhs = GetParam().second;
  5304. MatchMatrix graph(nlhs, nrhs);
  5305. do {
  5306. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
  5307. internal::FindMaxBipartiteMatching(graph).size())
  5308. << "graph: " << graph.DebugString()
  5309. << "\nbacktracking: "
  5310. << PrintToString(FindBacktrackingMaxBPM(graph))
  5311. << "\nmax flow: "
  5312. << PrintToString(internal::FindMaxBipartiteMatching(graph));
  5313. } while (graph.NextGraph());
  5314. }
  5315. INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteNonSquareTest,
  5316. testing::Values(
  5317. std::make_pair(1, 2),
  5318. std::make_pair(2, 1),
  5319. std::make_pair(3, 2),
  5320. std::make_pair(2, 3),
  5321. std::make_pair(4, 1),
  5322. std::make_pair(1, 4),
  5323. std::make_pair(4, 3),
  5324. std::make_pair(3, 4)));
  5325. class BipartiteRandomTest
  5326. : public ::testing::TestWithParam<std::pair<int, int> > {
  5327. };
  5328. // Verifies a large sample of larger graphs.
  5329. TEST_P(BipartiteRandomTest, LargerNets) {
  5330. int nodes = GetParam().first;
  5331. int iters = GetParam().second;
  5332. MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));
  5333. auto seed = static_cast<uint32_t>(GTEST_FLAG(random_seed));
  5334. if (seed == 0) {
  5335. seed = static_cast<uint32_t>(time(nullptr));
  5336. }
  5337. for (; iters > 0; --iters, ++seed) {
  5338. srand(static_cast<unsigned int>(seed));
  5339. graph.Randomize();
  5340. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
  5341. internal::FindMaxBipartiteMatching(graph).size())
  5342. << " graph: " << graph.DebugString()
  5343. << "\nTo reproduce the failure, rerun the test with the flag"
  5344. " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
  5345. }
  5346. }
  5347. // Test argument is a std::pair<int, int> representing (nodes, iters).
  5348. INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,
  5349. testing::Values(
  5350. std::make_pair(5, 10000),
  5351. std::make_pair(6, 5000),
  5352. std::make_pair(7, 2000),
  5353. std::make_pair(8, 500),
  5354. std::make_pair(9, 100)));
  5355. // Tests IsReadableTypeName().
  5356. TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
  5357. EXPECT_TRUE(IsReadableTypeName("int"));
  5358. EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
  5359. EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
  5360. EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
  5361. }
  5362. TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
  5363. EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
  5364. EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
  5365. EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
  5366. }
  5367. TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
  5368. EXPECT_FALSE(
  5369. IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
  5370. EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
  5371. }
  5372. TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
  5373. EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
  5374. }
  5375. // Tests FormatMatcherDescription().
  5376. TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
  5377. EXPECT_EQ("is even",
  5378. FormatMatcherDescription(false, "IsEven", Strings()));
  5379. EXPECT_EQ("not (is even)",
  5380. FormatMatcherDescription(true, "IsEven", Strings()));
  5381. const char* params[] = {"5"};
  5382. EXPECT_EQ("equals 5",
  5383. FormatMatcherDescription(false, "Equals",
  5384. Strings(params, params + 1)));
  5385. const char* params2[] = {"5", "8"};
  5386. EXPECT_EQ("is in range (5, 8)",
  5387. FormatMatcherDescription(false, "IsInRange",
  5388. Strings(params2, params2 + 2)));
  5389. }
  5390. // Tests PolymorphicMatcher::mutable_impl().
  5391. TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
  5392. PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
  5393. DivisibleByImpl& impl = m.mutable_impl();
  5394. EXPECT_EQ(42, impl.divider());
  5395. impl.set_divider(0);
  5396. EXPECT_EQ(0, m.mutable_impl().divider());
  5397. }
  5398. // Tests PolymorphicMatcher::impl().
  5399. TEST(PolymorphicMatcherTest, CanAccessImpl) {
  5400. const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
  5401. const DivisibleByImpl& impl = m.impl();
  5402. EXPECT_EQ(42, impl.divider());
  5403. }
  5404. TEST(MatcherTupleTest, ExplainsMatchFailure) {
  5405. stringstream ss1;
  5406. ExplainMatchFailureTupleTo(
  5407. std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
  5408. std::make_tuple('a', 10), &ss1);
  5409. EXPECT_EQ("", ss1.str()); // Successful match.
  5410. stringstream ss2;
  5411. ExplainMatchFailureTupleTo(
  5412. std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
  5413. std::make_tuple(2, 'b'), &ss2);
  5414. EXPECT_EQ(" Expected arg #0: is > 5\n"
  5415. " Actual: 2, which is 3 less than 5\n"
  5416. " Expected arg #1: is equal to 'a' (97, 0x61)\n"
  5417. " Actual: 'b' (98, 0x62)\n",
  5418. ss2.str()); // Failed match where both arguments need explanation.
  5419. stringstream ss3;
  5420. ExplainMatchFailureTupleTo(
  5421. std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
  5422. std::make_tuple(2, 'a'), &ss3);
  5423. EXPECT_EQ(" Expected arg #0: is > 5\n"
  5424. " Actual: 2, which is 3 less than 5\n",
  5425. ss3.str()); // Failed match where only one argument needs
  5426. // explanation.
  5427. }
  5428. // Tests Each().
  5429. TEST(EachTest, ExplainsMatchResultCorrectly) {
  5430. set<int> a; // empty
  5431. Matcher<set<int> > m = Each(2);
  5432. EXPECT_EQ("", Explain(m, a));
  5433. Matcher<const int(&)[1]> n = Each(1); // NOLINT
  5434. const int b[1] = {1};
  5435. EXPECT_EQ("", Explain(n, b));
  5436. n = Each(3);
  5437. EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
  5438. a.insert(1);
  5439. a.insert(2);
  5440. a.insert(3);
  5441. m = Each(GreaterThan(0));
  5442. EXPECT_EQ("", Explain(m, a));
  5443. m = Each(GreaterThan(10));
  5444. EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
  5445. Explain(m, a));
  5446. }
  5447. TEST(EachTest, DescribesItselfCorrectly) {
  5448. Matcher<vector<int> > m = Each(1);
  5449. EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
  5450. Matcher<vector<int> > m2 = Not(m);
  5451. EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
  5452. }
  5453. TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
  5454. vector<int> some_vector;
  5455. EXPECT_THAT(some_vector, Each(1));
  5456. some_vector.push_back(3);
  5457. EXPECT_THAT(some_vector, Not(Each(1)));
  5458. EXPECT_THAT(some_vector, Each(3));
  5459. some_vector.push_back(1);
  5460. some_vector.push_back(2);
  5461. EXPECT_THAT(some_vector, Not(Each(3)));
  5462. EXPECT_THAT(some_vector, Each(Lt(3.5)));
  5463. vector<std::string> another_vector;
  5464. another_vector.push_back("fee");
  5465. EXPECT_THAT(another_vector, Each(std::string("fee")));
  5466. another_vector.push_back("fie");
  5467. another_vector.push_back("foe");
  5468. another_vector.push_back("fum");
  5469. EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
  5470. }
  5471. TEST(EachTest, MatchesMapWhenAllElementsMatch) {
  5472. map<const char*, int> my_map;
  5473. const char* bar = "a string";
  5474. my_map[bar] = 2;
  5475. EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
  5476. map<std::string, int> another_map;
  5477. EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
  5478. another_map["fee"] = 1;
  5479. EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
  5480. another_map["fie"] = 2;
  5481. another_map["foe"] = 3;
  5482. another_map["fum"] = 4;
  5483. EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
  5484. EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
  5485. EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
  5486. }
  5487. TEST(EachTest, AcceptsMatcher) {
  5488. const int a[] = {1, 2, 3};
  5489. EXPECT_THAT(a, Each(Gt(0)));
  5490. EXPECT_THAT(a, Not(Each(Gt(1))));
  5491. }
  5492. TEST(EachTest, WorksForNativeArrayAsTuple) {
  5493. const int a[] = {1, 2};
  5494. const int* const pointer = a;
  5495. EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
  5496. EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
  5497. }
  5498. TEST(EachTest, WorksWithMoveOnly) {
  5499. ContainerHelper helper;
  5500. EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
  5501. helper.Call(MakeUniquePtrs({1, 2}));
  5502. }
  5503. // For testing Pointwise().
  5504. class IsHalfOfMatcher {
  5505. public:
  5506. template <typename T1, typename T2>
  5507. bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
  5508. MatchResultListener* listener) const {
  5509. if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
  5510. *listener << "where the second is " << std::get<1>(a_pair);
  5511. return true;
  5512. } else {
  5513. *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
  5514. return false;
  5515. }
  5516. }
  5517. void DescribeTo(ostream* os) const {
  5518. *os << "are a pair where the first is half of the second";
  5519. }
  5520. void DescribeNegationTo(ostream* os) const {
  5521. *os << "are a pair where the first isn't half of the second";
  5522. }
  5523. };
  5524. PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
  5525. return MakePolymorphicMatcher(IsHalfOfMatcher());
  5526. }
  5527. TEST(PointwiseTest, DescribesSelf) {
  5528. vector<int> rhs;
  5529. rhs.push_back(1);
  5530. rhs.push_back(2);
  5531. rhs.push_back(3);
  5532. const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
  5533. EXPECT_EQ("contains 3 values, where each value and its corresponding value "
  5534. "in { 1, 2, 3 } are a pair where the first is half of the second",
  5535. Describe(m));
  5536. EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
  5537. "index i where x and the i-th value of { 1, 2, 3 } are a pair "
  5538. "where the first isn't half of the second",
  5539. DescribeNegation(m));
  5540. }
  5541. TEST(PointwiseTest, MakesCopyOfRhs) {
  5542. list<signed char> rhs;
  5543. rhs.push_back(2);
  5544. rhs.push_back(4);
  5545. int lhs[] = {1, 2};
  5546. const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
  5547. EXPECT_THAT(lhs, m);
  5548. // Changing rhs now shouldn't affect m, which made a copy of rhs.
  5549. rhs.push_back(6);
  5550. EXPECT_THAT(lhs, m);
  5551. }
  5552. TEST(PointwiseTest, WorksForLhsNativeArray) {
  5553. const int lhs[] = {1, 2, 3};
  5554. vector<int> rhs;
  5555. rhs.push_back(2);
  5556. rhs.push_back(4);
  5557. rhs.push_back(6);
  5558. EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
  5559. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
  5560. }
  5561. TEST(PointwiseTest, WorksForRhsNativeArray) {
  5562. const int rhs[] = {1, 2, 3};
  5563. vector<int> lhs;
  5564. lhs.push_back(2);
  5565. lhs.push_back(4);
  5566. lhs.push_back(6);
  5567. EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
  5568. EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
  5569. }
  5570. // Test is effective only with sanitizers.
  5571. TEST(PointwiseTest, WorksForVectorOfBool) {
  5572. vector<bool> rhs(3, false);
  5573. rhs[1] = true;
  5574. vector<bool> lhs = rhs;
  5575. EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
  5576. rhs[0] = true;
  5577. EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
  5578. }
  5579. TEST(PointwiseTest, WorksForRhsInitializerList) {
  5580. const vector<int> lhs{2, 4, 6};
  5581. EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
  5582. EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
  5583. }
  5584. TEST(PointwiseTest, RejectsWrongSize) {
  5585. const double lhs[2] = {1, 2};
  5586. const int rhs[1] = {0};
  5587. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
  5588. EXPECT_EQ("which contains 2 values",
  5589. Explain(Pointwise(Gt(), rhs), lhs));
  5590. const int rhs2[3] = {0, 1, 2};
  5591. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
  5592. }
  5593. TEST(PointwiseTest, RejectsWrongContent) {
  5594. const double lhs[3] = {1, 2, 3};
  5595. const int rhs[3] = {2, 6, 4};
  5596. EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
  5597. EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
  5598. "where the second/2 is 3",
  5599. Explain(Pointwise(IsHalfOf(), rhs), lhs));
  5600. }
  5601. TEST(PointwiseTest, AcceptsCorrectContent) {
  5602. const double lhs[3] = {1, 2, 3};
  5603. const int rhs[3] = {2, 4, 6};
  5604. EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
  5605. EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
  5606. }
  5607. TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
  5608. const double lhs[3] = {1, 2, 3};
  5609. const int rhs[3] = {2, 4, 6};
  5610. const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
  5611. EXPECT_THAT(lhs, Pointwise(m1, rhs));
  5612. EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
  5613. // This type works as a std::tuple<const double&, const int&> can be
  5614. // implicitly cast to std::tuple<double, int>.
  5615. const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
  5616. EXPECT_THAT(lhs, Pointwise(m2, rhs));
  5617. EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
  5618. }
  5619. MATCHER(PointeeEquals, "Points to an equal value") {
  5620. return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
  5621. ::testing::get<0>(arg), result_listener);
  5622. }
  5623. TEST(PointwiseTest, WorksWithMoveOnly) {
  5624. ContainerHelper helper;
  5625. EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
  5626. helper.Call(MakeUniquePtrs({1, 2}));
  5627. }
  5628. TEST(UnorderedPointwiseTest, DescribesSelf) {
  5629. vector<int> rhs;
  5630. rhs.push_back(1);
  5631. rhs.push_back(2);
  5632. rhs.push_back(3);
  5633. const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
  5634. EXPECT_EQ(
  5635. "has 3 elements and there exists some permutation of elements such "
  5636. "that:\n"
  5637. " - element #0 and 1 are a pair where the first is half of the second, "
  5638. "and\n"
  5639. " - element #1 and 2 are a pair where the first is half of the second, "
  5640. "and\n"
  5641. " - element #2 and 3 are a pair where the first is half of the second",
  5642. Describe(m));
  5643. EXPECT_EQ(
  5644. "doesn't have 3 elements, or there exists no permutation of elements "
  5645. "such that:\n"
  5646. " - element #0 and 1 are a pair where the first is half of the second, "
  5647. "and\n"
  5648. " - element #1 and 2 are a pair where the first is half of the second, "
  5649. "and\n"
  5650. " - element #2 and 3 are a pair where the first is half of the second",
  5651. DescribeNegation(m));
  5652. }
  5653. TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
  5654. list<signed char> rhs;
  5655. rhs.push_back(2);
  5656. rhs.push_back(4);
  5657. int lhs[] = {2, 1};
  5658. const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
  5659. EXPECT_THAT(lhs, m);
  5660. // Changing rhs now shouldn't affect m, which made a copy of rhs.
  5661. rhs.push_back(6);
  5662. EXPECT_THAT(lhs, m);
  5663. }
  5664. TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
  5665. const int lhs[] = {1, 2, 3};
  5666. vector<int> rhs;
  5667. rhs.push_back(4);
  5668. rhs.push_back(6);
  5669. rhs.push_back(2);
  5670. EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
  5671. EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
  5672. }
  5673. TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
  5674. const int rhs[] = {1, 2, 3};
  5675. vector<int> lhs;
  5676. lhs.push_back(4);
  5677. lhs.push_back(2);
  5678. lhs.push_back(6);
  5679. EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
  5680. EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
  5681. }
  5682. TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
  5683. const vector<int> lhs{2, 4, 6};
  5684. EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
  5685. EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
  5686. }
  5687. TEST(UnorderedPointwiseTest, RejectsWrongSize) {
  5688. const double lhs[2] = {1, 2};
  5689. const int rhs[1] = {0};
  5690. EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
  5691. EXPECT_EQ("which has 2 elements",
  5692. Explain(UnorderedPointwise(Gt(), rhs), lhs));
  5693. const int rhs2[3] = {0, 1, 2};
  5694. EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
  5695. }
  5696. TEST(UnorderedPointwiseTest, RejectsWrongContent) {
  5697. const double lhs[3] = {1, 2, 3};
  5698. const int rhs[3] = {2, 6, 6};
  5699. EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
  5700. EXPECT_EQ("where the following elements don't match any matchers:\n"
  5701. "element #1: 2",
  5702. Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
  5703. }
  5704. TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
  5705. const double lhs[3] = {1, 2, 3};
  5706. const int rhs[3] = {2, 4, 6};
  5707. EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
  5708. }
  5709. TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
  5710. const double lhs[3] = {1, 2, 3};
  5711. const int rhs[3] = {6, 4, 2};
  5712. EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
  5713. }
  5714. TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
  5715. const double lhs[3] = {1, 2, 3};
  5716. const int rhs[3] = {4, 6, 2};
  5717. const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
  5718. EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
  5719. // This type works as a std::tuple<const double&, const int&> can be
  5720. // implicitly cast to std::tuple<double, int>.
  5721. const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
  5722. EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
  5723. }
  5724. TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
  5725. ContainerHelper helper;
  5726. EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
  5727. std::vector<int>{1, 2})));
  5728. helper.Call(MakeUniquePtrs({2, 1}));
  5729. }
  5730. // Sample optional type implementation with minimal requirements for use with
  5731. // Optional matcher.
  5732. template <typename T>
  5733. class SampleOptional {
  5734. public:
  5735. using value_type = T;
  5736. explicit SampleOptional(T value)
  5737. : value_(std::move(value)), has_value_(true) {}
  5738. SampleOptional() : value_(), has_value_(false) {}
  5739. operator bool() const { return has_value_; }
  5740. const T& operator*() const { return value_; }
  5741. private:
  5742. T value_;
  5743. bool has_value_;
  5744. };
  5745. TEST(OptionalTest, DescribesSelf) {
  5746. const Matcher<SampleOptional<int>> m = Optional(Eq(1));
  5747. EXPECT_EQ("value is equal to 1", Describe(m));
  5748. }
  5749. TEST(OptionalTest, ExplainsSelf) {
  5750. const Matcher<SampleOptional<int>> m = Optional(Eq(1));
  5751. EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
  5752. EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
  5753. }
  5754. TEST(OptionalTest, MatchesNonEmptyOptional) {
  5755. const Matcher<SampleOptional<int>> m1 = Optional(1);
  5756. const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
  5757. const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
  5758. SampleOptional<int> opt(1);
  5759. EXPECT_TRUE(m1.Matches(opt));
  5760. EXPECT_FALSE(m2.Matches(opt));
  5761. EXPECT_TRUE(m3.Matches(opt));
  5762. }
  5763. TEST(OptionalTest, DoesNotMatchNullopt) {
  5764. const Matcher<SampleOptional<int>> m = Optional(1);
  5765. SampleOptional<int> empty;
  5766. EXPECT_FALSE(m.Matches(empty));
  5767. }
  5768. TEST(OptionalTest, WorksWithMoveOnly) {
  5769. Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
  5770. EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
  5771. }
  5772. class SampleVariantIntString {
  5773. public:
  5774. SampleVariantIntString(int i) : i_(i), has_int_(true) {}
  5775. SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
  5776. template <typename T>
  5777. friend bool holds_alternative(const SampleVariantIntString& value) {
  5778. return value.has_int_ == std::is_same<T, int>::value;
  5779. }
  5780. template <typename T>
  5781. friend const T& get(const SampleVariantIntString& value) {
  5782. return value.get_impl(static_cast<T*>(nullptr));
  5783. }
  5784. private:
  5785. const int& get_impl(int*) const { return i_; }
  5786. const std::string& get_impl(std::string*) const { return s_; }
  5787. int i_;
  5788. std::string s_;
  5789. bool has_int_;
  5790. };
  5791. TEST(VariantTest, DescribesSelf) {
  5792. const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  5793. EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
  5794. "'.*' and the value is equal to 1"));
  5795. }
  5796. TEST(VariantTest, ExplainsSelf) {
  5797. const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  5798. EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
  5799. ContainsRegex("whose value 1"));
  5800. EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
  5801. HasSubstr("whose value is not of type '"));
  5802. EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
  5803. "whose value 2 doesn't match");
  5804. }
  5805. TEST(VariantTest, FullMatch) {
  5806. Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  5807. EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
  5808. m = VariantWith<std::string>(Eq("1"));
  5809. EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
  5810. }
  5811. TEST(VariantTest, TypeDoesNotMatch) {
  5812. Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  5813. EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
  5814. m = VariantWith<std::string>(Eq("1"));
  5815. EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
  5816. }
  5817. TEST(VariantTest, InnerDoesNotMatch) {
  5818. Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  5819. EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
  5820. m = VariantWith<std::string>(Eq("1"));
  5821. EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
  5822. }
  5823. class SampleAnyType {
  5824. public:
  5825. explicit SampleAnyType(int i) : index_(0), i_(i) {}
  5826. explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
  5827. template <typename T>
  5828. friend const T* any_cast(const SampleAnyType* any) {
  5829. return any->get_impl(static_cast<T*>(nullptr));
  5830. }
  5831. private:
  5832. int index_;
  5833. int i_;
  5834. std::string s_;
  5835. const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }
  5836. const std::string* get_impl(std::string*) const {
  5837. return index_ == 1 ? &s_ : nullptr;
  5838. }
  5839. };
  5840. TEST(AnyWithTest, FullMatch) {
  5841. Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
  5842. EXPECT_TRUE(m.Matches(SampleAnyType(1)));
  5843. }
  5844. TEST(AnyWithTest, TestBadCastType) {
  5845. Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));
  5846. EXPECT_FALSE(m.Matches(SampleAnyType(1)));
  5847. }
  5848. TEST(AnyWithTest, TestUseInContainers) {
  5849. std::vector<SampleAnyType> a;
  5850. a.emplace_back(1);
  5851. a.emplace_back(2);
  5852. a.emplace_back(3);
  5853. EXPECT_THAT(
  5854. a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));
  5855. std::vector<SampleAnyType> b;
  5856. b.emplace_back("hello");
  5857. b.emplace_back("merhaba");
  5858. b.emplace_back("salut");
  5859. EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),
  5860. AnyWith<std::string>("merhaba"),
  5861. AnyWith<std::string>("salut")}));
  5862. }
  5863. TEST(AnyWithTest, TestCompare) {
  5864. EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
  5865. }
  5866. TEST(AnyWithTest, DescribesSelf) {
  5867. const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
  5868. EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
  5869. "'.*' and the value is equal to 1"));
  5870. }
  5871. TEST(AnyWithTest, ExplainsSelf) {
  5872. const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
  5873. EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
  5874. EXPECT_THAT(Explain(m, SampleAnyType("A")),
  5875. HasSubstr("whose value is not of type '"));
  5876. EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
  5877. }
  5878. TEST(PointeeTest, WorksOnMoveOnlyType) {
  5879. std::unique_ptr<int> p(new int(3));
  5880. EXPECT_THAT(p, Pointee(Eq(3)));
  5881. EXPECT_THAT(p, Not(Pointee(Eq(2))));
  5882. }
  5883. TEST(NotTest, WorksOnMoveOnlyType) {
  5884. std::unique_ptr<int> p(new int(3));
  5885. EXPECT_THAT(p, Pointee(Eq(3)));
  5886. EXPECT_THAT(p, Not(Pointee(Eq(2))));
  5887. }
  5888. // Tests Args<k0, ..., kn>(m).
  5889. TEST(ArgsTest, AcceptsZeroTemplateArg) {
  5890. const std::tuple<int, bool> t(5, true);
  5891. EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));
  5892. EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));
  5893. }
  5894. TEST(ArgsTest, AcceptsOneTemplateArg) {
  5895. const std::tuple<int, bool> t(5, true);
  5896. EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));
  5897. EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));
  5898. EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));
  5899. }
  5900. TEST(ArgsTest, AcceptsTwoTemplateArgs) {
  5901. const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
  5902. EXPECT_THAT(t, (Args<0, 1>(Lt())));
  5903. EXPECT_THAT(t, (Args<1, 2>(Lt())));
  5904. EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
  5905. }
  5906. TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
  5907. const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
  5908. EXPECT_THAT(t, (Args<0, 0>(Eq())));
  5909. EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
  5910. }
  5911. TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
  5912. const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
  5913. EXPECT_THAT(t, (Args<2, 0>(Gt())));
  5914. EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
  5915. }
  5916. MATCHER(SumIsZero, "") {
  5917. return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;
  5918. }
  5919. TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
  5920. EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
  5921. EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
  5922. }
  5923. TEST(ArgsTest, CanBeNested) {
  5924. const std::tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT
  5925. EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
  5926. EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
  5927. }
  5928. TEST(ArgsTest, CanMatchTupleByValue) {
  5929. typedef std::tuple<char, int, int> Tuple3;
  5930. const Matcher<Tuple3> m = Args<1, 2>(Lt());
  5931. EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
  5932. EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
  5933. }
  5934. TEST(ArgsTest, CanMatchTupleByReference) {
  5935. typedef std::tuple<char, char, int> Tuple3;
  5936. const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
  5937. EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
  5938. EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
  5939. }
  5940. // Validates that arg is printed as str.
  5941. MATCHER_P(PrintsAs, str, "") {
  5942. return testing::PrintToString(arg) == str;
  5943. }
  5944. TEST(ArgsTest, AcceptsTenTemplateArgs) {
  5945. EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
  5946. (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
  5947. PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
  5948. EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
  5949. Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
  5950. PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
  5951. }
  5952. TEST(ArgsTest, DescirbesSelfCorrectly) {
  5953. const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt());
  5954. EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
  5955. "the first < the second",
  5956. Describe(m));
  5957. }
  5958. TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
  5959. const Matcher<const std::tuple<int, bool, char, int>&> m =
  5960. Args<0, 2, 3>(Args<2, 0>(Lt()));
  5961. EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
  5962. "whose fields (#2, #0) are a pair where the first < the second",
  5963. Describe(m));
  5964. }
  5965. TEST(ArgsTest, DescribesNegationCorrectly) {
  5966. const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt());
  5967. EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
  5968. "where the first > the second",
  5969. DescribeNegation(m));
  5970. }
  5971. TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
  5972. const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq());
  5973. EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
  5974. Explain(m, std::make_tuple(false, 42, 42)));
  5975. EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
  5976. Explain(m, std::make_tuple(false, 42, 43)));
  5977. }
  5978. // For testing Args<>'s explanation.
  5979. class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > {
  5980. public:
  5981. void DescribeTo(::std::ostream* /*os*/) const override {}
  5982. bool MatchAndExplain(std::tuple<char, int> value,
  5983. MatchResultListener* listener) const override {
  5984. const int diff = std::get<0>(value) - std::get<1>(value);
  5985. if (diff > 0) {
  5986. *listener << "where the first value is " << diff
  5987. << " more than the second";
  5988. }
  5989. return diff < 0;
  5990. }
  5991. };
  5992. Matcher<std::tuple<char, int> > LessThan() {
  5993. return MakeMatcher(new LessThanMatcher);
  5994. }
  5995. TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
  5996. const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan());
  5997. EXPECT_EQ(
  5998. "whose fields (#0, #2) are ('a' (97, 0x61), 42), "
  5999. "where the first value is 55 more than the second",
  6000. Explain(m, std::make_tuple('a', 42, 42)));
  6001. EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
  6002. Explain(m, std::make_tuple('\0', 42, 43)));
  6003. }
  6004. class PredicateFormatterFromMatcherTest : public ::testing::Test {
  6005. protected:
  6006. enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
  6007. // A matcher that can return different results when used multiple times on the
  6008. // same input. No real matcher should do this; but this lets us test that we
  6009. // detect such behavior and fail appropriately.
  6010. class MockMatcher : public MatcherInterface<Behavior> {
  6011. public:
  6012. bool MatchAndExplain(Behavior behavior,
  6013. MatchResultListener* listener) const override {
  6014. *listener << "[MatchAndExplain]";
  6015. switch (behavior) {
  6016. case kInitialSuccess:
  6017. // The first call to MatchAndExplain should use a "not interested"
  6018. // listener; so this is expected to return |true|. There should be no
  6019. // subsequent calls.
  6020. return !listener->IsInterested();
  6021. case kAlwaysFail:
  6022. return false;
  6023. case kFlaky:
  6024. // The first call to MatchAndExplain should use a "not interested"
  6025. // listener; so this will return |false|. Subsequent calls should have
  6026. // an "interested" listener; so this will return |true|, thus
  6027. // simulating a flaky matcher.
  6028. return listener->IsInterested();
  6029. }
  6030. GTEST_LOG_(FATAL) << "This should never be reached";
  6031. return false;
  6032. }
  6033. void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
  6034. void DescribeNegationTo(ostream* os) const override {
  6035. *os << "[DescribeNegationTo]";
  6036. }
  6037. };
  6038. AssertionResult RunPredicateFormatter(Behavior behavior) {
  6039. auto matcher = MakeMatcher(new MockMatcher);
  6040. PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
  6041. matcher);
  6042. return predicate_formatter("dummy-name", behavior);
  6043. }
  6044. };
  6045. TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
  6046. AssertionResult result = RunPredicateFormatter(kInitialSuccess);
  6047. EXPECT_TRUE(result); // Implicit cast to bool.
  6048. std::string expect;
  6049. EXPECT_EQ(expect, result.message());
  6050. }
  6051. TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
  6052. AssertionResult result = RunPredicateFormatter(kAlwaysFail);
  6053. EXPECT_FALSE(result); // Implicit cast to bool.
  6054. std::string expect =
  6055. "Value of: dummy-name\nExpected: [DescribeTo]\n"
  6056. " Actual: 1" +
  6057. OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
  6058. EXPECT_EQ(expect, result.message());
  6059. }
  6060. TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
  6061. AssertionResult result = RunPredicateFormatter(kFlaky);
  6062. EXPECT_FALSE(result); // Implicit cast to bool.
  6063. std::string expect =
  6064. "Value of: dummy-name\nExpected: [DescribeTo]\n"
  6065. " The matcher failed on the initial attempt; but passed when rerun to "
  6066. "generate the explanation.\n"
  6067. " Actual: 2" +
  6068. OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
  6069. EXPECT_EQ(expect, result.message());
  6070. }
  6071. // Tests for ElementsAre().
  6072. TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
  6073. Matcher<const vector<int>&> m = ElementsAre();
  6074. EXPECT_EQ("is empty", Describe(m));
  6075. }
  6076. TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
  6077. Matcher<vector<int>> m = ElementsAre(Gt(5));
  6078. EXPECT_EQ("has 1 element that is > 5", Describe(m));
  6079. }
  6080. TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
  6081. Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
  6082. EXPECT_EQ(
  6083. "has 2 elements where\n"
  6084. "element #0 is equal to \"one\",\n"
  6085. "element #1 is equal to \"two\"",
  6086. Describe(m));
  6087. }
  6088. TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
  6089. Matcher<vector<int>> m = ElementsAre();
  6090. EXPECT_EQ("isn't empty", DescribeNegation(m));
  6091. }
  6092. TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
  6093. Matcher<const list<int>&> m = ElementsAre(Gt(5));
  6094. EXPECT_EQ(
  6095. "doesn't have 1 element, or\n"
  6096. "element #0 isn't > 5",
  6097. DescribeNegation(m));
  6098. }
  6099. TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
  6100. Matcher<const list<std::string>&> m = ElementsAre("one", "two");
  6101. EXPECT_EQ(
  6102. "doesn't have 2 elements, or\n"
  6103. "element #0 isn't equal to \"one\", or\n"
  6104. "element #1 isn't equal to \"two\"",
  6105. DescribeNegation(m));
  6106. }
  6107. TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
  6108. Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
  6109. list<int> test_list;
  6110. test_list.push_back(1);
  6111. test_list.push_back(3);
  6112. EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything.
  6113. }
  6114. TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
  6115. Matcher<const vector<int>&> m =
  6116. ElementsAre(GreaterThan(1), 0, GreaterThan(2));
  6117. const int a[] = {10, 0, 100};
  6118. vector<int> test_vector(std::begin(a), std::end(a));
  6119. EXPECT_EQ(
  6120. "whose element #0 matches, which is 9 more than 1,\n"
  6121. "and whose element #2 matches, which is 98 more than 2",
  6122. Explain(m, test_vector));
  6123. }
  6124. TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
  6125. Matcher<const list<int>&> m = ElementsAre(1, 3);
  6126. list<int> test_list;
  6127. // No need to explain when the container is empty.
  6128. EXPECT_EQ("", Explain(m, test_list));
  6129. test_list.push_back(1);
  6130. EXPECT_EQ("which has 1 element", Explain(m, test_list));
  6131. }
  6132. TEST(ElementsAreTest, CanExplainMismatchRightSize) {
  6133. Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
  6134. vector<int> v;
  6135. v.push_back(2);
  6136. v.push_back(1);
  6137. EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
  6138. v[0] = 1;
  6139. EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
  6140. Explain(m, v));
  6141. }
  6142. TEST(ElementsAreTest, MatchesOneElementVector) {
  6143. vector<std::string> test_vector;
  6144. test_vector.push_back("test string");
  6145. EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
  6146. }
  6147. TEST(ElementsAreTest, MatchesOneElementList) {
  6148. list<std::string> test_list;
  6149. test_list.push_back("test string");
  6150. EXPECT_THAT(test_list, ElementsAre("test string"));
  6151. }
  6152. TEST(ElementsAreTest, MatchesThreeElementVector) {
  6153. vector<std::string> test_vector;
  6154. test_vector.push_back("one");
  6155. test_vector.push_back("two");
  6156. test_vector.push_back("three");
  6157. EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
  6158. }
  6159. TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
  6160. vector<int> test_vector;
  6161. test_vector.push_back(4);
  6162. EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
  6163. }
  6164. TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
  6165. vector<int> test_vector;
  6166. test_vector.push_back(4);
  6167. EXPECT_THAT(test_vector, ElementsAre(_));
  6168. }
  6169. TEST(ElementsAreTest, MatchesOneElementValue) {
  6170. vector<int> test_vector;
  6171. test_vector.push_back(4);
  6172. EXPECT_THAT(test_vector, ElementsAre(4));
  6173. }
  6174. TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
  6175. vector<int> test_vector;
  6176. test_vector.push_back(1);
  6177. test_vector.push_back(2);
  6178. test_vector.push_back(3);
  6179. EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
  6180. }
  6181. TEST(ElementsAreTest, MatchesTenElementVector) {
  6182. const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  6183. vector<int> test_vector(std::begin(a), std::end(a));
  6184. EXPECT_THAT(test_vector,
  6185. // The element list can contain values and/or matchers
  6186. // of different types.
  6187. ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
  6188. }
  6189. TEST(ElementsAreTest, DoesNotMatchWrongSize) {
  6190. vector<std::string> test_vector;
  6191. test_vector.push_back("test string");
  6192. test_vector.push_back("test string");
  6193. Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
  6194. EXPECT_FALSE(m.Matches(test_vector));
  6195. }
  6196. TEST(ElementsAreTest, DoesNotMatchWrongValue) {
  6197. vector<std::string> test_vector;
  6198. test_vector.push_back("other string");
  6199. Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
  6200. EXPECT_FALSE(m.Matches(test_vector));
  6201. }
  6202. TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
  6203. vector<std::string> test_vector;
  6204. test_vector.push_back("one");
  6205. test_vector.push_back("three");
  6206. test_vector.push_back("two");
  6207. Matcher<vector<std::string>> m =
  6208. ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
  6209. EXPECT_FALSE(m.Matches(test_vector));
  6210. }
  6211. TEST(ElementsAreTest, WorksForNestedContainer) {
  6212. constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
  6213. vector<list<char>> nested;
  6214. for (const auto& s : strings) {
  6215. nested.emplace_back(s, s + strlen(s));
  6216. }
  6217. EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
  6218. ElementsAre('w', 'o', _, _, 'd')));
  6219. EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
  6220. ElementsAre('w', 'o', _, _, 'd'))));
  6221. }
  6222. TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
  6223. int a[] = {0, 1, 2};
  6224. vector<int> v(std::begin(a), std::end(a));
  6225. EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
  6226. EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
  6227. }
  6228. TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
  6229. int a[] = {0, 1, 2};
  6230. vector<int> v(std::begin(a), std::end(a));
  6231. EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
  6232. EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
  6233. }
  6234. TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
  6235. int array[] = {0, 1, 2};
  6236. EXPECT_THAT(array, ElementsAre(0, 1, _));
  6237. EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
  6238. EXPECT_THAT(array, Not(ElementsAre(0, _)));
  6239. }
  6240. class NativeArrayPassedAsPointerAndSize {
  6241. public:
  6242. NativeArrayPassedAsPointerAndSize() {}
  6243. MOCK_METHOD(void, Helper, (int* array, int size));
  6244. private:
  6245. GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
  6246. };
  6247. TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
  6248. int array[] = {0, 1};
  6249. ::std::tuple<int*, size_t> array_as_tuple(array, 2);
  6250. EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
  6251. EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
  6252. NativeArrayPassedAsPointerAndSize helper;
  6253. EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
  6254. helper.Helper(array, 2);
  6255. }
  6256. TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
  6257. const char a2[][3] = {"hi", "lo"};
  6258. EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
  6259. ElementsAre('l', 'o', '\0')));
  6260. EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
  6261. EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
  6262. ElementsAre('l', 'o', '\0')));
  6263. }
  6264. TEST(ElementsAreTest, AcceptsStringLiteral) {
  6265. std::string array[] = {"hi", "one", "two"};
  6266. EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
  6267. EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
  6268. }
  6269. // Declared here with the size unknown. Defined AFTER the following test.
  6270. extern const char kHi[];
  6271. TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
  6272. // The size of kHi is not known in this test, but ElementsAre() should
  6273. // still accept it.
  6274. std::string array1[] = {"hi"};
  6275. EXPECT_THAT(array1, ElementsAre(kHi));
  6276. std::string array2[] = {"ho"};
  6277. EXPECT_THAT(array2, Not(ElementsAre(kHi)));
  6278. }
  6279. const char kHi[] = "hi";
  6280. TEST(ElementsAreTest, MakesCopyOfArguments) {
  6281. int x = 1;
  6282. int y = 2;
  6283. // This should make a copy of x and y.
  6284. ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
  6285. polymorphic_matcher = ElementsAre(x, y);
  6286. // Changing x and y now shouldn't affect the meaning of the above matcher.
  6287. x = y = 0;
  6288. const int array1[] = {1, 2};
  6289. EXPECT_THAT(array1, polymorphic_matcher);
  6290. const int array2[] = {0, 0};
  6291. EXPECT_THAT(array2, Not(polymorphic_matcher));
  6292. }
  6293. // Tests for ElementsAreArray(). Since ElementsAreArray() shares most
  6294. // of the implementation with ElementsAre(), we don't test it as
  6295. // thoroughly here.
  6296. TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
  6297. const int a[] = {1, 2, 3};
  6298. vector<int> test_vector(std::begin(a), std::end(a));
  6299. EXPECT_THAT(test_vector, ElementsAreArray(a));
  6300. test_vector[2] = 0;
  6301. EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
  6302. }
  6303. TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
  6304. std::array<const char*, 3> a = {{"one", "two", "three"}};
  6305. vector<std::string> test_vector(std::begin(a), std::end(a));
  6306. EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
  6307. const char** p = a.data();
  6308. test_vector[0] = "1";
  6309. EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
  6310. }
  6311. TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
  6312. const char* a[] = {"one", "two", "three"};
  6313. vector<std::string> test_vector(std::begin(a), std::end(a));
  6314. EXPECT_THAT(test_vector, ElementsAreArray(a));
  6315. test_vector[0] = "1";
  6316. EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
  6317. }
  6318. TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
  6319. const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
  6320. StrEq("three")};
  6321. vector<std::string> test_vector;
  6322. test_vector.push_back("one");
  6323. test_vector.push_back("two");
  6324. test_vector.push_back("three");
  6325. EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
  6326. test_vector.push_back("three");
  6327. EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
  6328. }
  6329. TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
  6330. const int a[] = {1, 2, 3};
  6331. vector<int> test_vector(std::begin(a), std::end(a));
  6332. const vector<int> expected(std::begin(a), std::end(a));
  6333. EXPECT_THAT(test_vector, ElementsAreArray(expected));
  6334. test_vector.push_back(4);
  6335. EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
  6336. }
  6337. TEST(ElementsAreArrayTest, TakesInitializerList) {
  6338. const int a[5] = {1, 2, 3, 4, 5};
  6339. EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
  6340. EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
  6341. EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
  6342. }
  6343. TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
  6344. const std::string a[5] = {"a", "b", "c", "d", "e"};
  6345. EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
  6346. EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
  6347. EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
  6348. }
  6349. TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
  6350. const int a[5] = {1, 2, 3, 4, 5};
  6351. EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
  6352. EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
  6353. }
  6354. TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
  6355. const int a[5] = {1, 2, 3, 4, 5};
  6356. // The compiler cannot infer the type of the initializer list if its
  6357. // elements have different types. We must explicitly specify the
  6358. // unified element type in this case.
  6359. EXPECT_THAT(
  6360. a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
  6361. EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
  6362. {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
  6363. }
  6364. TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
  6365. const int a[] = {1, 2, 3};
  6366. const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
  6367. vector<int> test_vector(std::begin(a), std::end(a));
  6368. const vector<Matcher<int>> expected(std::begin(kMatchers),
  6369. std::end(kMatchers));
  6370. EXPECT_THAT(test_vector, ElementsAreArray(expected));
  6371. test_vector.push_back(4);
  6372. EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
  6373. }
  6374. TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
  6375. const int a[] = {1, 2, 3};
  6376. const vector<int> test_vector(std::begin(a), std::end(a));
  6377. const vector<int> expected(std::begin(a), std::end(a));
  6378. EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
  6379. // Pointers are iterators, too.
  6380. EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
  6381. // The empty range of NULL pointers should also be okay.
  6382. int* const null_int = nullptr;
  6383. EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
  6384. EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
  6385. }
  6386. // Since ElementsAre() and ElementsAreArray() share much of the
  6387. // implementation, we only do a sanity test for native arrays here.
  6388. TEST(ElementsAreArrayTest, WorksWithNativeArray) {
  6389. ::std::string a[] = {"hi", "ho"};
  6390. ::std::string b[] = {"hi", "ho"};
  6391. EXPECT_THAT(a, ElementsAreArray(b));
  6392. EXPECT_THAT(a, ElementsAreArray(b, 2));
  6393. EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
  6394. }
  6395. TEST(ElementsAreArrayTest, SourceLifeSpan) {
  6396. const int a[] = {1, 2, 3};
  6397. vector<int> test_vector(std::begin(a), std::end(a));
  6398. vector<int> expect(std::begin(a), std::end(a));
  6399. ElementsAreArrayMatcher<int> matcher_maker =
  6400. ElementsAreArray(expect.begin(), expect.end());
  6401. EXPECT_THAT(test_vector, matcher_maker);
  6402. // Changing in place the values that initialized matcher_maker should not
  6403. // affect matcher_maker anymore. It should have made its own copy of them.
  6404. for (int& i : expect) {
  6405. i += 10;
  6406. }
  6407. EXPECT_THAT(test_vector, matcher_maker);
  6408. test_vector.push_back(3);
  6409. EXPECT_THAT(test_vector, Not(matcher_maker));
  6410. }
  6411. // Tests for the MATCHER*() macro family.
  6412. // Tests that a simple MATCHER() definition works.
  6413. MATCHER(IsEven, "") { return (arg % 2) == 0; }
  6414. TEST(MatcherMacroTest, Works) {
  6415. const Matcher<int> m = IsEven();
  6416. EXPECT_TRUE(m.Matches(6));
  6417. EXPECT_FALSE(m.Matches(7));
  6418. EXPECT_EQ("is even", Describe(m));
  6419. EXPECT_EQ("not (is even)", DescribeNegation(m));
  6420. EXPECT_EQ("", Explain(m, 6));
  6421. EXPECT_EQ("", Explain(m, 7));
  6422. }
  6423. // This also tests that the description string can reference 'negation'.
  6424. MATCHER(IsEven2, negation ? "is odd" : "is even") {
  6425. if ((arg % 2) == 0) {
  6426. // Verifies that we can stream to result_listener, a listener
  6427. // supplied by the MATCHER macro implicitly.
  6428. *result_listener << "OK";
  6429. return true;
  6430. } else {
  6431. *result_listener << "% 2 == " << (arg % 2);
  6432. return false;
  6433. }
  6434. }
  6435. // This also tests that the description string can reference matcher
  6436. // parameters.
  6437. MATCHER_P2(EqSumOf, x, y,
  6438. std::string(negation ? "doesn't equal" : "equals") + " the sum of " +
  6439. PrintToString(x) + " and " + PrintToString(y)) {
  6440. if (arg == (x + y)) {
  6441. *result_listener << "OK";
  6442. return true;
  6443. } else {
  6444. // Verifies that we can stream to the underlying stream of
  6445. // result_listener.
  6446. if (result_listener->stream() != nullptr) {
  6447. *result_listener->stream() << "diff == " << (x + y - arg);
  6448. }
  6449. return false;
  6450. }
  6451. }
  6452. // Tests that the matcher description can reference 'negation' and the
  6453. // matcher parameters.
  6454. TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
  6455. const Matcher<int> m1 = IsEven2();
  6456. EXPECT_EQ("is even", Describe(m1));
  6457. EXPECT_EQ("is odd", DescribeNegation(m1));
  6458. const Matcher<int> m2 = EqSumOf(5, 9);
  6459. EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
  6460. EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
  6461. }
  6462. // Tests explaining match result in a MATCHER* macro.
  6463. TEST(MatcherMacroTest, CanExplainMatchResult) {
  6464. const Matcher<int> m1 = IsEven2();
  6465. EXPECT_EQ("OK", Explain(m1, 4));
  6466. EXPECT_EQ("% 2 == 1", Explain(m1, 5));
  6467. const Matcher<int> m2 = EqSumOf(1, 2);
  6468. EXPECT_EQ("OK", Explain(m2, 3));
  6469. EXPECT_EQ("diff == -1", Explain(m2, 4));
  6470. }
  6471. // Tests that the body of MATCHER() can reference the type of the
  6472. // value being matched.
  6473. MATCHER(IsEmptyString, "") {
  6474. StaticAssertTypeEq<::std::string, arg_type>();
  6475. return arg.empty();
  6476. }
  6477. MATCHER(IsEmptyStringByRef, "") {
  6478. StaticAssertTypeEq<const ::std::string&, arg_type>();
  6479. return arg.empty();
  6480. }
  6481. TEST(MatcherMacroTest, CanReferenceArgType) {
  6482. const Matcher<::std::string> m1 = IsEmptyString();
  6483. EXPECT_TRUE(m1.Matches(""));
  6484. const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
  6485. EXPECT_TRUE(m2.Matches(""));
  6486. }
  6487. // Tests that MATCHER() can be used in a namespace.
  6488. namespace matcher_test {
  6489. MATCHER(IsOdd, "") { return (arg % 2) != 0; }
  6490. } // namespace matcher_test
  6491. TEST(MatcherMacroTest, WorksInNamespace) {
  6492. Matcher<int> m = matcher_test::IsOdd();
  6493. EXPECT_FALSE(m.Matches(4));
  6494. EXPECT_TRUE(m.Matches(5));
  6495. }
  6496. // Tests that Value() can be used to compose matchers.
  6497. MATCHER(IsPositiveOdd, "") {
  6498. return Value(arg, matcher_test::IsOdd()) && arg > 0;
  6499. }
  6500. TEST(MatcherMacroTest, CanBeComposedUsingValue) {
  6501. EXPECT_THAT(3, IsPositiveOdd());
  6502. EXPECT_THAT(4, Not(IsPositiveOdd()));
  6503. EXPECT_THAT(-1, Not(IsPositiveOdd()));
  6504. }
  6505. // Tests that a simple MATCHER_P() definition works.
  6506. MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
  6507. TEST(MatcherPMacroTest, Works) {
  6508. const Matcher<int> m = IsGreaterThan32And(5);
  6509. EXPECT_TRUE(m.Matches(36));
  6510. EXPECT_FALSE(m.Matches(5));
  6511. EXPECT_EQ("is greater than 32 and 5", Describe(m));
  6512. EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
  6513. EXPECT_EQ("", Explain(m, 36));
  6514. EXPECT_EQ("", Explain(m, 5));
  6515. }
  6516. // Tests that the description is calculated correctly from the matcher name.
  6517. MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
  6518. TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
  6519. const Matcher<int> m = _is_Greater_Than32and_(5);
  6520. EXPECT_EQ("is greater than 32 and 5", Describe(m));
  6521. EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
  6522. EXPECT_EQ("", Explain(m, 36));
  6523. EXPECT_EQ("", Explain(m, 5));
  6524. }
  6525. // Tests that a MATCHER_P matcher can be explicitly instantiated with
  6526. // a reference parameter type.
  6527. class UncopyableFoo {
  6528. public:
  6529. explicit UncopyableFoo(char value) : value_(value) { (void)value_; }
  6530. UncopyableFoo(const UncopyableFoo&) = delete;
  6531. void operator=(const UncopyableFoo&) = delete;
  6532. private:
  6533. char value_;
  6534. };
  6535. MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
  6536. TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
  6537. UncopyableFoo foo1('1'), foo2('2');
  6538. const Matcher<const UncopyableFoo&> m =
  6539. ReferencesUncopyable<const UncopyableFoo&>(foo1);
  6540. EXPECT_TRUE(m.Matches(foo1));
  6541. EXPECT_FALSE(m.Matches(foo2));
  6542. // We don't want the address of the parameter printed, as most
  6543. // likely it will just annoy the user. If the address is
  6544. // interesting, the user should consider passing the parameter by
  6545. // pointer instead.
  6546. EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m));
  6547. }
  6548. // Tests that the body of MATCHER_Pn() can reference the parameter
  6549. // types.
  6550. MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
  6551. StaticAssertTypeEq<int, foo_type>();
  6552. StaticAssertTypeEq<long, bar_type>(); // NOLINT
  6553. StaticAssertTypeEq<char, baz_type>();
  6554. return arg == 0;
  6555. }
  6556. TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
  6557. EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
  6558. }
  6559. // Tests that a MATCHER_Pn matcher can be explicitly instantiated with
  6560. // reference parameter types.
  6561. MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
  6562. return &arg == &variable1 || &arg == &variable2;
  6563. }
  6564. TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
  6565. UncopyableFoo foo1('1'), foo2('2'), foo3('3');
  6566. const Matcher<const UncopyableFoo&> const_m =
  6567. ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
  6568. EXPECT_TRUE(const_m.Matches(foo1));
  6569. EXPECT_TRUE(const_m.Matches(foo2));
  6570. EXPECT_FALSE(const_m.Matches(foo3));
  6571. const Matcher<UncopyableFoo&> m =
  6572. ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);
  6573. EXPECT_TRUE(m.Matches(foo1));
  6574. EXPECT_TRUE(m.Matches(foo2));
  6575. EXPECT_FALSE(m.Matches(foo3));
  6576. }
  6577. TEST(MatcherPnMacroTest,
  6578. GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
  6579. UncopyableFoo foo1('1'), foo2('2');
  6580. const Matcher<const UncopyableFoo&> m =
  6581. ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
  6582. // We don't want the addresses of the parameters printed, as most
  6583. // likely they will just annoy the user. If the addresses are
  6584. // interesting, the user should consider passing the parameters by
  6585. // pointers instead.
  6586. EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
  6587. Describe(m));
  6588. }
  6589. // Tests that a simple MATCHER_P2() definition works.
  6590. MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
  6591. TEST(MatcherPnMacroTest, Works) {
  6592. const Matcher<const long&> m = IsNotInClosedRange(10, 20); // NOLINT
  6593. EXPECT_TRUE(m.Matches(36L));
  6594. EXPECT_FALSE(m.Matches(15L));
  6595. EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
  6596. EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
  6597. EXPECT_EQ("", Explain(m, 36L));
  6598. EXPECT_EQ("", Explain(m, 15L));
  6599. }
  6600. // Tests that MATCHER*() definitions can be overloaded on the number
  6601. // of parameters; also tests MATCHER_Pn() where n >= 3.
  6602. MATCHER(EqualsSumOf, "") { return arg == 0; }
  6603. MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
  6604. MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
  6605. MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
  6606. MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
  6607. MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
  6608. MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
  6609. return arg == a + b + c + d + e + f;
  6610. }
  6611. MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
  6612. return arg == a + b + c + d + e + f + g;
  6613. }
  6614. MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
  6615. return arg == a + b + c + d + e + f + g + h;
  6616. }
  6617. MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
  6618. return arg == a + b + c + d + e + f + g + h + i;
  6619. }
  6620. MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
  6621. return arg == a + b + c + d + e + f + g + h + i + j;
  6622. }
  6623. TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
  6624. EXPECT_THAT(0, EqualsSumOf());
  6625. EXPECT_THAT(1, EqualsSumOf(1));
  6626. EXPECT_THAT(12, EqualsSumOf(10, 2));
  6627. EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
  6628. EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
  6629. EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
  6630. EXPECT_THAT("abcdef",
  6631. EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
  6632. EXPECT_THAT("abcdefg",
  6633. EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
  6634. EXPECT_THAT("abcdefgh", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
  6635. 'f', 'g', "h"));
  6636. EXPECT_THAT("abcdefghi", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
  6637. 'f', 'g', "h", 'i'));
  6638. EXPECT_THAT("abcdefghij",
  6639. EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', "h",
  6640. 'i', ::std::string("j")));
  6641. EXPECT_THAT(1, Not(EqualsSumOf()));
  6642. EXPECT_THAT(-1, Not(EqualsSumOf(1)));
  6643. EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
  6644. EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
  6645. EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
  6646. EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
  6647. EXPECT_THAT("abcdef ",
  6648. Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
  6649. EXPECT_THAT("abcdefg ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
  6650. "e", 'f', 'g')));
  6651. EXPECT_THAT("abcdefgh ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
  6652. "e", 'f', 'g', "h")));
  6653. EXPECT_THAT("abcdefghi ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
  6654. "e", 'f', 'g', "h", 'i')));
  6655. EXPECT_THAT("abcdefghij ",
  6656. Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
  6657. "h", 'i', ::std::string("j"))));
  6658. }
  6659. // Tests that a MATCHER_Pn() definition can be instantiated with any
  6660. // compatible parameter types.
  6661. TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
  6662. EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
  6663. EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
  6664. EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
  6665. EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
  6666. }
  6667. // Tests that the matcher body can promote the parameter types.
  6668. MATCHER_P2(EqConcat, prefix, suffix, "") {
  6669. // The following lines promote the two parameters to desired types.
  6670. std::string prefix_str(prefix);
  6671. char suffix_char = static_cast<char>(suffix);
  6672. return arg == prefix_str + suffix_char;
  6673. }
  6674. TEST(MatcherPnMacroTest, SimpleTypePromotion) {
  6675. Matcher<std::string> no_promo = EqConcat(std::string("foo"), 't');
  6676. Matcher<const std::string&> promo = EqConcat("foo", static_cast<int>('t'));
  6677. EXPECT_FALSE(no_promo.Matches("fool"));
  6678. EXPECT_FALSE(promo.Matches("fool"));
  6679. EXPECT_TRUE(no_promo.Matches("foot"));
  6680. EXPECT_TRUE(promo.Matches("foot"));
  6681. }
  6682. // Verifies the type of a MATCHER*.
  6683. TEST(MatcherPnMacroTest, TypesAreCorrect) {
  6684. // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
  6685. EqualsSumOfMatcher a0 = EqualsSumOf();
  6686. // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
  6687. EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
  6688. // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
  6689. // variable, and so on.
  6690. EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
  6691. EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
  6692. EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
  6693. EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
  6694. EqualsSumOf(1, 2, 3, 4, '5');
  6695. EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
  6696. EqualsSumOf(1, 2, 3, 4, 5, '6');
  6697. EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
  6698. EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
  6699. EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
  6700. EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
  6701. EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
  6702. EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
  6703. EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
  6704. EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
  6705. // Avoid "unused variable" warnings.
  6706. (void)a0;
  6707. (void)a1;
  6708. (void)a2;
  6709. (void)a3;
  6710. (void)a4;
  6711. (void)a5;
  6712. (void)a6;
  6713. (void)a7;
  6714. (void)a8;
  6715. (void)a9;
  6716. (void)a10;
  6717. }
  6718. // Tests that matcher-typed parameters can be used in Value() inside a
  6719. // MATCHER_Pn definition.
  6720. // Succeeds if arg matches exactly 2 of the 3 matchers.
  6721. MATCHER_P3(TwoOf, m1, m2, m3, "") {
  6722. const int count = static_cast<int>(Value(arg, m1)) +
  6723. static_cast<int>(Value(arg, m2)) +
  6724. static_cast<int>(Value(arg, m3));
  6725. return count == 2;
  6726. }
  6727. TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
  6728. EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
  6729. EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
  6730. }
  6731. // Tests Contains().
  6732. TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
  6733. list<int> some_list;
  6734. some_list.push_back(3);
  6735. some_list.push_back(1);
  6736. some_list.push_back(2);
  6737. EXPECT_THAT(some_list, Contains(1));
  6738. EXPECT_THAT(some_list, Contains(Gt(2.5)));
  6739. EXPECT_THAT(some_list, Contains(Eq(2.0f)));
  6740. list<std::string> another_list;
  6741. another_list.push_back("fee");
  6742. another_list.push_back("fie");
  6743. another_list.push_back("foe");
  6744. another_list.push_back("fum");
  6745. EXPECT_THAT(another_list, Contains(std::string("fee")));
  6746. }
  6747. TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
  6748. list<int> some_list;
  6749. some_list.push_back(3);
  6750. some_list.push_back(1);
  6751. EXPECT_THAT(some_list, Not(Contains(4)));
  6752. }
  6753. TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
  6754. set<int> some_set;
  6755. some_set.insert(3);
  6756. some_set.insert(1);
  6757. some_set.insert(2);
  6758. EXPECT_THAT(some_set, Contains(Eq(1.0)));
  6759. EXPECT_THAT(some_set, Contains(Eq(3.0f)));
  6760. EXPECT_THAT(some_set, Contains(2));
  6761. set<std::string> another_set;
  6762. another_set.insert("fee");
  6763. another_set.insert("fie");
  6764. another_set.insert("foe");
  6765. another_set.insert("fum");
  6766. EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
  6767. }
  6768. TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
  6769. set<int> some_set;
  6770. some_set.insert(3);
  6771. some_set.insert(1);
  6772. EXPECT_THAT(some_set, Not(Contains(4)));
  6773. set<std::string> c_string_set;
  6774. c_string_set.insert("hello");
  6775. EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
  6776. }
  6777. TEST(ContainsTest, ExplainsMatchResultCorrectly) {
  6778. const int a[2] = {1, 2};
  6779. Matcher<const int(&)[2]> m = Contains(2);
  6780. EXPECT_EQ("whose element #1 matches", Explain(m, a));
  6781. m = Contains(3);
  6782. EXPECT_EQ("", Explain(m, a));
  6783. m = Contains(GreaterThan(0));
  6784. EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
  6785. m = Contains(GreaterThan(10));
  6786. EXPECT_EQ("", Explain(m, a));
  6787. }
  6788. TEST(ContainsTest, DescribesItselfCorrectly) {
  6789. Matcher<vector<int>> m = Contains(1);
  6790. EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
  6791. Matcher<vector<int>> m2 = Not(m);
  6792. EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
  6793. }
  6794. TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
  6795. map<std::string, int> my_map;
  6796. const char* bar = "a string";
  6797. my_map[bar] = 2;
  6798. EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
  6799. map<std::string, int> another_map;
  6800. another_map["fee"] = 1;
  6801. another_map["fie"] = 2;
  6802. another_map["foe"] = 3;
  6803. another_map["fum"] = 4;
  6804. EXPECT_THAT(another_map,
  6805. Contains(pair<const std::string, int>(std::string("fee"), 1)));
  6806. EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
  6807. }
  6808. TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
  6809. map<int, int> some_map;
  6810. some_map[1] = 11;
  6811. some_map[2] = 22;
  6812. EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
  6813. }
  6814. TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
  6815. const char* string_array[] = {"fee", "fie", "foe", "fum"};
  6816. EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
  6817. }
  6818. TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
  6819. int int_array[] = {1, 2, 3, 4};
  6820. EXPECT_THAT(int_array, Not(Contains(5)));
  6821. }
  6822. TEST(ContainsTest, AcceptsMatcher) {
  6823. const int a[] = {1, 2, 3};
  6824. EXPECT_THAT(a, Contains(Gt(2)));
  6825. EXPECT_THAT(a, Not(Contains(Gt(4))));
  6826. }
  6827. TEST(ContainsTest, WorksForNativeArrayAsTuple) {
  6828. const int a[] = {1, 2};
  6829. const int* const pointer = a;
  6830. EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
  6831. EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
  6832. }
  6833. TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
  6834. int a[][3] = {{1, 2, 3}, {4, 5, 6}};
  6835. EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
  6836. EXPECT_THAT(a, Contains(Contains(5)));
  6837. EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
  6838. EXPECT_THAT(a, Contains(Not(Contains(5))));
  6839. }
  6840. TEST(AllOfArrayTest, BasicForms) {
  6841. // Iterator
  6842. std::vector<int> v0{};
  6843. std::vector<int> v1{1};
  6844. std::vector<int> v2{2, 3};
  6845. std::vector<int> v3{4, 4, 4};
  6846. EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));
  6847. EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));
  6848. EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
  6849. EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
  6850. EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));
  6851. // Pointer + size
  6852. int ar[6] = {1, 2, 3, 4, 4, 4};
  6853. EXPECT_THAT(0, AllOfArray(ar, 0));
  6854. EXPECT_THAT(1, AllOfArray(ar, 1));
  6855. EXPECT_THAT(2, Not(AllOfArray(ar, 1)));
  6856. EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));
  6857. EXPECT_THAT(4, AllOfArray(ar + 3, 3));
  6858. // Array
  6859. // int ar0[0]; Not usable
  6860. int ar1[1] = {1};
  6861. int ar2[2] = {2, 3};
  6862. int ar3[3] = {4, 4, 4};
  6863. // EXPECT_THAT(0, Not(AllOfArray(ar0))); // Cannot work
  6864. EXPECT_THAT(1, AllOfArray(ar1));
  6865. EXPECT_THAT(2, Not(AllOfArray(ar1)));
  6866. EXPECT_THAT(3, Not(AllOfArray(ar2)));
  6867. EXPECT_THAT(4, AllOfArray(ar3));
  6868. // Container
  6869. EXPECT_THAT(0, AllOfArray(v0));
  6870. EXPECT_THAT(1, AllOfArray(v1));
  6871. EXPECT_THAT(2, Not(AllOfArray(v1)));
  6872. EXPECT_THAT(3, Not(AllOfArray(v2)));
  6873. EXPECT_THAT(4, AllOfArray(v3));
  6874. // Initializer
  6875. EXPECT_THAT(0, AllOfArray<int>({})); // Requires template arg.
  6876. EXPECT_THAT(1, AllOfArray({1}));
  6877. EXPECT_THAT(2, Not(AllOfArray({1})));
  6878. EXPECT_THAT(3, Not(AllOfArray({2, 3})));
  6879. EXPECT_THAT(4, AllOfArray({4, 4, 4}));
  6880. }
  6881. TEST(AllOfArrayTest, Matchers) {
  6882. // vector
  6883. std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
  6884. EXPECT_THAT(0, Not(AllOfArray(matchers)));
  6885. EXPECT_THAT(1, AllOfArray(matchers));
  6886. EXPECT_THAT(2, Not(AllOfArray(matchers)));
  6887. // initializer_list
  6888. EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));
  6889. EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));
  6890. }
  6891. TEST(AnyOfArrayTest, BasicForms) {
  6892. // Iterator
  6893. std::vector<int> v0{};
  6894. std::vector<int> v1{1};
  6895. std::vector<int> v2{2, 3};
  6896. EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));
  6897. EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));
  6898. EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
  6899. EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));
  6900. EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
  6901. // Pointer + size
  6902. int ar[3] = {1, 2, 3};
  6903. EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));
  6904. EXPECT_THAT(1, AnyOfArray(ar, 1));
  6905. EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));
  6906. EXPECT_THAT(3, AnyOfArray(ar + 1, 2));
  6907. EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));
  6908. // Array
  6909. // int ar0[0]; Not usable
  6910. int ar1[1] = {1};
  6911. int ar2[2] = {2, 3};
  6912. // EXPECT_THAT(0, Not(AnyOfArray(ar0))); // Cannot work
  6913. EXPECT_THAT(1, AnyOfArray(ar1));
  6914. EXPECT_THAT(2, Not(AnyOfArray(ar1)));
  6915. EXPECT_THAT(3, AnyOfArray(ar2));
  6916. EXPECT_THAT(4, Not(AnyOfArray(ar2)));
  6917. // Container
  6918. EXPECT_THAT(0, Not(AnyOfArray(v0)));
  6919. EXPECT_THAT(1, AnyOfArray(v1));
  6920. EXPECT_THAT(2, Not(AnyOfArray(v1)));
  6921. EXPECT_THAT(3, AnyOfArray(v2));
  6922. EXPECT_THAT(4, Not(AnyOfArray(v2)));
  6923. // Initializer
  6924. EXPECT_THAT(0, Not(AnyOfArray<int>({}))); // Requires template arg.
  6925. EXPECT_THAT(1, AnyOfArray({1}));
  6926. EXPECT_THAT(2, Not(AnyOfArray({1})));
  6927. EXPECT_THAT(3, AnyOfArray({2, 3}));
  6928. EXPECT_THAT(4, Not(AnyOfArray({2, 3})));
  6929. }
  6930. TEST(AnyOfArrayTest, Matchers) {
  6931. // We negate test AllOfArrayTest.Matchers.
  6932. // vector
  6933. std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
  6934. EXPECT_THAT(0, AnyOfArray(matchers));
  6935. EXPECT_THAT(1, Not(AnyOfArray(matchers)));
  6936. EXPECT_THAT(2, AnyOfArray(matchers));
  6937. // initializer_list
  6938. EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));
  6939. EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));
  6940. }
  6941. TEST(AnyOfArrayTest, ExplainsMatchResultCorrectly) {
  6942. // AnyOfArray and AllOfArry use the same underlying template-template,
  6943. // thus it is sufficient to test one here.
  6944. const std::vector<int> v0{};
  6945. const std::vector<int> v1{1};
  6946. const std::vector<int> v2{2, 3};
  6947. const Matcher<int> m0 = AnyOfArray(v0);
  6948. const Matcher<int> m1 = AnyOfArray(v1);
  6949. const Matcher<int> m2 = AnyOfArray(v2);
  6950. EXPECT_EQ("", Explain(m0, 0));
  6951. EXPECT_EQ("", Explain(m1, 1));
  6952. EXPECT_EQ("", Explain(m1, 2));
  6953. EXPECT_EQ("", Explain(m2, 3));
  6954. EXPECT_EQ("", Explain(m2, 4));
  6955. EXPECT_EQ("()", Describe(m0));
  6956. EXPECT_EQ("(is equal to 1)", Describe(m1));
  6957. EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
  6958. EXPECT_EQ("()", DescribeNegation(m0));
  6959. EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));
  6960. EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));
  6961. // Explain with matchers
  6962. const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
  6963. const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
  6964. // Explains the first positiv match and all prior negative matches...
  6965. EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));
  6966. EXPECT_EQ("which is the same as 1", Explain(g1, 1));
  6967. EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));
  6968. EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",
  6969. Explain(g2, 0));
  6970. EXPECT_EQ("which is the same as 1, and which is 1 less than 2",
  6971. Explain(g2, 1));
  6972. EXPECT_EQ("which is 1 more than 1", // Only the first
  6973. Explain(g2, 2));
  6974. }
  6975. TEST(AllOfTest, HugeMatcher) {
  6976. // Verify that using AllOf with many arguments doesn't cause
  6977. // the compiler to exceed template instantiation depth limit.
  6978. EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
  6979. testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
  6980. }
  6981. TEST(AnyOfTest, HugeMatcher) {
  6982. // Verify that using AnyOf with many arguments doesn't cause
  6983. // the compiler to exceed template instantiation depth limit.
  6984. EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
  6985. testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
  6986. }
  6987. namespace adl_test {
  6988. // Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
  6989. // don't issue unqualified recursive calls. If they do, the argument dependent
  6990. // name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
  6991. // as a candidate and the compilation will break due to an ambiguous overload.
  6992. // The matcher must be in the same namespace as AllOf/AnyOf to make argument
  6993. // dependent lookup find those.
  6994. MATCHER(M, "") {
  6995. (void)arg;
  6996. return true;
  6997. }
  6998. template <typename T1, typename T2>
  6999. bool AllOf(const T1& /*t1*/, const T2& /*t2*/) {
  7000. return true;
  7001. }
  7002. TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
  7003. EXPECT_THAT(42,
  7004. testing::AllOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
  7005. }
  7006. template <typename T1, typename T2>
  7007. bool AnyOf(const T1&, const T2&) {
  7008. return true;
  7009. }
  7010. TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
  7011. EXPECT_THAT(42,
  7012. testing::AnyOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
  7013. }
  7014. } // namespace adl_test
  7015. TEST(AllOfTest, WorksOnMoveOnlyType) {
  7016. std::unique_ptr<int> p(new int(3));
  7017. EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
  7018. EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
  7019. }
  7020. TEST(AnyOfTest, WorksOnMoveOnlyType) {
  7021. std::unique_ptr<int> p(new int(3));
  7022. EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
  7023. EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
  7024. }
  7025. MATCHER(IsNotNull, "") { return arg != nullptr; }
  7026. // Verifies that a matcher defined using MATCHER() can work on
  7027. // move-only types.
  7028. TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
  7029. std::unique_ptr<int> p(new int(3));
  7030. EXPECT_THAT(p, IsNotNull());
  7031. EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
  7032. }
  7033. MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }
  7034. // Verifies that a matcher defined using MATCHER_P*() can work on
  7035. // move-only types.
  7036. TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
  7037. std::unique_ptr<int> p(new int(3));
  7038. EXPECT_THAT(p, UniquePointee(3));
  7039. EXPECT_THAT(p, Not(UniquePointee(2)));
  7040. }
  7041. #if GTEST_HAS_EXCEPTIONS
  7042. // std::function<void()> is used below for compatibility with older copies of
  7043. // GCC. Normally, a raw lambda is all that is needed.
  7044. // Test that examples from documentation compile
  7045. TEST(ThrowsTest, Examples) {
  7046. EXPECT_THAT(
  7047. std::function<void()>([]() { throw std::runtime_error("message"); }),
  7048. Throws<std::runtime_error>());
  7049. EXPECT_THAT(
  7050. std::function<void()>([]() { throw std::runtime_error("message"); }),
  7051. ThrowsMessage<std::runtime_error>(HasSubstr("message")));
  7052. }
  7053. TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {
  7054. EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }),
  7055. Throws<std::exception>());
  7056. }
  7057. TEST(ThrowsTest, CallableExecutedExactlyOnce) {
  7058. size_t a = 0;
  7059. EXPECT_THAT(std::function<void()>([&a]() {
  7060. a++;
  7061. throw 10;
  7062. }),
  7063. Throws<int>());
  7064. EXPECT_EQ(a, 1u);
  7065. EXPECT_THAT(std::function<void()>([&a]() {
  7066. a++;
  7067. throw std::runtime_error("message");
  7068. }),
  7069. Throws<std::runtime_error>());
  7070. EXPECT_EQ(a, 2u);
  7071. EXPECT_THAT(std::function<void()>([&a]() {
  7072. a++;
  7073. throw std::runtime_error("message");
  7074. }),
  7075. ThrowsMessage<std::runtime_error>(HasSubstr("message")));
  7076. EXPECT_EQ(a, 3u);
  7077. EXPECT_THAT(std::function<void()>([&a]() {
  7078. a++;
  7079. throw std::runtime_error("message");
  7080. }),
  7081. Throws<std::runtime_error>(
  7082. Property(&std::runtime_error::what, HasSubstr("message"))));
  7083. EXPECT_EQ(a, 4u);
  7084. }
  7085. TEST(ThrowsTest, Describe) {
  7086. Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
  7087. std::stringstream ss;
  7088. matcher.DescribeTo(&ss);
  7089. auto explanation = ss.str();
  7090. EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
  7091. }
  7092. TEST(ThrowsTest, Success) {
  7093. Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
  7094. StringMatchResultListener listener;
  7095. EXPECT_TRUE(matcher.MatchAndExplain(
  7096. []() { throw std::runtime_error("error message"); }, &listener));
  7097. EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
  7098. }
  7099. TEST(ThrowsTest, FailWrongType) {
  7100. Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
  7101. StringMatchResultListener listener;
  7102. EXPECT_FALSE(matcher.MatchAndExplain(
  7103. []() { throw std::logic_error("error message"); }, &listener));
  7104. EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
  7105. EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
  7106. }
  7107. TEST(ThrowsTest, FailWrongTypeNonStd) {
  7108. Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
  7109. StringMatchResultListener listener;
  7110. EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
  7111. EXPECT_THAT(listener.str(),
  7112. HasSubstr("throws an exception of an unknown type"));
  7113. }
  7114. TEST(ThrowsTest, FailNoThrow) {
  7115. Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
  7116. StringMatchResultListener listener;
  7117. EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener));
  7118. EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
  7119. }
  7120. class ThrowsPredicateTest
  7121. : public TestWithParam<Matcher<std::function<void()>>> {};
  7122. TEST_P(ThrowsPredicateTest, Describe) {
  7123. Matcher<std::function<void()>> matcher = GetParam();
  7124. std::stringstream ss;
  7125. matcher.DescribeTo(&ss);
  7126. auto explanation = ss.str();
  7127. EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
  7128. EXPECT_THAT(explanation, HasSubstr("error message"));
  7129. }
  7130. TEST_P(ThrowsPredicateTest, Success) {
  7131. Matcher<std::function<void()>> matcher = GetParam();
  7132. StringMatchResultListener listener;
  7133. EXPECT_TRUE(matcher.MatchAndExplain(
  7134. []() { throw std::runtime_error("error message"); }, &listener));
  7135. EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
  7136. }
  7137. TEST_P(ThrowsPredicateTest, FailWrongType) {
  7138. Matcher<std::function<void()>> matcher = GetParam();
  7139. StringMatchResultListener listener;
  7140. EXPECT_FALSE(matcher.MatchAndExplain(
  7141. []() { throw std::logic_error("error message"); }, &listener));
  7142. EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
  7143. EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
  7144. }
  7145. TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {
  7146. Matcher<std::function<void()>> matcher = GetParam();
  7147. StringMatchResultListener listener;
  7148. EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
  7149. EXPECT_THAT(listener.str(),
  7150. HasSubstr("throws an exception of an unknown type"));
  7151. }
  7152. TEST_P(ThrowsPredicateTest, FailWrongMessage) {
  7153. Matcher<std::function<void()>> matcher = GetParam();
  7154. StringMatchResultListener listener;
  7155. EXPECT_FALSE(matcher.MatchAndExplain(
  7156. []() { throw std::runtime_error("wrong message"); }, &listener));
  7157. EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
  7158. EXPECT_THAT(listener.str(), Not(HasSubstr("wrong message")));
  7159. }
  7160. TEST_P(ThrowsPredicateTest, FailNoThrow) {
  7161. Matcher<std::function<void()>> matcher = GetParam();
  7162. StringMatchResultListener listener;
  7163. EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener));
  7164. EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
  7165. }
  7166. INSTANTIATE_TEST_SUITE_P(
  7167. AllMessagePredicates, ThrowsPredicateTest,
  7168. Values(Matcher<std::function<void()>>(
  7169. ThrowsMessage<std::runtime_error>(HasSubstr("error message")))));
  7170. // Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&.
  7171. TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {
  7172. {
  7173. Matcher<std::function<void()>> matcher =
  7174. ThrowsMessage<std::runtime_error>(HasSubstr("error message"));
  7175. EXPECT_TRUE(
  7176. matcher.Matches([]() { throw std::runtime_error("error message"); }));
  7177. EXPECT_FALSE(
  7178. matcher.Matches([]() { throw std::runtime_error("wrong message"); }));
  7179. }
  7180. {
  7181. Matcher<uint64_t> inner = Eq(10);
  7182. Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);
  7183. EXPECT_TRUE(matcher.Matches([]() { throw(uint32_t) 10; }));
  7184. EXPECT_FALSE(matcher.Matches([]() { throw(uint32_t) 11; }));
  7185. }
  7186. }
  7187. // Tests that ThrowsMessage("message") is equivalent
  7188. // to ThrowsMessage(Eq<std::string>("message")).
  7189. TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
  7190. Matcher<std::function<void()>> matcher =
  7191. ThrowsMessage<std::runtime_error>("error message");
  7192. EXPECT_TRUE(
  7193. matcher.Matches([]() { throw std::runtime_error("error message"); }));
  7194. EXPECT_FALSE(matcher.Matches(
  7195. []() { throw std::runtime_error("wrong error message"); }));
  7196. }
  7197. #endif // GTEST_HAS_EXCEPTIONS
  7198. } // namespace
  7199. } // namespace gmock_matchers_test
  7200. } // namespace testing
  7201. #ifdef _MSC_VER
  7202. # pragma warning(pop)
  7203. #endif