gmock-matchers_test.cc 281 KB

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