gmock-matchers_test.cc 218 KB

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