gmock-matchers_test.cc 224 KB

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