gmock.h 444 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645
  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 is the main header file a user should include.
  32. // GOOGLETEST_CM0002 DO NOT DELETE
  33. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
  34. #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
  35. // This file implements the following syntax:
  36. //
  37. // ON_CALL(mock_object, Method(...))
  38. // .With(...) ?
  39. // .WillByDefault(...);
  40. //
  41. // where With() is optional and WillByDefault() must appear exactly
  42. // once.
  43. //
  44. // EXPECT_CALL(mock_object, Method(...))
  45. // .With(...) ?
  46. // .Times(...) ?
  47. // .InSequence(...) *
  48. // .WillOnce(...) *
  49. // .WillRepeatedly(...) ?
  50. // .RetiresOnSaturation() ? ;
  51. //
  52. // where all clauses are optional and WillOnce() can be repeated.
  53. // Copyright 2007, Google Inc.
  54. // All rights reserved.
  55. //
  56. // Redistribution and use in source and binary forms, with or without
  57. // modification, are permitted provided that the following conditions are
  58. // met:
  59. //
  60. // * Redistributions of source code must retain the above copyright
  61. // notice, this list of conditions and the following disclaimer.
  62. // * Redistributions in binary form must reproduce the above
  63. // copyright notice, this list of conditions and the following disclaimer
  64. // in the documentation and/or other materials provided with the
  65. // distribution.
  66. // * Neither the name of Google Inc. nor the names of its
  67. // contributors may be used to endorse or promote products derived from
  68. // this software without specific prior written permission.
  69. //
  70. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  71. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  72. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  73. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  74. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  75. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  76. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  77. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  78. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  79. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  80. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  81. // Google Mock - a framework for writing C++ mock classes.
  82. //
  83. // The ACTION* family of macros can be used in a namespace scope to
  84. // define custom actions easily. The syntax:
  85. //
  86. // ACTION(name) { statements; }
  87. //
  88. // will define an action with the given name that executes the
  89. // statements. The value returned by the statements will be used as
  90. // the return value of the action. Inside the statements, you can
  91. // refer to the K-th (0-based) argument of the mock function by
  92. // 'argK', and refer to its type by 'argK_type'. For example:
  93. //
  94. // ACTION(IncrementArg1) {
  95. // arg1_type temp = arg1;
  96. // return ++(*temp);
  97. // }
  98. //
  99. // allows you to write
  100. //
  101. // ...WillOnce(IncrementArg1());
  102. //
  103. // You can also refer to the entire argument tuple and its type by
  104. // 'args' and 'args_type', and refer to the mock function type and its
  105. // return type by 'function_type' and 'return_type'.
  106. //
  107. // Note that you don't need to specify the types of the mock function
  108. // arguments. However rest assured that your code is still type-safe:
  109. // you'll get a compiler error if *arg1 doesn't support the ++
  110. // operator, or if the type of ++(*arg1) isn't compatible with the
  111. // mock function's return type, for example.
  112. //
  113. // Sometimes you'll want to parameterize the action. For that you can use
  114. // another macro:
  115. //
  116. // ACTION_P(name, param_name) { statements; }
  117. //
  118. // For example:
  119. //
  120. // ACTION_P(Add, n) { return arg0 + n; }
  121. //
  122. // will allow you to write:
  123. //
  124. // ...WillOnce(Add(5));
  125. //
  126. // Note that you don't need to provide the type of the parameter
  127. // either. If you need to reference the type of a parameter named
  128. // 'foo', you can write 'foo_type'. For example, in the body of
  129. // ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
  130. // of 'n'.
  131. //
  132. // We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
  133. // multi-parameter actions.
  134. //
  135. // For the purpose of typing, you can view
  136. //
  137. // ACTION_Pk(Foo, p1, ..., pk) { ... }
  138. //
  139. // as shorthand for
  140. //
  141. // template <typename p1_type, ..., typename pk_type>
  142. // FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
  143. //
  144. // In particular, you can provide the template type arguments
  145. // explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
  146. // although usually you can rely on the compiler to infer the types
  147. // for you automatically. You can assign the result of expression
  148. // Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
  149. // pk_type>. This can be useful when composing actions.
  150. //
  151. // You can also overload actions with different numbers of parameters:
  152. //
  153. // ACTION_P(Plus, a) { ... }
  154. // ACTION_P2(Plus, a, b) { ... }
  155. //
  156. // While it's tempting to always use the ACTION* macros when defining
  157. // a new action, you should also consider implementing ActionInterface
  158. // or using MakePolymorphicAction() instead, especially if you need to
  159. // use the action a lot. While these approaches require more work,
  160. // they give you more control on the types of the mock function
  161. // arguments and the action parameters, which in general leads to
  162. // better compiler error messages that pay off in the long run. They
  163. // also allow overloading actions based on parameter types (as opposed
  164. // to just based on the number of parameters).
  165. //
  166. // CAVEAT:
  167. //
  168. // ACTION*() can only be used in a namespace scope as templates cannot be
  169. // declared inside of a local class.
  170. // Users can, however, define any local functors (e.g. a lambda) that
  171. // can be used as actions.
  172. //
  173. // MORE INFORMATION:
  174. //
  175. // To learn more about using these macros, please search for 'ACTION' on
  176. // https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
  177. // GOOGLETEST_CM0002 DO NOT DELETE
  178. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
  179. #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
  180. #ifndef _WIN32_WCE
  181. # include <errno.h>
  182. #endif
  183. #include <algorithm>
  184. #include <functional>
  185. #include <memory>
  186. #include <string>
  187. #include <tuple>
  188. #include <type_traits>
  189. #include <utility>
  190. // Copyright 2007, Google Inc.
  191. // All rights reserved.
  192. //
  193. // Redistribution and use in source and binary forms, with or without
  194. // modification, are permitted provided that the following conditions are
  195. // met:
  196. //
  197. // * Redistributions of source code must retain the above copyright
  198. // notice, this list of conditions and the following disclaimer.
  199. // * Redistributions in binary form must reproduce the above
  200. // copyright notice, this list of conditions and the following disclaimer
  201. // in the documentation and/or other materials provided with the
  202. // distribution.
  203. // * Neither the name of Google Inc. nor the names of its
  204. // contributors may be used to endorse or promote products derived from
  205. // this software without specific prior written permission.
  206. //
  207. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  208. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  209. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  210. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  211. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  212. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  213. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  214. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  215. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  216. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  217. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  218. // Google Mock - a framework for writing C++ mock classes.
  219. //
  220. // This file defines some utilities useful for implementing Google
  221. // Mock. They are subject to change without notice, so please DO NOT
  222. // USE THEM IN USER CODE.
  223. // GOOGLETEST_CM0002 DO NOT DELETE
  224. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
  225. #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
  226. #include <stdio.h>
  227. #include <ostream> // NOLINT
  228. #include <string>
  229. #include <type_traits>
  230. // Copyright 2008, Google Inc.
  231. // All rights reserved.
  232. //
  233. // Redistribution and use in source and binary forms, with or without
  234. // modification, are permitted provided that the following conditions are
  235. // met:
  236. //
  237. // * Redistributions of source code must retain the above copyright
  238. // notice, this list of conditions and the following disclaimer.
  239. // * Redistributions in binary form must reproduce the above
  240. // copyright notice, this list of conditions and the following disclaimer
  241. // in the documentation and/or other materials provided with the
  242. // distribution.
  243. // * Neither the name of Google Inc. nor the names of its
  244. // contributors may be used to endorse or promote products derived from
  245. // this software without specific prior written permission.
  246. //
  247. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  248. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  249. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  250. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  251. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  252. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  253. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  254. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  255. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  256. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  257. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  258. //
  259. // Low-level types and utilities for porting Google Mock to various
  260. // platforms. All macros ending with _ and symbols defined in an
  261. // internal namespace are subject to change without notice. Code
  262. // outside Google Mock MUST NOT USE THEM DIRECTLY. Macros that don't
  263. // end with _ are part of Google Mock's public API and can be used by
  264. // code outside Google Mock.
  265. // GOOGLETEST_CM0002 DO NOT DELETE
  266. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
  267. #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
  268. #include <assert.h>
  269. #include <stdlib.h>
  270. #include <cstdint>
  271. #include <iostream>
  272. // Most of the utilities needed for porting Google Mock are also
  273. // required for Google Test and are defined in gtest-port.h.
  274. //
  275. // Note to maintainers: to reduce code duplication, prefer adding
  276. // portability utilities to Google Test's gtest-port.h instead of
  277. // here, as Google Mock depends on Google Test. Only add a utility
  278. // here if it's truly specific to Google Mock.
  279. #include "gtest/gtest.h"
  280. // Copyright 2015, Google Inc.
  281. // All rights reserved.
  282. //
  283. // Redistribution and use in source and binary forms, with or without
  284. // modification, are permitted provided that the following conditions are
  285. // met:
  286. //
  287. // * Redistributions of source code must retain the above copyright
  288. // notice, this list of conditions and the following disclaimer.
  289. // * Redistributions in binary form must reproduce the above
  290. // copyright notice, this list of conditions and the following disclaimer
  291. // in the documentation and/or other materials provided with the
  292. // distribution.
  293. // * Neither the name of Google Inc. nor the names of its
  294. // contributors may be used to endorse or promote products derived from
  295. // this software without specific prior written permission.
  296. //
  297. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  298. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  299. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  300. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  301. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  302. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  303. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  304. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  305. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  306. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  307. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  308. //
  309. // Injection point for custom user configurations. See README for details
  310. //
  311. // ** Custom implementation starts here **
  312. // GOOGLETEST_CM0002 DO NOT DELETE
  313. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
  314. #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
  315. #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
  316. // For MS Visual C++, check the compiler version. At least VS 2015 is
  317. // required to compile Google Mock.
  318. #if defined(_MSC_VER) && _MSC_VER < 1900
  319. # error "At least Visual C++ 2015 (14.0) is required to compile Google Mock."
  320. #endif
  321. // Macro for referencing flags. This is public as we want the user to
  322. // use this syntax to reference Google Mock flags.
  323. #define GMOCK_FLAG(name) FLAGS_gmock_##name
  324. #if !defined(GMOCK_DECLARE_bool_)
  325. // Macros for declaring flags.
  326. # define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name)
  327. # define GMOCK_DECLARE_int32_(name) extern GTEST_API_ int32_t GMOCK_FLAG(name)
  328. # define GMOCK_DECLARE_string_(name) \
  329. extern GTEST_API_ ::std::string GMOCK_FLAG(name)
  330. // Macros for defining flags.
  331. # define GMOCK_DEFINE_bool_(name, default_val, doc) \
  332. GTEST_API_ bool GMOCK_FLAG(name) = (default_val)
  333. # define GMOCK_DEFINE_int32_(name, default_val, doc) \
  334. GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val)
  335. # define GMOCK_DEFINE_string_(name, default_val, doc) \
  336. GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val)
  337. #endif // !defined(GMOCK_DECLARE_bool_)
  338. #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
  339. namespace testing {
  340. template <typename>
  341. class Matcher;
  342. namespace internal {
  343. // Silence MSVC C4100 (unreferenced formal parameter) and
  344. // C4805('==': unsafe mix of type 'const int' and type 'const bool')
  345. #ifdef _MSC_VER
  346. # pragma warning(push)
  347. # pragma warning(disable:4100)
  348. # pragma warning(disable:4805)
  349. #endif
  350. // Joins a vector of strings as if they are fields of a tuple; returns
  351. // the joined string.
  352. GTEST_API_ std::string JoinAsTuple(const Strings& fields);
  353. // Converts an identifier name to a space-separated list of lower-case
  354. // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
  355. // treated as one word. For example, both "FooBar123" and
  356. // "foo_bar_123" are converted to "foo bar 123".
  357. GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
  358. // GetRawPointer(p) returns the raw pointer underlying p when p is a
  359. // smart pointer, or returns p itself when p is already a raw pointer.
  360. // The following default implementation is for the smart pointer case.
  361. template <typename Pointer>
  362. inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
  363. return p.get();
  364. }
  365. // This overloaded version is for the raw pointer case.
  366. template <typename Element>
  367. inline Element* GetRawPointer(Element* p) { return p; }
  368. // MSVC treats wchar_t as a native type usually, but treats it as the
  369. // same as unsigned short when the compiler option /Zc:wchar_t- is
  370. // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
  371. // is a native type.
  372. #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
  373. // wchar_t is a typedef.
  374. #else
  375. # define GMOCK_WCHAR_T_IS_NATIVE_ 1
  376. #endif
  377. // In what follows, we use the term "kind" to indicate whether a type
  378. // is bool, an integer type (excluding bool), a floating-point type,
  379. // or none of them. This categorization is useful for determining
  380. // when a matcher argument type can be safely converted to another
  381. // type in the implementation of SafeMatcherCast.
  382. enum TypeKind {
  383. kBool, kInteger, kFloatingPoint, kOther
  384. };
  385. // KindOf<T>::value is the kind of type T.
  386. template <typename T> struct KindOf {
  387. enum { value = kOther }; // The default kind.
  388. };
  389. // This macro declares that the kind of 'type' is 'kind'.
  390. #define GMOCK_DECLARE_KIND_(type, kind) \
  391. template <> struct KindOf<type> { enum { value = kind }; }
  392. GMOCK_DECLARE_KIND_(bool, kBool);
  393. // All standard integer types.
  394. GMOCK_DECLARE_KIND_(char, kInteger);
  395. GMOCK_DECLARE_KIND_(signed char, kInteger);
  396. GMOCK_DECLARE_KIND_(unsigned char, kInteger);
  397. GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT
  398. GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT
  399. GMOCK_DECLARE_KIND_(int, kInteger);
  400. GMOCK_DECLARE_KIND_(unsigned int, kInteger);
  401. GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT
  402. GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
  403. GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT
  404. GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT
  405. #if GMOCK_WCHAR_T_IS_NATIVE_
  406. GMOCK_DECLARE_KIND_(wchar_t, kInteger);
  407. #endif
  408. // All standard floating-point types.
  409. GMOCK_DECLARE_KIND_(float, kFloatingPoint);
  410. GMOCK_DECLARE_KIND_(double, kFloatingPoint);
  411. GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
  412. #undef GMOCK_DECLARE_KIND_
  413. // Evaluates to the kind of 'type'.
  414. #define GMOCK_KIND_OF_(type) \
  415. static_cast< ::testing::internal::TypeKind>( \
  416. ::testing::internal::KindOf<type>::value)
  417. // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
  418. // is true if and only if arithmetic type From can be losslessly converted to
  419. // arithmetic type To.
  420. //
  421. // It's the user's responsibility to ensure that both From and To are
  422. // raw (i.e. has no CV modifier, is not a pointer, and is not a
  423. // reference) built-in arithmetic types, kFromKind is the kind of
  424. // From, and kToKind is the kind of To; the value is
  425. // implementation-defined when the above pre-condition is violated.
  426. template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
  427. using LosslessArithmeticConvertibleImpl = std::integral_constant<
  428. bool,
  429. // clang-format off
  430. // Converting from bool is always lossless
  431. (kFromKind == kBool) ? true
  432. // Converting between any other type kinds will be lossy if the type
  433. // kinds are not the same.
  434. : (kFromKind != kToKind) ? false
  435. : (kFromKind == kInteger &&
  436. // Converting between integers of different widths is allowed so long
  437. // as the conversion does not go from signed to unsigned.
  438. (((sizeof(From) < sizeof(To)) &&
  439. !(std::is_signed<From>::value && !std::is_signed<To>::value)) ||
  440. // Converting between integers of the same width only requires the
  441. // two types to have the same signedness.
  442. ((sizeof(From) == sizeof(To)) &&
  443. (std::is_signed<From>::value == std::is_signed<To>::value)))
  444. ) ? true
  445. // Floating point conversions are lossless if and only if `To` is at least
  446. // as wide as `From`.
  447. : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true
  448. : false
  449. // clang-format on
  450. >;
  451. // LosslessArithmeticConvertible<From, To>::value is true if and only if
  452. // arithmetic type From can be losslessly converted to arithmetic type To.
  453. //
  454. // It's the user's responsibility to ensure that both From and To are
  455. // raw (i.e. has no CV modifier, is not a pointer, and is not a
  456. // reference) built-in arithmetic types; the value is
  457. // implementation-defined when the above pre-condition is violated.
  458. template <typename From, typename To>
  459. using LosslessArithmeticConvertible =
  460. LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From,
  461. GMOCK_KIND_OF_(To), To>;
  462. // This interface knows how to report a Google Mock failure (either
  463. // non-fatal or fatal).
  464. class FailureReporterInterface {
  465. public:
  466. // The type of a failure (either non-fatal or fatal).
  467. enum FailureType {
  468. kNonfatal, kFatal
  469. };
  470. virtual ~FailureReporterInterface() {}
  471. // Reports a failure that occurred at the given source file location.
  472. virtual void ReportFailure(FailureType type, const char* file, int line,
  473. const std::string& message) = 0;
  474. };
  475. // Returns the failure reporter used by Google Mock.
  476. GTEST_API_ FailureReporterInterface* GetFailureReporter();
  477. // Asserts that condition is true; aborts the process with the given
  478. // message if condition is false. We cannot use LOG(FATAL) or CHECK()
  479. // as Google Mock might be used to mock the log sink itself. We
  480. // inline this function to prevent it from showing up in the stack
  481. // trace.
  482. inline void Assert(bool condition, const char* file, int line,
  483. const std::string& msg) {
  484. if (!condition) {
  485. GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
  486. file, line, msg);
  487. }
  488. }
  489. inline void Assert(bool condition, const char* file, int line) {
  490. Assert(condition, file, line, "Assertion failed.");
  491. }
  492. // Verifies that condition is true; generates a non-fatal failure if
  493. // condition is false.
  494. inline void Expect(bool condition, const char* file, int line,
  495. const std::string& msg) {
  496. if (!condition) {
  497. GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
  498. file, line, msg);
  499. }
  500. }
  501. inline void Expect(bool condition, const char* file, int line) {
  502. Expect(condition, file, line, "Expectation failed.");
  503. }
  504. // Severity level of a log.
  505. enum LogSeverity {
  506. kInfo = 0,
  507. kWarning = 1
  508. };
  509. // Valid values for the --gmock_verbose flag.
  510. // All logs (informational and warnings) are printed.
  511. const char kInfoVerbosity[] = "info";
  512. // Only warnings are printed.
  513. const char kWarningVerbosity[] = "warning";
  514. // No logs are printed.
  515. const char kErrorVerbosity[] = "error";
  516. // Returns true if and only if a log with the given severity is visible
  517. // according to the --gmock_verbose flag.
  518. GTEST_API_ bool LogIsVisible(LogSeverity severity);
  519. // Prints the given message to stdout if and only if 'severity' >= the level
  520. // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
  521. // 0, also prints the stack trace excluding the top
  522. // stack_frames_to_skip frames. In opt mode, any positive
  523. // stack_frames_to_skip is treated as 0, since we don't know which
  524. // function calls will be inlined by the compiler and need to be
  525. // conservative.
  526. GTEST_API_ void Log(LogSeverity severity, const std::string& message,
  527. int stack_frames_to_skip);
  528. // A marker class that is used to resolve parameterless expectations to the
  529. // correct overload. This must not be instantiable, to prevent client code from
  530. // accidentally resolving to the overload; for example:
  531. //
  532. // ON_CALL(mock, Method({}, nullptr))...
  533. //
  534. class WithoutMatchers {
  535. private:
  536. WithoutMatchers() {}
  537. friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
  538. };
  539. // Internal use only: access the singleton instance of WithoutMatchers.
  540. GTEST_API_ WithoutMatchers GetWithoutMatchers();
  541. // Disable MSVC warnings for infinite recursion, since in this case the
  542. // the recursion is unreachable.
  543. #ifdef _MSC_VER
  544. # pragma warning(push)
  545. # pragma warning(disable:4717)
  546. #endif
  547. // Invalid<T>() is usable as an expression of type T, but will terminate
  548. // the program with an assertion failure if actually run. This is useful
  549. // when a value of type T is needed for compilation, but the statement
  550. // will not really be executed (or we don't care if the statement
  551. // crashes).
  552. template <typename T>
  553. inline T Invalid() {
  554. Assert(false, "", -1, "Internal error: attempt to return invalid value");
  555. // This statement is unreachable, and would never terminate even if it
  556. // could be reached. It is provided only to placate compiler warnings
  557. // about missing return statements.
  558. return Invalid<T>();
  559. }
  560. #ifdef _MSC_VER
  561. # pragma warning(pop)
  562. #endif
  563. // Given a raw type (i.e. having no top-level reference or const
  564. // modifier) RawContainer that's either an STL-style container or a
  565. // native array, class StlContainerView<RawContainer> has the
  566. // following members:
  567. //
  568. // - type is a type that provides an STL-style container view to
  569. // (i.e. implements the STL container concept for) RawContainer;
  570. // - const_reference is a type that provides a reference to a const
  571. // RawContainer;
  572. // - ConstReference(raw_container) returns a const reference to an STL-style
  573. // container view to raw_container, which is a RawContainer.
  574. // - Copy(raw_container) returns an STL-style container view of a
  575. // copy of raw_container, which is a RawContainer.
  576. //
  577. // This generic version is used when RawContainer itself is already an
  578. // STL-style container.
  579. template <class RawContainer>
  580. class StlContainerView {
  581. public:
  582. typedef RawContainer type;
  583. typedef const type& const_reference;
  584. static const_reference ConstReference(const RawContainer& container) {
  585. static_assert(!std::is_const<RawContainer>::value,
  586. "RawContainer type must not be const");
  587. return container;
  588. }
  589. static type Copy(const RawContainer& container) { return container; }
  590. };
  591. // This specialization is used when RawContainer is a native array type.
  592. template <typename Element, size_t N>
  593. class StlContainerView<Element[N]> {
  594. public:
  595. typedef typename std::remove_const<Element>::type RawElement;
  596. typedef internal::NativeArray<RawElement> type;
  597. // NativeArray<T> can represent a native array either by value or by
  598. // reference (selected by a constructor argument), so 'const type'
  599. // can be used to reference a const native array. We cannot
  600. // 'typedef const type& const_reference' here, as that would mean
  601. // ConstReference() has to return a reference to a local variable.
  602. typedef const type const_reference;
  603. static const_reference ConstReference(const Element (&array)[N]) {
  604. static_assert(std::is_same<Element, RawElement>::value,
  605. "Element type must not be const");
  606. return type(array, N, RelationToSourceReference());
  607. }
  608. static type Copy(const Element (&array)[N]) {
  609. return type(array, N, RelationToSourceCopy());
  610. }
  611. };
  612. // This specialization is used when RawContainer is a native array
  613. // represented as a (pointer, size) tuple.
  614. template <typename ElementPointer, typename Size>
  615. class StlContainerView< ::std::tuple<ElementPointer, Size> > {
  616. public:
  617. typedef typename std::remove_const<
  618. typename std::pointer_traits<ElementPointer>::element_type>::type
  619. RawElement;
  620. typedef internal::NativeArray<RawElement> type;
  621. typedef const type const_reference;
  622. static const_reference ConstReference(
  623. const ::std::tuple<ElementPointer, Size>& array) {
  624. return type(std::get<0>(array), std::get<1>(array),
  625. RelationToSourceReference());
  626. }
  627. static type Copy(const ::std::tuple<ElementPointer, Size>& array) {
  628. return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy());
  629. }
  630. };
  631. // The following specialization prevents the user from instantiating
  632. // StlContainer with a reference type.
  633. template <typename T> class StlContainerView<T&>;
  634. // A type transform to remove constness from the first part of a pair.
  635. // Pairs like that are used as the value_type of associative containers,
  636. // and this transform produces a similar but assignable pair.
  637. template <typename T>
  638. struct RemoveConstFromKey {
  639. typedef T type;
  640. };
  641. // Partially specialized to remove constness from std::pair<const K, V>.
  642. template <typename K, typename V>
  643. struct RemoveConstFromKey<std::pair<const K, V> > {
  644. typedef std::pair<K, V> type;
  645. };
  646. // Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
  647. // reduce code size.
  648. GTEST_API_ void IllegalDoDefault(const char* file, int line);
  649. template <typename F, typename Tuple, size_t... Idx>
  650. auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype(
  651. std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
  652. return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
  653. }
  654. // Apply the function to a tuple of arguments.
  655. template <typename F, typename Tuple>
  656. auto Apply(F&& f, Tuple&& args) -> decltype(
  657. ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
  658. MakeIndexSequence<std::tuple_size<
  659. typename std::remove_reference<Tuple>::type>::value>())) {
  660. return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
  661. MakeIndexSequence<std::tuple_size<
  662. typename std::remove_reference<Tuple>::type>::value>());
  663. }
  664. // Template struct Function<F>, where F must be a function type, contains
  665. // the following typedefs:
  666. //
  667. // Result: the function's return type.
  668. // Arg<N>: the type of the N-th argument, where N starts with 0.
  669. // ArgumentTuple: the tuple type consisting of all parameters of F.
  670. // ArgumentMatcherTuple: the tuple type consisting of Matchers for all
  671. // parameters of F.
  672. // MakeResultVoid: the function type obtained by substituting void
  673. // for the return type of F.
  674. // MakeResultIgnoredValue:
  675. // the function type obtained by substituting Something
  676. // for the return type of F.
  677. template <typename T>
  678. struct Function;
  679. template <typename R, typename... Args>
  680. struct Function<R(Args...)> {
  681. using Result = R;
  682. static constexpr size_t ArgumentCount = sizeof...(Args);
  683. template <size_t I>
  684. using Arg = ElemFromList<I, Args...>;
  685. using ArgumentTuple = std::tuple<Args...>;
  686. using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
  687. using MakeResultVoid = void(Args...);
  688. using MakeResultIgnoredValue = IgnoredValue(Args...);
  689. };
  690. template <typename R, typename... Args>
  691. constexpr size_t Function<R(Args...)>::ArgumentCount;
  692. #ifdef _MSC_VER
  693. # pragma warning(pop)
  694. #endif
  695. } // namespace internal
  696. } // namespace testing
  697. #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
  698. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
  699. #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
  700. // Expands and concatenates the arguments. Constructed macros reevaluate.
  701. #define GMOCK_PP_CAT(_1, _2) GMOCK_PP_INTERNAL_CAT(_1, _2)
  702. // Expands and stringifies the only argument.
  703. #define GMOCK_PP_STRINGIZE(...) GMOCK_PP_INTERNAL_STRINGIZE(__VA_ARGS__)
  704. // Returns empty. Given a variadic number of arguments.
  705. #define GMOCK_PP_EMPTY(...)
  706. // Returns a comma. Given a variadic number of arguments.
  707. #define GMOCK_PP_COMMA(...) ,
  708. // Returns the only argument.
  709. #define GMOCK_PP_IDENTITY(_1) _1
  710. // Evaluates to the number of arguments after expansion.
  711. //
  712. // #define PAIR x, y
  713. //
  714. // GMOCK_PP_NARG() => 1
  715. // GMOCK_PP_NARG(x) => 1
  716. // GMOCK_PP_NARG(x, y) => 2
  717. // GMOCK_PP_NARG(PAIR) => 2
  718. //
  719. // Requires: the number of arguments after expansion is at most 15.
  720. #define GMOCK_PP_NARG(...) \
  721. GMOCK_PP_INTERNAL_16TH( \
  722. (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
  723. // Returns 1 if the expansion of arguments has an unprotected comma. Otherwise
  724. // returns 0. Requires no more than 15 unprotected commas.
  725. #define GMOCK_PP_HAS_COMMA(...) \
  726. GMOCK_PP_INTERNAL_16TH( \
  727. (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0))
  728. // Returns the first argument.
  729. #define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__, unusedArg))
  730. // Returns the tail. A variadic list of all arguments minus the first. Requires
  731. // at least one argument.
  732. #define GMOCK_PP_TAIL(...) GMOCK_PP_INTERNAL_TAIL((__VA_ARGS__))
  733. // Calls CAT(_Macro, NARG(__VA_ARGS__))(__VA_ARGS__)
  734. #define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \
  735. GMOCK_PP_IDENTITY( \
  736. GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__))
  737. // If the arguments after expansion have no tokens, evaluates to `1`. Otherwise
  738. // evaluates to `0`.
  739. //
  740. // Requires: * the number of arguments after expansion is at most 15.
  741. // * If the argument is a macro, it must be able to be called with one
  742. // argument.
  743. //
  744. // Implementation details:
  745. //
  746. // There is one case when it generates a compile error: if the argument is macro
  747. // that cannot be called with one argument.
  748. //
  749. // #define M(a, b) // it doesn't matter what it expands to
  750. //
  751. // // Expected: expands to `0`.
  752. // // Actual: compile error.
  753. // GMOCK_PP_IS_EMPTY(M)
  754. //
  755. // There are 4 cases tested:
  756. //
  757. // * __VA_ARGS__ possible expansion has no unparen'd commas. Expected 0.
  758. // * __VA_ARGS__ possible expansion is not enclosed in parenthesis. Expected 0.
  759. // * __VA_ARGS__ possible expansion is not a macro that ()-evaluates to a comma.
  760. // Expected 0
  761. // * __VA_ARGS__ is empty, or has unparen'd commas, or is enclosed in
  762. // parenthesis, or is a macro that ()-evaluates to comma. Expected 1.
  763. //
  764. // We trigger detection on '0001', i.e. on empty.
  765. #define GMOCK_PP_IS_EMPTY(...) \
  766. GMOCK_PP_INTERNAL_IS_EMPTY(GMOCK_PP_HAS_COMMA(__VA_ARGS__), \
  767. GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__), \
  768. GMOCK_PP_HAS_COMMA(__VA_ARGS__()), \
  769. GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__()))
  770. // Evaluates to _Then if _Cond is 1 and _Else if _Cond is 0.
  771. #define GMOCK_PP_IF(_Cond, _Then, _Else) \
  772. GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else)
  773. // Similar to GMOCK_PP_IF but takes _Then and _Else in parentheses.
  774. //
  775. // GMOCK_PP_GENERIC_IF(1, (a, b, c), (d, e, f)) => a, b, c
  776. // GMOCK_PP_GENERIC_IF(0, (a, b, c), (d, e, f)) => d, e, f
  777. //
  778. #define GMOCK_PP_GENERIC_IF(_Cond, _Then, _Else) \
  779. GMOCK_PP_REMOVE_PARENS(GMOCK_PP_IF(_Cond, _Then, _Else))
  780. // Evaluates to the number of arguments after expansion. Identifies 'empty' as
  781. // 0.
  782. //
  783. // #define PAIR x, y
  784. //
  785. // GMOCK_PP_NARG0() => 0
  786. // GMOCK_PP_NARG0(x) => 1
  787. // GMOCK_PP_NARG0(x, y) => 2
  788. // GMOCK_PP_NARG0(PAIR) => 2
  789. //
  790. // Requires: * the number of arguments after expansion is at most 15.
  791. // * If the argument is a macro, it must be able to be called with one
  792. // argument.
  793. #define GMOCK_PP_NARG0(...) \
  794. GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(__VA_ARGS__), 0, GMOCK_PP_NARG(__VA_ARGS__))
  795. // Expands to 1 if the first argument starts with something in parentheses,
  796. // otherwise to 0.
  797. #define GMOCK_PP_IS_BEGIN_PARENS(...) \
  798. GMOCK_PP_HEAD(GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_, \
  799. GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C __VA_ARGS__))
  800. // Expands to 1 is there is only one argument and it is enclosed in parentheses.
  801. #define GMOCK_PP_IS_ENCLOSED_PARENS(...) \
  802. GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(__VA_ARGS__), \
  803. GMOCK_PP_IS_EMPTY(GMOCK_PP_EMPTY __VA_ARGS__), 0)
  804. // Remove the parens, requires GMOCK_PP_IS_ENCLOSED_PARENS(args) => 1.
  805. #define GMOCK_PP_REMOVE_PARENS(...) GMOCK_PP_INTERNAL_REMOVE_PARENS __VA_ARGS__
  806. // Expands to _Macro(0, _Data, e1) _Macro(1, _Data, e2) ... _Macro(K -1, _Data,
  807. // eK) as many of GMOCK_INTERNAL_NARG0 _Tuple.
  808. // Requires: * |_Macro| can be called with 3 arguments.
  809. // * |_Tuple| expansion has no more than 15 elements.
  810. #define GMOCK_PP_FOR_EACH(_Macro, _Data, _Tuple) \
  811. GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, GMOCK_PP_NARG0 _Tuple) \
  812. (0, _Macro, _Data, _Tuple)
  813. // Expands to _Macro(0, _Data, ) _Macro(1, _Data, ) ... _Macro(K - 1, _Data, )
  814. // Empty if _K = 0.
  815. // Requires: * |_Macro| can be called with 3 arguments.
  816. // * |_K| literal between 0 and 15
  817. #define GMOCK_PP_REPEAT(_Macro, _Data, _N) \
  818. GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, _N) \
  819. (0, _Macro, _Data, GMOCK_PP_INTENRAL_EMPTY_TUPLE)
  820. // Increments the argument, requires the argument to be between 0 and 15.
  821. #define GMOCK_PP_INC(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_INC_, _i)
  822. // Returns comma if _i != 0. Requires _i to be between 0 and 15.
  823. #define GMOCK_PP_COMMA_IF(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_COMMA_IF_, _i)
  824. // Internal details follow. Do not use any of these symbols outside of this
  825. // file or we will break your code.
  826. #define GMOCK_PP_INTENRAL_EMPTY_TUPLE (, , , , , , , , , , , , , , , )
  827. #define GMOCK_PP_INTERNAL_CAT(_1, _2) _1##_2
  828. #define GMOCK_PP_INTERNAL_STRINGIZE(...) #__VA_ARGS__
  829. #define GMOCK_PP_INTERNAL_CAT_5(_1, _2, _3, _4, _5) _1##_2##_3##_4##_5
  830. #define GMOCK_PP_INTERNAL_IS_EMPTY(_1, _2, _3, _4) \
  831. GMOCK_PP_HAS_COMMA(GMOCK_PP_INTERNAL_CAT_5(GMOCK_PP_INTERNAL_IS_EMPTY_CASE_, \
  832. _1, _2, _3, _4))
  833. #define GMOCK_PP_INTERNAL_IS_EMPTY_CASE_0001 ,
  834. #define GMOCK_PP_INTERNAL_IF_1(_Then, _Else) _Then
  835. #define GMOCK_PP_INTERNAL_IF_0(_Then, _Else) _Else
  836. // Because of MSVC treating a token with a comma in it as a single token when
  837. // passed to another macro, we need to force it to evaluate it as multiple
  838. // tokens. We do that by using a "IDENTITY(MACRO PARENTHESIZED_ARGS)" macro. We
  839. // define one per possible macro that relies on this behavior. Note "_Args" must
  840. // be parenthesized.
  841. #define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \
  842. _10, _11, _12, _13, _14, _15, _16, \
  843. ...) \
  844. _16
  845. #define GMOCK_PP_INTERNAL_16TH(_Args) \
  846. GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_16TH _Args)
  847. #define GMOCK_PP_INTERNAL_INTERNAL_HEAD(_1, ...) _1
  848. #define GMOCK_PP_INTERNAL_HEAD(_Args) \
  849. GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_HEAD _Args)
  850. #define GMOCK_PP_INTERNAL_INTERNAL_TAIL(_1, ...) __VA_ARGS__
  851. #define GMOCK_PP_INTERNAL_TAIL(_Args) \
  852. GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_TAIL _Args)
  853. #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _
  854. #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1,
  855. #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C \
  856. 0,
  857. #define GMOCK_PP_INTERNAL_REMOVE_PARENS(...) __VA_ARGS__
  858. #define GMOCK_PP_INTERNAL_INC_0 1
  859. #define GMOCK_PP_INTERNAL_INC_1 2
  860. #define GMOCK_PP_INTERNAL_INC_2 3
  861. #define GMOCK_PP_INTERNAL_INC_3 4
  862. #define GMOCK_PP_INTERNAL_INC_4 5
  863. #define GMOCK_PP_INTERNAL_INC_5 6
  864. #define GMOCK_PP_INTERNAL_INC_6 7
  865. #define GMOCK_PP_INTERNAL_INC_7 8
  866. #define GMOCK_PP_INTERNAL_INC_8 9
  867. #define GMOCK_PP_INTERNAL_INC_9 10
  868. #define GMOCK_PP_INTERNAL_INC_10 11
  869. #define GMOCK_PP_INTERNAL_INC_11 12
  870. #define GMOCK_PP_INTERNAL_INC_12 13
  871. #define GMOCK_PP_INTERNAL_INC_13 14
  872. #define GMOCK_PP_INTERNAL_INC_14 15
  873. #define GMOCK_PP_INTERNAL_INC_15 16
  874. #define GMOCK_PP_INTERNAL_COMMA_IF_0
  875. #define GMOCK_PP_INTERNAL_COMMA_IF_1 ,
  876. #define GMOCK_PP_INTERNAL_COMMA_IF_2 ,
  877. #define GMOCK_PP_INTERNAL_COMMA_IF_3 ,
  878. #define GMOCK_PP_INTERNAL_COMMA_IF_4 ,
  879. #define GMOCK_PP_INTERNAL_COMMA_IF_5 ,
  880. #define GMOCK_PP_INTERNAL_COMMA_IF_6 ,
  881. #define GMOCK_PP_INTERNAL_COMMA_IF_7 ,
  882. #define GMOCK_PP_INTERNAL_COMMA_IF_8 ,
  883. #define GMOCK_PP_INTERNAL_COMMA_IF_9 ,
  884. #define GMOCK_PP_INTERNAL_COMMA_IF_10 ,
  885. #define GMOCK_PP_INTERNAL_COMMA_IF_11 ,
  886. #define GMOCK_PP_INTERNAL_COMMA_IF_12 ,
  887. #define GMOCK_PP_INTERNAL_COMMA_IF_13 ,
  888. #define GMOCK_PP_INTERNAL_COMMA_IF_14 ,
  889. #define GMOCK_PP_INTERNAL_COMMA_IF_15 ,
  890. #define GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, _element) \
  891. _Macro(_i, _Data, _element)
  892. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_0(_i, _Macro, _Data, _Tuple)
  893. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(_i, _Macro, _Data, _Tuple) \
  894. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple)
  895. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(_i, _Macro, _Data, _Tuple) \
  896. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  897. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(GMOCK_PP_INC(_i), _Macro, _Data, \
  898. (GMOCK_PP_TAIL _Tuple))
  899. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(_i, _Macro, _Data, _Tuple) \
  900. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  901. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(GMOCK_PP_INC(_i), _Macro, _Data, \
  902. (GMOCK_PP_TAIL _Tuple))
  903. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(_i, _Macro, _Data, _Tuple) \
  904. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  905. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(GMOCK_PP_INC(_i), _Macro, _Data, \
  906. (GMOCK_PP_TAIL _Tuple))
  907. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(_i, _Macro, _Data, _Tuple) \
  908. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  909. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(GMOCK_PP_INC(_i), _Macro, _Data, \
  910. (GMOCK_PP_TAIL _Tuple))
  911. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(_i, _Macro, _Data, _Tuple) \
  912. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  913. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(GMOCK_PP_INC(_i), _Macro, _Data, \
  914. (GMOCK_PP_TAIL _Tuple))
  915. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(_i, _Macro, _Data, _Tuple) \
  916. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  917. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(GMOCK_PP_INC(_i), _Macro, _Data, \
  918. (GMOCK_PP_TAIL _Tuple))
  919. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(_i, _Macro, _Data, _Tuple) \
  920. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  921. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(GMOCK_PP_INC(_i), _Macro, _Data, \
  922. (GMOCK_PP_TAIL _Tuple))
  923. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(_i, _Macro, _Data, _Tuple) \
  924. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  925. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(GMOCK_PP_INC(_i), _Macro, _Data, \
  926. (GMOCK_PP_TAIL _Tuple))
  927. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(_i, _Macro, _Data, _Tuple) \
  928. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  929. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(GMOCK_PP_INC(_i), _Macro, _Data, \
  930. (GMOCK_PP_TAIL _Tuple))
  931. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(_i, _Macro, _Data, _Tuple) \
  932. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  933. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(GMOCK_PP_INC(_i), _Macro, _Data, \
  934. (GMOCK_PP_TAIL _Tuple))
  935. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(_i, _Macro, _Data, _Tuple) \
  936. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  937. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(GMOCK_PP_INC(_i), _Macro, _Data, \
  938. (GMOCK_PP_TAIL _Tuple))
  939. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(_i, _Macro, _Data, _Tuple) \
  940. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  941. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(GMOCK_PP_INC(_i), _Macro, _Data, \
  942. (GMOCK_PP_TAIL _Tuple))
  943. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(_i, _Macro, _Data, _Tuple) \
  944. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  945. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(GMOCK_PP_INC(_i), _Macro, _Data, \
  946. (GMOCK_PP_TAIL _Tuple))
  947. #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_15(_i, _Macro, _Data, _Tuple) \
  948. GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \
  949. GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(GMOCK_PP_INC(_i), _Macro, _Data, \
  950. (GMOCK_PP_TAIL _Tuple))
  951. #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
  952. #ifdef _MSC_VER
  953. # pragma warning(push)
  954. # pragma warning(disable:4100)
  955. #endif
  956. namespace testing {
  957. // To implement an action Foo, define:
  958. // 1. a class FooAction that implements the ActionInterface interface, and
  959. // 2. a factory function that creates an Action object from a
  960. // const FooAction*.
  961. //
  962. // The two-level delegation design follows that of Matcher, providing
  963. // consistency for extension developers. It also eases ownership
  964. // management as Action objects can now be copied like plain values.
  965. namespace internal {
  966. // BuiltInDefaultValueGetter<T, true>::Get() returns a
  967. // default-constructed T value. BuiltInDefaultValueGetter<T,
  968. // false>::Get() crashes with an error.
  969. //
  970. // This primary template is used when kDefaultConstructible is true.
  971. template <typename T, bool kDefaultConstructible>
  972. struct BuiltInDefaultValueGetter {
  973. static T Get() { return T(); }
  974. };
  975. template <typename T>
  976. struct BuiltInDefaultValueGetter<T, false> {
  977. static T Get() {
  978. Assert(false, __FILE__, __LINE__,
  979. "Default action undefined for the function return type.");
  980. return internal::Invalid<T>();
  981. // The above statement will never be reached, but is required in
  982. // order for this function to compile.
  983. }
  984. };
  985. // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
  986. // for type T, which is NULL when T is a raw pointer type, 0 when T is
  987. // a numeric type, false when T is bool, or "" when T is string or
  988. // std::string. In addition, in C++11 and above, it turns a
  989. // default-constructed T value if T is default constructible. For any
  990. // other type T, the built-in default T value is undefined, and the
  991. // function will abort the process.
  992. template <typename T>
  993. class BuiltInDefaultValue {
  994. public:
  995. // This function returns true if and only if type T has a built-in default
  996. // value.
  997. static bool Exists() {
  998. return ::std::is_default_constructible<T>::value;
  999. }
  1000. static T Get() {
  1001. return BuiltInDefaultValueGetter<
  1002. T, ::std::is_default_constructible<T>::value>::Get();
  1003. }
  1004. };
  1005. // This partial specialization says that we use the same built-in
  1006. // default value for T and const T.
  1007. template <typename T>
  1008. class BuiltInDefaultValue<const T> {
  1009. public:
  1010. static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
  1011. static T Get() { return BuiltInDefaultValue<T>::Get(); }
  1012. };
  1013. // This partial specialization defines the default values for pointer
  1014. // types.
  1015. template <typename T>
  1016. class BuiltInDefaultValue<T*> {
  1017. public:
  1018. static bool Exists() { return true; }
  1019. static T* Get() { return nullptr; }
  1020. };
  1021. // The following specializations define the default values for
  1022. // specific types we care about.
  1023. #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
  1024. template <> \
  1025. class BuiltInDefaultValue<type> { \
  1026. public: \
  1027. static bool Exists() { return true; } \
  1028. static type Get() { return value; } \
  1029. }
  1030. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
  1031. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
  1032. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
  1033. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
  1034. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
  1035. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
  1036. // There's no need for a default action for signed wchar_t, as that
  1037. // type is the same as wchar_t for gcc, and invalid for MSVC.
  1038. //
  1039. // There's also no need for a default action for unsigned wchar_t, as
  1040. // that type is the same as unsigned int for gcc, and invalid for
  1041. // MSVC.
  1042. #if GMOCK_WCHAR_T_IS_NATIVE_
  1043. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
  1044. #endif
  1045. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
  1046. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
  1047. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
  1048. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
  1049. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
  1050. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
  1051. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT
  1052. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT
  1053. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
  1054. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
  1055. #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
  1056. // Simple two-arg form of std::disjunction.
  1057. template <typename P, typename Q>
  1058. using disjunction = typename ::std::conditional<P::value, P, Q>::type;
  1059. } // namespace internal
  1060. // When an unexpected function call is encountered, Google Mock will
  1061. // let it return a default value if the user has specified one for its
  1062. // return type, or if the return type has a built-in default value;
  1063. // otherwise Google Mock won't know what value to return and will have
  1064. // to abort the process.
  1065. //
  1066. // The DefaultValue<T> class allows a user to specify the
  1067. // default value for a type T that is both copyable and publicly
  1068. // destructible (i.e. anything that can be used as a function return
  1069. // type). The usage is:
  1070. //
  1071. // // Sets the default value for type T to be foo.
  1072. // DefaultValue<T>::Set(foo);
  1073. template <typename T>
  1074. class DefaultValue {
  1075. public:
  1076. // Sets the default value for type T; requires T to be
  1077. // copy-constructable and have a public destructor.
  1078. static void Set(T x) {
  1079. delete producer_;
  1080. producer_ = new FixedValueProducer(x);
  1081. }
  1082. // Provides a factory function to be called to generate the default value.
  1083. // This method can be used even if T is only move-constructible, but it is not
  1084. // limited to that case.
  1085. typedef T (*FactoryFunction)();
  1086. static void SetFactory(FactoryFunction factory) {
  1087. delete producer_;
  1088. producer_ = new FactoryValueProducer(factory);
  1089. }
  1090. // Unsets the default value for type T.
  1091. static void Clear() {
  1092. delete producer_;
  1093. producer_ = nullptr;
  1094. }
  1095. // Returns true if and only if the user has set the default value for type T.
  1096. static bool IsSet() { return producer_ != nullptr; }
  1097. // Returns true if T has a default return value set by the user or there
  1098. // exists a built-in default value.
  1099. static bool Exists() {
  1100. return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
  1101. }
  1102. // Returns the default value for type T if the user has set one;
  1103. // otherwise returns the built-in default value. Requires that Exists()
  1104. // is true, which ensures that the return value is well-defined.
  1105. static T Get() {
  1106. return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()
  1107. : producer_->Produce();
  1108. }
  1109. private:
  1110. class ValueProducer {
  1111. public:
  1112. virtual ~ValueProducer() {}
  1113. virtual T Produce() = 0;
  1114. };
  1115. class FixedValueProducer : public ValueProducer {
  1116. public:
  1117. explicit FixedValueProducer(T value) : value_(value) {}
  1118. T Produce() override { return value_; }
  1119. private:
  1120. const T value_;
  1121. GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
  1122. };
  1123. class FactoryValueProducer : public ValueProducer {
  1124. public:
  1125. explicit FactoryValueProducer(FactoryFunction factory)
  1126. : factory_(factory) {}
  1127. T Produce() override { return factory_(); }
  1128. private:
  1129. const FactoryFunction factory_;
  1130. GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
  1131. };
  1132. static ValueProducer* producer_;
  1133. };
  1134. // This partial specialization allows a user to set default values for
  1135. // reference types.
  1136. template <typename T>
  1137. class DefaultValue<T&> {
  1138. public:
  1139. // Sets the default value for type T&.
  1140. static void Set(T& x) { // NOLINT
  1141. address_ = &x;
  1142. }
  1143. // Unsets the default value for type T&.
  1144. static void Clear() { address_ = nullptr; }
  1145. // Returns true if and only if the user has set the default value for type T&.
  1146. static bool IsSet() { return address_ != nullptr; }
  1147. // Returns true if T has a default return value set by the user or there
  1148. // exists a built-in default value.
  1149. static bool Exists() {
  1150. return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
  1151. }
  1152. // Returns the default value for type T& if the user has set one;
  1153. // otherwise returns the built-in default value if there is one;
  1154. // otherwise aborts the process.
  1155. static T& Get() {
  1156. return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()
  1157. : *address_;
  1158. }
  1159. private:
  1160. static T* address_;
  1161. };
  1162. // This specialization allows DefaultValue<void>::Get() to
  1163. // compile.
  1164. template <>
  1165. class DefaultValue<void> {
  1166. public:
  1167. static bool Exists() { return true; }
  1168. static void Get() {}
  1169. };
  1170. // Points to the user-set default value for type T.
  1171. template <typename T>
  1172. typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;
  1173. // Points to the user-set default value for type T&.
  1174. template <typename T>
  1175. T* DefaultValue<T&>::address_ = nullptr;
  1176. // Implement this interface to define an action for function type F.
  1177. template <typename F>
  1178. class ActionInterface {
  1179. public:
  1180. typedef typename internal::Function<F>::Result Result;
  1181. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  1182. ActionInterface() {}
  1183. virtual ~ActionInterface() {}
  1184. // Performs the action. This method is not const, as in general an
  1185. // action can have side effects and be stateful. For example, a
  1186. // get-the-next-element-from-the-collection action will need to
  1187. // remember the current element.
  1188. virtual Result Perform(const ArgumentTuple& args) = 0;
  1189. private:
  1190. GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
  1191. };
  1192. // An Action<F> is a copyable and IMMUTABLE (except by assignment)
  1193. // object that represents an action to be taken when a mock function
  1194. // of type F is called. The implementation of Action<T> is just a
  1195. // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action!
  1196. // You can view an object implementing ActionInterface<F> as a
  1197. // concrete action (including its current state), and an Action<F>
  1198. // object as a handle to it.
  1199. template <typename F>
  1200. class Action {
  1201. // Adapter class to allow constructing Action from a legacy ActionInterface.
  1202. // New code should create Actions from functors instead.
  1203. struct ActionAdapter {
  1204. // Adapter must be copyable to satisfy std::function requirements.
  1205. ::std::shared_ptr<ActionInterface<F>> impl_;
  1206. template <typename... Args>
  1207. typename internal::Function<F>::Result operator()(Args&&... args) {
  1208. return impl_->Perform(
  1209. ::std::forward_as_tuple(::std::forward<Args>(args)...));
  1210. }
  1211. };
  1212. template <typename G>
  1213. using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>;
  1214. public:
  1215. typedef typename internal::Function<F>::Result Result;
  1216. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  1217. // Constructs a null Action. Needed for storing Action objects in
  1218. // STL containers.
  1219. Action() {}
  1220. // Construct an Action from a specified callable.
  1221. // This cannot take std::function directly, because then Action would not be
  1222. // directly constructible from lambda (it would require two conversions).
  1223. template <
  1224. typename G,
  1225. typename = typename std::enable_if<internal::disjunction<
  1226. IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>,
  1227. G>>::value>::type>
  1228. Action(G&& fun) { // NOLINT
  1229. Init(::std::forward<G>(fun), IsCompatibleFunctor<G>());
  1230. }
  1231. // Constructs an Action from its implementation.
  1232. explicit Action(ActionInterface<F>* impl)
  1233. : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}
  1234. // This constructor allows us to turn an Action<Func> object into an
  1235. // Action<F>, as long as F's arguments can be implicitly converted
  1236. // to Func's and Func's return type can be implicitly converted to F's.
  1237. template <typename Func>
  1238. explicit Action(const Action<Func>& action) : fun_(action.fun_) {}
  1239. // Returns true if and only if this is the DoDefault() action.
  1240. bool IsDoDefault() const { return fun_ == nullptr; }
  1241. // Performs the action. Note that this method is const even though
  1242. // the corresponding method in ActionInterface is not. The reason
  1243. // is that a const Action<F> means that it cannot be re-bound to
  1244. // another concrete action, not that the concrete action it binds to
  1245. // cannot change state. (Think of the difference between a const
  1246. // pointer and a pointer to const.)
  1247. Result Perform(ArgumentTuple args) const {
  1248. if (IsDoDefault()) {
  1249. internal::IllegalDoDefault(__FILE__, __LINE__);
  1250. }
  1251. return internal::Apply(fun_, ::std::move(args));
  1252. }
  1253. private:
  1254. template <typename G>
  1255. friend class Action;
  1256. template <typename G>
  1257. void Init(G&& g, ::std::true_type) {
  1258. fun_ = ::std::forward<G>(g);
  1259. }
  1260. template <typename G>
  1261. void Init(G&& g, ::std::false_type) {
  1262. fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};
  1263. }
  1264. template <typename FunctionImpl>
  1265. struct IgnoreArgs {
  1266. template <typename... Args>
  1267. Result operator()(const Args&...) const {
  1268. return function_impl();
  1269. }
  1270. FunctionImpl function_impl;
  1271. };
  1272. // fun_ is an empty function if and only if this is the DoDefault() action.
  1273. ::std::function<F> fun_;
  1274. };
  1275. // The PolymorphicAction class template makes it easy to implement a
  1276. // polymorphic action (i.e. an action that can be used in mock
  1277. // functions of than one type, e.g. Return()).
  1278. //
  1279. // To define a polymorphic action, a user first provides a COPYABLE
  1280. // implementation class that has a Perform() method template:
  1281. //
  1282. // class FooAction {
  1283. // public:
  1284. // template <typename Result, typename ArgumentTuple>
  1285. // Result Perform(const ArgumentTuple& args) const {
  1286. // // Processes the arguments and returns a result, using
  1287. // // std::get<N>(args) to get the N-th (0-based) argument in the tuple.
  1288. // }
  1289. // ...
  1290. // };
  1291. //
  1292. // Then the user creates the polymorphic action using
  1293. // MakePolymorphicAction(object) where object has type FooAction. See
  1294. // the definition of Return(void) and SetArgumentPointee<N>(value) for
  1295. // complete examples.
  1296. template <typename Impl>
  1297. class PolymorphicAction {
  1298. public:
  1299. explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
  1300. template <typename F>
  1301. operator Action<F>() const {
  1302. return Action<F>(new MonomorphicImpl<F>(impl_));
  1303. }
  1304. private:
  1305. template <typename F>
  1306. class MonomorphicImpl : public ActionInterface<F> {
  1307. public:
  1308. typedef typename internal::Function<F>::Result Result;
  1309. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  1310. explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
  1311. Result Perform(const ArgumentTuple& args) override {
  1312. return impl_.template Perform<Result>(args);
  1313. }
  1314. private:
  1315. Impl impl_;
  1316. };
  1317. Impl impl_;
  1318. };
  1319. // Creates an Action from its implementation and returns it. The
  1320. // created Action object owns the implementation.
  1321. template <typename F>
  1322. Action<F> MakeAction(ActionInterface<F>* impl) {
  1323. return Action<F>(impl);
  1324. }
  1325. // Creates a polymorphic action from its implementation. This is
  1326. // easier to use than the PolymorphicAction<Impl> constructor as it
  1327. // doesn't require you to explicitly write the template argument, e.g.
  1328. //
  1329. // MakePolymorphicAction(foo);
  1330. // vs
  1331. // PolymorphicAction<TypeOfFoo>(foo);
  1332. template <typename Impl>
  1333. inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
  1334. return PolymorphicAction<Impl>(impl);
  1335. }
  1336. namespace internal {
  1337. // Helper struct to specialize ReturnAction to execute a move instead of a copy
  1338. // on return. Useful for move-only types, but could be used on any type.
  1339. template <typename T>
  1340. struct ByMoveWrapper {
  1341. explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
  1342. T payload;
  1343. };
  1344. // Implements the polymorphic Return(x) action, which can be used in
  1345. // any function that returns the type of x, regardless of the argument
  1346. // types.
  1347. //
  1348. // Note: The value passed into Return must be converted into
  1349. // Function<F>::Result when this action is cast to Action<F> rather than
  1350. // when that action is performed. This is important in scenarios like
  1351. //
  1352. // MOCK_METHOD1(Method, T(U));
  1353. // ...
  1354. // {
  1355. // Foo foo;
  1356. // X x(&foo);
  1357. // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
  1358. // }
  1359. //
  1360. // In the example above the variable x holds reference to foo which leaves
  1361. // scope and gets destroyed. If copying X just copies a reference to foo,
  1362. // that copy will be left with a hanging reference. If conversion to T
  1363. // makes a copy of foo, the above code is safe. To support that scenario, we
  1364. // need to make sure that the type conversion happens inside the EXPECT_CALL
  1365. // statement, and conversion of the result of Return to Action<T(U)> is a
  1366. // good place for that.
  1367. //
  1368. // The real life example of the above scenario happens when an invocation
  1369. // of gtl::Container() is passed into Return.
  1370. //
  1371. template <typename R>
  1372. class ReturnAction {
  1373. public:
  1374. // Constructs a ReturnAction object from the value to be returned.
  1375. // 'value' is passed by value instead of by const reference in order
  1376. // to allow Return("string literal") to compile.
  1377. explicit ReturnAction(R value) : value_(new R(std::move(value))) {}
  1378. // This template type conversion operator allows Return(x) to be
  1379. // used in ANY function that returns x's type.
  1380. template <typename F>
  1381. operator Action<F>() const { // NOLINT
  1382. // Assert statement belongs here because this is the best place to verify
  1383. // conditions on F. It produces the clearest error messages
  1384. // in most compilers.
  1385. // Impl really belongs in this scope as a local class but can't
  1386. // because MSVC produces duplicate symbols in different translation units
  1387. // in this case. Until MS fixes that bug we put Impl into the class scope
  1388. // and put the typedef both here (for use in assert statement) and
  1389. // in the Impl class. But both definitions must be the same.
  1390. typedef typename Function<F>::Result Result;
  1391. GTEST_COMPILE_ASSERT_(
  1392. !std::is_reference<Result>::value,
  1393. use_ReturnRef_instead_of_Return_to_return_a_reference);
  1394. static_assert(!std::is_void<Result>::value,
  1395. "Can't use Return() on an action expected to return `void`.");
  1396. return Action<F>(new Impl<R, F>(value_));
  1397. }
  1398. private:
  1399. // Implements the Return(x) action for a particular function type F.
  1400. template <typename R_, typename F>
  1401. class Impl : public ActionInterface<F> {
  1402. public:
  1403. typedef typename Function<F>::Result Result;
  1404. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  1405. // The implicit cast is necessary when Result has more than one
  1406. // single-argument constructor (e.g. Result is std::vector<int>) and R
  1407. // has a type conversion operator template. In that case, value_(value)
  1408. // won't compile as the compiler doesn't known which constructor of
  1409. // Result to call. ImplicitCast_ forces the compiler to convert R to
  1410. // Result without considering explicit constructors, thus resolving the
  1411. // ambiguity. value_ is then initialized using its copy constructor.
  1412. explicit Impl(const std::shared_ptr<R>& value)
  1413. : value_before_cast_(*value),
  1414. value_(ImplicitCast_<Result>(value_before_cast_)) {}
  1415. Result Perform(const ArgumentTuple&) override { return value_; }
  1416. private:
  1417. GTEST_COMPILE_ASSERT_(!std::is_reference<Result>::value,
  1418. Result_cannot_be_a_reference_type);
  1419. // We save the value before casting just in case it is being cast to a
  1420. // wrapper type.
  1421. R value_before_cast_;
  1422. Result value_;
  1423. GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
  1424. };
  1425. // Partially specialize for ByMoveWrapper. This version of ReturnAction will
  1426. // move its contents instead.
  1427. template <typename R_, typename F>
  1428. class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
  1429. public:
  1430. typedef typename Function<F>::Result Result;
  1431. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  1432. explicit Impl(const std::shared_ptr<R>& wrapper)
  1433. : performed_(false), wrapper_(wrapper) {}
  1434. Result Perform(const ArgumentTuple&) override {
  1435. GTEST_CHECK_(!performed_)
  1436. << "A ByMove() action should only be performed once.";
  1437. performed_ = true;
  1438. return std::move(wrapper_->payload);
  1439. }
  1440. private:
  1441. bool performed_;
  1442. const std::shared_ptr<R> wrapper_;
  1443. };
  1444. const std::shared_ptr<R> value_;
  1445. };
  1446. // Implements the ReturnNull() action.
  1447. class ReturnNullAction {
  1448. public:
  1449. // Allows ReturnNull() to be used in any pointer-returning function. In C++11
  1450. // this is enforced by returning nullptr, and in non-C++11 by asserting a
  1451. // pointer type on compile time.
  1452. template <typename Result, typename ArgumentTuple>
  1453. static Result Perform(const ArgumentTuple&) {
  1454. return nullptr;
  1455. }
  1456. };
  1457. // Implements the Return() action.
  1458. class ReturnVoidAction {
  1459. public:
  1460. // Allows Return() to be used in any void-returning function.
  1461. template <typename Result, typename ArgumentTuple>
  1462. static void Perform(const ArgumentTuple&) {
  1463. static_assert(std::is_void<Result>::value, "Result should be void.");
  1464. }
  1465. };
  1466. // Implements the polymorphic ReturnRef(x) action, which can be used
  1467. // in any function that returns a reference to the type of x,
  1468. // regardless of the argument types.
  1469. template <typename T>
  1470. class ReturnRefAction {
  1471. public:
  1472. // Constructs a ReturnRefAction object from the reference to be returned.
  1473. explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
  1474. // This template type conversion operator allows ReturnRef(x) to be
  1475. // used in ANY function that returns a reference to x's type.
  1476. template <typename F>
  1477. operator Action<F>() const {
  1478. typedef typename Function<F>::Result Result;
  1479. // Asserts that the function return type is a reference. This
  1480. // catches the user error of using ReturnRef(x) when Return(x)
  1481. // should be used, and generates some helpful error message.
  1482. GTEST_COMPILE_ASSERT_(std::is_reference<Result>::value,
  1483. use_Return_instead_of_ReturnRef_to_return_a_value);
  1484. return Action<F>(new Impl<F>(ref_));
  1485. }
  1486. private:
  1487. // Implements the ReturnRef(x) action for a particular function type F.
  1488. template <typename F>
  1489. class Impl : public ActionInterface<F> {
  1490. public:
  1491. typedef typename Function<F>::Result Result;
  1492. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  1493. explicit Impl(T& ref) : ref_(ref) {} // NOLINT
  1494. Result Perform(const ArgumentTuple&) override { return ref_; }
  1495. private:
  1496. T& ref_;
  1497. };
  1498. T& ref_;
  1499. };
  1500. // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
  1501. // used in any function that returns a reference to the type of x,
  1502. // regardless of the argument types.
  1503. template <typename T>
  1504. class ReturnRefOfCopyAction {
  1505. public:
  1506. // Constructs a ReturnRefOfCopyAction object from the reference to
  1507. // be returned.
  1508. explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
  1509. // This template type conversion operator allows ReturnRefOfCopy(x) to be
  1510. // used in ANY function that returns a reference to x's type.
  1511. template <typename F>
  1512. operator Action<F>() const {
  1513. typedef typename Function<F>::Result Result;
  1514. // Asserts that the function return type is a reference. This
  1515. // catches the user error of using ReturnRefOfCopy(x) when Return(x)
  1516. // should be used, and generates some helpful error message.
  1517. GTEST_COMPILE_ASSERT_(
  1518. std::is_reference<Result>::value,
  1519. use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
  1520. return Action<F>(new Impl<F>(value_));
  1521. }
  1522. private:
  1523. // Implements the ReturnRefOfCopy(x) action for a particular function type F.
  1524. template <typename F>
  1525. class Impl : public ActionInterface<F> {
  1526. public:
  1527. typedef typename Function<F>::Result Result;
  1528. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  1529. explicit Impl(const T& value) : value_(value) {} // NOLINT
  1530. Result Perform(const ArgumentTuple&) override { return value_; }
  1531. private:
  1532. T value_;
  1533. };
  1534. const T value_;
  1535. };
  1536. // Implements the polymorphic ReturnRoundRobin(v) action, which can be
  1537. // used in any function that returns the element_type of v.
  1538. template <typename T>
  1539. class ReturnRoundRobinAction {
  1540. public:
  1541. explicit ReturnRoundRobinAction(std::vector<T> values) {
  1542. GTEST_CHECK_(!values.empty())
  1543. << "ReturnRoundRobin requires at least one element.";
  1544. state_->values = std::move(values);
  1545. }
  1546. template <typename... Args>
  1547. T operator()(Args&&...) const {
  1548. return state_->Next();
  1549. }
  1550. private:
  1551. struct State {
  1552. T Next() {
  1553. T ret_val = values[i++];
  1554. if (i == values.size()) i = 0;
  1555. return ret_val;
  1556. }
  1557. std::vector<T> values;
  1558. size_t i = 0;
  1559. };
  1560. std::shared_ptr<State> state_ = std::make_shared<State>();
  1561. };
  1562. // Implements the polymorphic DoDefault() action.
  1563. class DoDefaultAction {
  1564. public:
  1565. // This template type conversion operator allows DoDefault() to be
  1566. // used in any function.
  1567. template <typename F>
  1568. operator Action<F>() const { return Action<F>(); } // NOLINT
  1569. };
  1570. // Implements the Assign action to set a given pointer referent to a
  1571. // particular value.
  1572. template <typename T1, typename T2>
  1573. class AssignAction {
  1574. public:
  1575. AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
  1576. template <typename Result, typename ArgumentTuple>
  1577. void Perform(const ArgumentTuple& /* args */) const {
  1578. *ptr_ = value_;
  1579. }
  1580. private:
  1581. T1* const ptr_;
  1582. const T2 value_;
  1583. };
  1584. #if !GTEST_OS_WINDOWS_MOBILE
  1585. // Implements the SetErrnoAndReturn action to simulate return from
  1586. // various system calls and libc functions.
  1587. template <typename T>
  1588. class SetErrnoAndReturnAction {
  1589. public:
  1590. SetErrnoAndReturnAction(int errno_value, T result)
  1591. : errno_(errno_value),
  1592. result_(result) {}
  1593. template <typename Result, typename ArgumentTuple>
  1594. Result Perform(const ArgumentTuple& /* args */) const {
  1595. errno = errno_;
  1596. return result_;
  1597. }
  1598. private:
  1599. const int errno_;
  1600. const T result_;
  1601. };
  1602. #endif // !GTEST_OS_WINDOWS_MOBILE
  1603. // Implements the SetArgumentPointee<N>(x) action for any function
  1604. // whose N-th argument (0-based) is a pointer to x's type.
  1605. template <size_t N, typename A, typename = void>
  1606. struct SetArgumentPointeeAction {
  1607. A value;
  1608. template <typename... Args>
  1609. void operator()(const Args&... args) const {
  1610. *::std::get<N>(std::tie(args...)) = value;
  1611. }
  1612. };
  1613. // Implements the Invoke(object_ptr, &Class::Method) action.
  1614. template <class Class, typename MethodPtr>
  1615. struct InvokeMethodAction {
  1616. Class* const obj_ptr;
  1617. const MethodPtr method_ptr;
  1618. template <typename... Args>
  1619. auto operator()(Args&&... args) const
  1620. -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
  1621. return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
  1622. }
  1623. };
  1624. // Implements the InvokeWithoutArgs(f) action. The template argument
  1625. // FunctionImpl is the implementation type of f, which can be either a
  1626. // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
  1627. // Action<F> as long as f's type is compatible with F.
  1628. template <typename FunctionImpl>
  1629. struct InvokeWithoutArgsAction {
  1630. FunctionImpl function_impl;
  1631. // Allows InvokeWithoutArgs(f) to be used as any action whose type is
  1632. // compatible with f.
  1633. template <typename... Args>
  1634. auto operator()(const Args&...) -> decltype(function_impl()) {
  1635. return function_impl();
  1636. }
  1637. };
  1638. // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
  1639. template <class Class, typename MethodPtr>
  1640. struct InvokeMethodWithoutArgsAction {
  1641. Class* const obj_ptr;
  1642. const MethodPtr method_ptr;
  1643. using ReturnType =
  1644. decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());
  1645. template <typename... Args>
  1646. ReturnType operator()(const Args&...) const {
  1647. return (obj_ptr->*method_ptr)();
  1648. }
  1649. };
  1650. // Implements the IgnoreResult(action) action.
  1651. template <typename A>
  1652. class IgnoreResultAction {
  1653. public:
  1654. explicit IgnoreResultAction(const A& action) : action_(action) {}
  1655. template <typename F>
  1656. operator Action<F>() const {
  1657. // Assert statement belongs here because this is the best place to verify
  1658. // conditions on F. It produces the clearest error messages
  1659. // in most compilers.
  1660. // Impl really belongs in this scope as a local class but can't
  1661. // because MSVC produces duplicate symbols in different translation units
  1662. // in this case. Until MS fixes that bug we put Impl into the class scope
  1663. // and put the typedef both here (for use in assert statement) and
  1664. // in the Impl class. But both definitions must be the same.
  1665. typedef typename internal::Function<F>::Result Result;
  1666. // Asserts at compile time that F returns void.
  1667. static_assert(std::is_void<Result>::value, "Result type should be void.");
  1668. return Action<F>(new Impl<F>(action_));
  1669. }
  1670. private:
  1671. template <typename F>
  1672. class Impl : public ActionInterface<F> {
  1673. public:
  1674. typedef typename internal::Function<F>::Result Result;
  1675. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  1676. explicit Impl(const A& action) : action_(action) {}
  1677. void Perform(const ArgumentTuple& args) override {
  1678. // Performs the action and ignores its result.
  1679. action_.Perform(args);
  1680. }
  1681. private:
  1682. // Type OriginalFunction is the same as F except that its return
  1683. // type is IgnoredValue.
  1684. typedef typename internal::Function<F>::MakeResultIgnoredValue
  1685. OriginalFunction;
  1686. const Action<OriginalFunction> action_;
  1687. };
  1688. const A action_;
  1689. };
  1690. template <typename InnerAction, size_t... I>
  1691. struct WithArgsAction {
  1692. InnerAction action;
  1693. // The inner action could be anything convertible to Action<X>.
  1694. // We use the conversion operator to detect the signature of the inner Action.
  1695. template <typename R, typename... Args>
  1696. operator Action<R(Args...)>() const { // NOLINT
  1697. using TupleType = std::tuple<Args...>;
  1698. Action<R(typename std::tuple_element<I, TupleType>::type...)>
  1699. converted(action);
  1700. return [converted](Args... args) -> R {
  1701. return converted.Perform(std::forward_as_tuple(
  1702. std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
  1703. };
  1704. }
  1705. };
  1706. template <typename... Actions>
  1707. struct DoAllAction {
  1708. private:
  1709. template <typename T>
  1710. using NonFinalType =
  1711. typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;
  1712. template <typename ActionT, size_t... I>
  1713. std::vector<ActionT> Convert(IndexSequence<I...>) const {
  1714. return {ActionT(std::get<I>(actions))...};
  1715. }
  1716. public:
  1717. std::tuple<Actions...> actions;
  1718. template <typename R, typename... Args>
  1719. operator Action<R(Args...)>() const { // NOLINT
  1720. struct Op {
  1721. std::vector<Action<void(NonFinalType<Args>...)>> converted;
  1722. Action<R(Args...)> last;
  1723. R operator()(Args... args) const {
  1724. auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
  1725. for (auto& a : converted) {
  1726. a.Perform(tuple_args);
  1727. }
  1728. return last.Perform(std::move(tuple_args));
  1729. }
  1730. };
  1731. return Op{Convert<Action<void(NonFinalType<Args>...)>>(
  1732. MakeIndexSequence<sizeof...(Actions) - 1>()),
  1733. std::get<sizeof...(Actions) - 1>(actions)};
  1734. }
  1735. };
  1736. template <typename T, typename... Params>
  1737. struct ReturnNewAction {
  1738. T* operator()() const {
  1739. return internal::Apply(
  1740. [](const Params&... unpacked_params) {
  1741. return new T(unpacked_params...);
  1742. },
  1743. params);
  1744. }
  1745. std::tuple<Params...> params;
  1746. };
  1747. template <size_t k>
  1748. struct ReturnArgAction {
  1749. template <typename... Args>
  1750. auto operator()(const Args&... args) const ->
  1751. typename std::tuple_element<k, std::tuple<Args...>>::type {
  1752. return std::get<k>(std::tie(args...));
  1753. }
  1754. };
  1755. template <size_t k, typename Ptr>
  1756. struct SaveArgAction {
  1757. Ptr pointer;
  1758. template <typename... Args>
  1759. void operator()(const Args&... args) const {
  1760. *pointer = std::get<k>(std::tie(args...));
  1761. }
  1762. };
  1763. template <size_t k, typename Ptr>
  1764. struct SaveArgPointeeAction {
  1765. Ptr pointer;
  1766. template <typename... Args>
  1767. void operator()(const Args&... args) const {
  1768. *pointer = *std::get<k>(std::tie(args...));
  1769. }
  1770. };
  1771. template <size_t k, typename T>
  1772. struct SetArgRefereeAction {
  1773. T value;
  1774. template <typename... Args>
  1775. void operator()(Args&&... args) const {
  1776. using argk_type =
  1777. typename ::std::tuple_element<k, std::tuple<Args...>>::type;
  1778. static_assert(std::is_lvalue_reference<argk_type>::value,
  1779. "Argument must be a reference type.");
  1780. std::get<k>(std::tie(args...)) = value;
  1781. }
  1782. };
  1783. template <size_t k, typename I1, typename I2>
  1784. struct SetArrayArgumentAction {
  1785. I1 first;
  1786. I2 last;
  1787. template <typename... Args>
  1788. void operator()(const Args&... args) const {
  1789. auto value = std::get<k>(std::tie(args...));
  1790. for (auto it = first; it != last; ++it, (void)++value) {
  1791. *value = *it;
  1792. }
  1793. }
  1794. };
  1795. template <size_t k>
  1796. struct DeleteArgAction {
  1797. template <typename... Args>
  1798. void operator()(const Args&... args) const {
  1799. delete std::get<k>(std::tie(args...));
  1800. }
  1801. };
  1802. template <typename Ptr>
  1803. struct ReturnPointeeAction {
  1804. Ptr pointer;
  1805. template <typename... Args>
  1806. auto operator()(const Args&...) const -> decltype(*pointer) {
  1807. return *pointer;
  1808. }
  1809. };
  1810. #if GTEST_HAS_EXCEPTIONS
  1811. template <typename T>
  1812. struct ThrowAction {
  1813. T exception;
  1814. // We use a conversion operator to adapt to any return type.
  1815. template <typename R, typename... Args>
  1816. operator Action<R(Args...)>() const { // NOLINT
  1817. T copy = exception;
  1818. return [copy](Args...) -> R { throw copy; };
  1819. }
  1820. };
  1821. #endif // GTEST_HAS_EXCEPTIONS
  1822. } // namespace internal
  1823. // An Unused object can be implicitly constructed from ANY value.
  1824. // This is handy when defining actions that ignore some or all of the
  1825. // mock function arguments. For example, given
  1826. //
  1827. // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
  1828. // MOCK_METHOD3(Bar, double(int index, double x, double y));
  1829. //
  1830. // instead of
  1831. //
  1832. // double DistanceToOriginWithLabel(const string& label, double x, double y) {
  1833. // return sqrt(x*x + y*y);
  1834. // }
  1835. // double DistanceToOriginWithIndex(int index, double x, double y) {
  1836. // return sqrt(x*x + y*y);
  1837. // }
  1838. // ...
  1839. // EXPECT_CALL(mock, Foo("abc", _, _))
  1840. // .WillOnce(Invoke(DistanceToOriginWithLabel));
  1841. // EXPECT_CALL(mock, Bar(5, _, _))
  1842. // .WillOnce(Invoke(DistanceToOriginWithIndex));
  1843. //
  1844. // you could write
  1845. //
  1846. // // We can declare any uninteresting argument as Unused.
  1847. // double DistanceToOrigin(Unused, double x, double y) {
  1848. // return sqrt(x*x + y*y);
  1849. // }
  1850. // ...
  1851. // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
  1852. // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
  1853. typedef internal::IgnoredValue Unused;
  1854. // Creates an action that does actions a1, a2, ..., sequentially in
  1855. // each invocation. All but the last action will have a readonly view of the
  1856. // arguments.
  1857. template <typename... Action>
  1858. internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
  1859. Action&&... action) {
  1860. return {std::forward_as_tuple(std::forward<Action>(action)...)};
  1861. }
  1862. // WithArg<k>(an_action) creates an action that passes the k-th
  1863. // (0-based) argument of the mock function to an_action and performs
  1864. // it. It adapts an action accepting one argument to one that accepts
  1865. // multiple arguments. For convenience, we also provide
  1866. // WithArgs<k>(an_action) (defined below) as a synonym.
  1867. template <size_t k, typename InnerAction>
  1868. internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
  1869. WithArg(InnerAction&& action) {
  1870. return {std::forward<InnerAction>(action)};
  1871. }
  1872. // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
  1873. // the selected arguments of the mock function to an_action and
  1874. // performs it. It serves as an adaptor between actions with
  1875. // different argument lists.
  1876. template <size_t k, size_t... ks, typename InnerAction>
  1877. internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
  1878. WithArgs(InnerAction&& action) {
  1879. return {std::forward<InnerAction>(action)};
  1880. }
  1881. // WithoutArgs(inner_action) can be used in a mock function with a
  1882. // non-empty argument list to perform inner_action, which takes no
  1883. // argument. In other words, it adapts an action accepting no
  1884. // argument to one that accepts (and ignores) arguments.
  1885. template <typename InnerAction>
  1886. internal::WithArgsAction<typename std::decay<InnerAction>::type>
  1887. WithoutArgs(InnerAction&& action) {
  1888. return {std::forward<InnerAction>(action)};
  1889. }
  1890. // Creates an action that returns 'value'. 'value' is passed by value
  1891. // instead of const reference - otherwise Return("string literal")
  1892. // will trigger a compiler error about using array as initializer.
  1893. template <typename R>
  1894. internal::ReturnAction<R> Return(R value) {
  1895. return internal::ReturnAction<R>(std::move(value));
  1896. }
  1897. // Creates an action that returns NULL.
  1898. inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
  1899. return MakePolymorphicAction(internal::ReturnNullAction());
  1900. }
  1901. // Creates an action that returns from a void function.
  1902. inline PolymorphicAction<internal::ReturnVoidAction> Return() {
  1903. return MakePolymorphicAction(internal::ReturnVoidAction());
  1904. }
  1905. // Creates an action that returns the reference to a variable.
  1906. template <typename R>
  1907. inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
  1908. return internal::ReturnRefAction<R>(x);
  1909. }
  1910. // Prevent using ReturnRef on reference to temporary.
  1911. template <typename R, R* = nullptr>
  1912. internal::ReturnRefAction<R> ReturnRef(R&&) = delete;
  1913. // Creates an action that returns the reference to a copy of the
  1914. // argument. The copy is created when the action is constructed and
  1915. // lives as long as the action.
  1916. template <typename R>
  1917. inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
  1918. return internal::ReturnRefOfCopyAction<R>(x);
  1919. }
  1920. // Modifies the parent action (a Return() action) to perform a move of the
  1921. // argument instead of a copy.
  1922. // Return(ByMove()) actions can only be executed once and will assert this
  1923. // invariant.
  1924. template <typename R>
  1925. internal::ByMoveWrapper<R> ByMove(R x) {
  1926. return internal::ByMoveWrapper<R>(std::move(x));
  1927. }
  1928. // Creates an action that returns an element of `vals`. Calling this action will
  1929. // repeatedly return the next value from `vals` until it reaches the end and
  1930. // will restart from the beginning.
  1931. template <typename T>
  1932. internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {
  1933. return internal::ReturnRoundRobinAction<T>(std::move(vals));
  1934. }
  1935. // Creates an action that returns an element of `vals`. Calling this action will
  1936. // repeatedly return the next value from `vals` until it reaches the end and
  1937. // will restart from the beginning.
  1938. template <typename T>
  1939. internal::ReturnRoundRobinAction<T> ReturnRoundRobin(
  1940. std::initializer_list<T> vals) {
  1941. return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));
  1942. }
  1943. // Creates an action that does the default action for the give mock function.
  1944. inline internal::DoDefaultAction DoDefault() {
  1945. return internal::DoDefaultAction();
  1946. }
  1947. // Creates an action that sets the variable pointed by the N-th
  1948. // (0-based) function argument to 'value'.
  1949. template <size_t N, typename T>
  1950. internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) {
  1951. return {std::move(value)};
  1952. }
  1953. // The following version is DEPRECATED.
  1954. template <size_t N, typename T>
  1955. internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {
  1956. return {std::move(value)};
  1957. }
  1958. // Creates an action that sets a pointer referent to a given value.
  1959. template <typename T1, typename T2>
  1960. PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
  1961. return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
  1962. }
  1963. #if !GTEST_OS_WINDOWS_MOBILE
  1964. // Creates an action that sets errno and returns the appropriate error.
  1965. template <typename T>
  1966. PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
  1967. SetErrnoAndReturn(int errval, T result) {
  1968. return MakePolymorphicAction(
  1969. internal::SetErrnoAndReturnAction<T>(errval, result));
  1970. }
  1971. #endif // !GTEST_OS_WINDOWS_MOBILE
  1972. // Various overloads for Invoke().
  1973. // Legacy function.
  1974. // Actions can now be implicitly constructed from callables. No need to create
  1975. // wrapper objects.
  1976. // This function exists for backwards compatibility.
  1977. template <typename FunctionImpl>
  1978. typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
  1979. return std::forward<FunctionImpl>(function_impl);
  1980. }
  1981. // Creates an action that invokes the given method on the given object
  1982. // with the mock function's arguments.
  1983. template <class Class, typename MethodPtr>
  1984. internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
  1985. MethodPtr method_ptr) {
  1986. return {obj_ptr, method_ptr};
  1987. }
  1988. // Creates an action that invokes 'function_impl' with no argument.
  1989. template <typename FunctionImpl>
  1990. internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
  1991. InvokeWithoutArgs(FunctionImpl function_impl) {
  1992. return {std::move(function_impl)};
  1993. }
  1994. // Creates an action that invokes the given method on the given object
  1995. // with no argument.
  1996. template <class Class, typename MethodPtr>
  1997. internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
  1998. Class* obj_ptr, MethodPtr method_ptr) {
  1999. return {obj_ptr, method_ptr};
  2000. }
  2001. // Creates an action that performs an_action and throws away its
  2002. // result. In other words, it changes the return type of an_action to
  2003. // void. an_action MUST NOT return void, or the code won't compile.
  2004. template <typename A>
  2005. inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
  2006. return internal::IgnoreResultAction<A>(an_action);
  2007. }
  2008. // Creates a reference wrapper for the given L-value. If necessary,
  2009. // you can explicitly specify the type of the reference. For example,
  2010. // suppose 'derived' is an object of type Derived, ByRef(derived)
  2011. // would wrap a Derived&. If you want to wrap a const Base& instead,
  2012. // where Base is a base class of Derived, just write:
  2013. //
  2014. // ByRef<const Base>(derived)
  2015. //
  2016. // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
  2017. // However, it may still be used for consistency with ByMove().
  2018. template <typename T>
  2019. inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
  2020. return ::std::reference_wrapper<T>(l_value);
  2021. }
  2022. // The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
  2023. // instance of type T, constructed on the heap with constructor arguments
  2024. // a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
  2025. template <typename T, typename... Params>
  2026. internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(
  2027. Params&&... params) {
  2028. return {std::forward_as_tuple(std::forward<Params>(params)...)};
  2029. }
  2030. // Action ReturnArg<k>() returns the k-th argument of the mock function.
  2031. template <size_t k>
  2032. internal::ReturnArgAction<k> ReturnArg() {
  2033. return {};
  2034. }
  2035. // Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
  2036. // mock function to *pointer.
  2037. template <size_t k, typename Ptr>
  2038. internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {
  2039. return {pointer};
  2040. }
  2041. // Action SaveArgPointee<k>(pointer) saves the value pointed to
  2042. // by the k-th (0-based) argument of the mock function to *pointer.
  2043. template <size_t k, typename Ptr>
  2044. internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) {
  2045. return {pointer};
  2046. }
  2047. // Action SetArgReferee<k>(value) assigns 'value' to the variable
  2048. // referenced by the k-th (0-based) argument of the mock function.
  2049. template <size_t k, typename T>
  2050. internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee(
  2051. T&& value) {
  2052. return {std::forward<T>(value)};
  2053. }
  2054. // Action SetArrayArgument<k>(first, last) copies the elements in
  2055. // source range [first, last) to the array pointed to by the k-th
  2056. // (0-based) argument, which can be either a pointer or an
  2057. // iterator. The action does not take ownership of the elements in the
  2058. // source range.
  2059. template <size_t k, typename I1, typename I2>
  2060. internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first,
  2061. I2 last) {
  2062. return {first, last};
  2063. }
  2064. // Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
  2065. // function.
  2066. template <size_t k>
  2067. internal::DeleteArgAction<k> DeleteArg() {
  2068. return {};
  2069. }
  2070. // This action returns the value pointed to by 'pointer'.
  2071. template <typename Ptr>
  2072. internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {
  2073. return {pointer};
  2074. }
  2075. // Action Throw(exception) can be used in a mock function of any type
  2076. // to throw the given exception. Any copyable value can be thrown.
  2077. #if GTEST_HAS_EXCEPTIONS
  2078. template <typename T>
  2079. internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) {
  2080. return {std::forward<T>(exception)};
  2081. }
  2082. #endif // GTEST_HAS_EXCEPTIONS
  2083. namespace internal {
  2084. // A macro from the ACTION* family (defined later in gmock-generated-actions.h)
  2085. // defines an action that can be used in a mock function. Typically,
  2086. // these actions only care about a subset of the arguments of the mock
  2087. // function. For example, if such an action only uses the second
  2088. // argument, it can be used in any mock function that takes >= 2
  2089. // arguments where the type of the second argument is compatible.
  2090. //
  2091. // Therefore, the action implementation must be prepared to take more
  2092. // arguments than it needs. The ExcessiveArg type is used to
  2093. // represent those excessive arguments. In order to keep the compiler
  2094. // error messages tractable, we define it in the testing namespace
  2095. // instead of testing::internal. However, this is an INTERNAL TYPE
  2096. // and subject to change without notice, so a user MUST NOT USE THIS
  2097. // TYPE DIRECTLY.
  2098. struct ExcessiveArg {};
  2099. // Builds an implementation of an Action<> for some particular signature, using
  2100. // a class defined by an ACTION* macro.
  2101. template <typename F, typename Impl> struct ActionImpl;
  2102. template <typename Impl>
  2103. struct ImplBase {
  2104. struct Holder {
  2105. // Allows each copy of the Action<> to get to the Impl.
  2106. explicit operator const Impl&() const { return *ptr; }
  2107. std::shared_ptr<Impl> ptr;
  2108. };
  2109. using type = typename std::conditional<std::is_constructible<Impl>::value,
  2110. Impl, Holder>::type;
  2111. };
  2112. template <typename R, typename... Args, typename Impl>
  2113. struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
  2114. using Base = typename ImplBase<Impl>::type;
  2115. using function_type = R(Args...);
  2116. using args_type = std::tuple<Args...>;
  2117. ActionImpl() = default; // Only defined if appropriate for Base.
  2118. explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} { }
  2119. R operator()(Args&&... arg) const {
  2120. static constexpr size_t kMaxArgs =
  2121. sizeof...(Args) <= 10 ? sizeof...(Args) : 10;
  2122. return Apply(MakeIndexSequence<kMaxArgs>{},
  2123. MakeIndexSequence<10 - kMaxArgs>{},
  2124. args_type{std::forward<Args>(arg)...});
  2125. }
  2126. template <std::size_t... arg_id, std::size_t... excess_id>
  2127. R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>,
  2128. const args_type& args) const {
  2129. // Impl need not be specific to the signature of action being implemented;
  2130. // only the implementing function body needs to have all of the specific
  2131. // types instantiated. Up to 10 of the args that are provided by the
  2132. // args_type get passed, followed by a dummy of unspecified type for the
  2133. // remainder up to 10 explicit args.
  2134. static constexpr ExcessiveArg kExcessArg{};
  2135. return static_cast<const Impl&>(*this).template gmock_PerformImpl<
  2136. /*function_type=*/function_type, /*return_type=*/R,
  2137. /*args_type=*/args_type,
  2138. /*argN_type=*/typename std::tuple_element<arg_id, args_type>::type...>(
  2139. /*args=*/args, std::get<arg_id>(args)...,
  2140. ((void)excess_id, kExcessArg)...);
  2141. }
  2142. };
  2143. // Stores a default-constructed Impl as part of the Action<>'s
  2144. // std::function<>. The Impl should be trivial to copy.
  2145. template <typename F, typename Impl>
  2146. ::testing::Action<F> MakeAction() {
  2147. return ::testing::Action<F>(ActionImpl<F, Impl>());
  2148. }
  2149. // Stores just the one given instance of Impl.
  2150. template <typename F, typename Impl>
  2151. ::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) {
  2152. return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl)));
  2153. }
  2154. #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
  2155. , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_
  2156. #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
  2157. const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
  2158. GMOCK_INTERNAL_ARG_UNUSED, , 10)
  2159. #define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
  2160. #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \
  2161. const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)
  2162. #define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type
  2163. #define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \
  2164. GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))
  2165. #define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type
  2166. #define GMOCK_ACTION_TYPENAME_PARAMS_(params) \
  2167. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))
  2168. #define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type
  2169. #define GMOCK_ACTION_TYPE_PARAMS_(params) \
  2170. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))
  2171. #define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \
  2172. , param##_type gmock_p##i
  2173. #define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \
  2174. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))
  2175. #define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \
  2176. , std::forward<param##_type>(gmock_p##i)
  2177. #define GMOCK_ACTION_GVALUE_PARAMS_(params) \
  2178. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))
  2179. #define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \
  2180. , param(::std::forward<param##_type>(gmock_p##i))
  2181. #define GMOCK_ACTION_INIT_PARAMS_(params) \
  2182. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))
  2183. #define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;
  2184. #define GMOCK_ACTION_FIELD_PARAMS_(params) \
  2185. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)
  2186. #define GMOCK_INTERNAL_ACTION(name, full_name, params) \
  2187. template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
  2188. class full_name { \
  2189. public: \
  2190. explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
  2191. : impl_(std::make_shared<gmock_Impl>( \
  2192. GMOCK_ACTION_GVALUE_PARAMS_(params))) { } \
  2193. full_name(const full_name&) = default; \
  2194. full_name(full_name&&) noexcept = default; \
  2195. template <typename F> \
  2196. operator ::testing::Action<F>() const { \
  2197. return ::testing::internal::MakeAction<F>(impl_); \
  2198. } \
  2199. private: \
  2200. class gmock_Impl { \
  2201. public: \
  2202. explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
  2203. : GMOCK_ACTION_INIT_PARAMS_(params) {} \
  2204. template <typename function_type, typename return_type, \
  2205. typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  2206. return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
  2207. GMOCK_ACTION_FIELD_PARAMS_(params) \
  2208. }; \
  2209. std::shared_ptr<const gmock_Impl> impl_; \
  2210. }; \
  2211. template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
  2212. inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
  2213. GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \
  2214. return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \
  2215. GMOCK_ACTION_GVALUE_PARAMS_(params)); \
  2216. } \
  2217. template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
  2218. template <typename function_type, typename return_type, typename args_type, \
  2219. GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  2220. return_type full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl:: \
  2221. gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
  2222. } // namespace internal
  2223. // Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored.
  2224. #define ACTION(name) \
  2225. class name##Action { \
  2226. public: \
  2227. explicit name##Action() noexcept {} \
  2228. name##Action(const name##Action&) noexcept {} \
  2229. template <typename F> \
  2230. operator ::testing::Action<F>() const { \
  2231. return ::testing::internal::MakeAction<F, gmock_Impl>(); \
  2232. } \
  2233. private: \
  2234. class gmock_Impl { \
  2235. public: \
  2236. template <typename function_type, typename return_type, \
  2237. typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  2238. return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
  2239. }; \
  2240. }; \
  2241. inline name##Action name() GTEST_MUST_USE_RESULT_; \
  2242. inline name##Action name() { return name##Action(); } \
  2243. template <typename function_type, typename return_type, typename args_type, \
  2244. GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  2245. return_type name##Action::gmock_Impl::gmock_PerformImpl( \
  2246. GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
  2247. #define ACTION_P(name, ...) \
  2248. GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))
  2249. #define ACTION_P2(name, ...) \
  2250. GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))
  2251. #define ACTION_P3(name, ...) \
  2252. GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))
  2253. #define ACTION_P4(name, ...) \
  2254. GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))
  2255. #define ACTION_P5(name, ...) \
  2256. GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))
  2257. #define ACTION_P6(name, ...) \
  2258. GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))
  2259. #define ACTION_P7(name, ...) \
  2260. GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))
  2261. #define ACTION_P8(name, ...) \
  2262. GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))
  2263. #define ACTION_P9(name, ...) \
  2264. GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))
  2265. #define ACTION_P10(name, ...) \
  2266. GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))
  2267. } // namespace testing
  2268. #ifdef _MSC_VER
  2269. # pragma warning(pop)
  2270. #endif
  2271. #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
  2272. // Copyright 2007, Google Inc.
  2273. // All rights reserved.
  2274. //
  2275. // Redistribution and use in source and binary forms, with or without
  2276. // modification, are permitted provided that the following conditions are
  2277. // met:
  2278. //
  2279. // * Redistributions of source code must retain the above copyright
  2280. // notice, this list of conditions and the following disclaimer.
  2281. // * Redistributions in binary form must reproduce the above
  2282. // copyright notice, this list of conditions and the following disclaimer
  2283. // in the documentation and/or other materials provided with the
  2284. // distribution.
  2285. // * Neither the name of Google Inc. nor the names of its
  2286. // contributors may be used to endorse or promote products derived from
  2287. // this software without specific prior written permission.
  2288. //
  2289. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2290. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2291. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2292. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2293. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2294. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2295. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2296. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2297. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2298. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2299. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2300. // Google Mock - a framework for writing C++ mock classes.
  2301. //
  2302. // This file implements some commonly used cardinalities. More
  2303. // cardinalities can be defined by the user implementing the
  2304. // CardinalityInterface interface if necessary.
  2305. // GOOGLETEST_CM0002 DO NOT DELETE
  2306. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
  2307. #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
  2308. #include <limits.h>
  2309. #include <memory>
  2310. #include <ostream> // NOLINT
  2311. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  2312. /* class A needs to have dll-interface to be used by clients of class B */)
  2313. namespace testing {
  2314. // To implement a cardinality Foo, define:
  2315. // 1. a class FooCardinality that implements the
  2316. // CardinalityInterface interface, and
  2317. // 2. a factory function that creates a Cardinality object from a
  2318. // const FooCardinality*.
  2319. //
  2320. // The two-level delegation design follows that of Matcher, providing
  2321. // consistency for extension developers. It also eases ownership
  2322. // management as Cardinality objects can now be copied like plain values.
  2323. // The implementation of a cardinality.
  2324. class CardinalityInterface {
  2325. public:
  2326. virtual ~CardinalityInterface() {}
  2327. // Conservative estimate on the lower/upper bound of the number of
  2328. // calls allowed.
  2329. virtual int ConservativeLowerBound() const { return 0; }
  2330. virtual int ConservativeUpperBound() const { return INT_MAX; }
  2331. // Returns true if and only if call_count calls will satisfy this
  2332. // cardinality.
  2333. virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
  2334. // Returns true if and only if call_count calls will saturate this
  2335. // cardinality.
  2336. virtual bool IsSaturatedByCallCount(int call_count) const = 0;
  2337. // Describes self to an ostream.
  2338. virtual void DescribeTo(::std::ostream* os) const = 0;
  2339. };
  2340. // A Cardinality is a copyable and IMMUTABLE (except by assignment)
  2341. // object that specifies how many times a mock function is expected to
  2342. // be called. The implementation of Cardinality is just a std::shared_ptr
  2343. // to const CardinalityInterface. Don't inherit from Cardinality!
  2344. class GTEST_API_ Cardinality {
  2345. public:
  2346. // Constructs a null cardinality. Needed for storing Cardinality
  2347. // objects in STL containers.
  2348. Cardinality() {}
  2349. // Constructs a Cardinality from its implementation.
  2350. explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}
  2351. // Conservative estimate on the lower/upper bound of the number of
  2352. // calls allowed.
  2353. int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); }
  2354. int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); }
  2355. // Returns true if and only if call_count calls will satisfy this
  2356. // cardinality.
  2357. bool IsSatisfiedByCallCount(int call_count) const {
  2358. return impl_->IsSatisfiedByCallCount(call_count);
  2359. }
  2360. // Returns true if and only if call_count calls will saturate this
  2361. // cardinality.
  2362. bool IsSaturatedByCallCount(int call_count) const {
  2363. return impl_->IsSaturatedByCallCount(call_count);
  2364. }
  2365. // Returns true if and only if call_count calls will over-saturate this
  2366. // cardinality, i.e. exceed the maximum number of allowed calls.
  2367. bool IsOverSaturatedByCallCount(int call_count) const {
  2368. return impl_->IsSaturatedByCallCount(call_count) &&
  2369. !impl_->IsSatisfiedByCallCount(call_count);
  2370. }
  2371. // Describes self to an ostream
  2372. void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
  2373. // Describes the given actual call count to an ostream.
  2374. static void DescribeActualCallCountTo(int actual_call_count,
  2375. ::std::ostream* os);
  2376. private:
  2377. std::shared_ptr<const CardinalityInterface> impl_;
  2378. };
  2379. // Creates a cardinality that allows at least n calls.
  2380. GTEST_API_ Cardinality AtLeast(int n);
  2381. // Creates a cardinality that allows at most n calls.
  2382. GTEST_API_ Cardinality AtMost(int n);
  2383. // Creates a cardinality that allows any number of calls.
  2384. GTEST_API_ Cardinality AnyNumber();
  2385. // Creates a cardinality that allows between min and max calls.
  2386. GTEST_API_ Cardinality Between(int min, int max);
  2387. // Creates a cardinality that allows exactly n calls.
  2388. GTEST_API_ Cardinality Exactly(int n);
  2389. // Creates a cardinality from its implementation.
  2390. inline Cardinality MakeCardinality(const CardinalityInterface* c) {
  2391. return Cardinality(c);
  2392. }
  2393. } // namespace testing
  2394. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  2395. #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
  2396. // Copyright 2007, Google Inc.
  2397. // All rights reserved.
  2398. //
  2399. // Redistribution and use in source and binary forms, with or without
  2400. // modification, are permitted provided that the following conditions are
  2401. // met:
  2402. //
  2403. // * Redistributions of source code must retain the above copyright
  2404. // notice, this list of conditions and the following disclaimer.
  2405. // * Redistributions in binary form must reproduce the above
  2406. // copyright notice, this list of conditions and the following disclaimer
  2407. // in the documentation and/or other materials provided with the
  2408. // distribution.
  2409. // * Neither the name of Google Inc. nor the names of its
  2410. // contributors may be used to endorse or promote products derived from
  2411. // this software without specific prior written permission.
  2412. //
  2413. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2414. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2415. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2416. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2417. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2418. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2419. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2420. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2421. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2422. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2423. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2424. // Google Mock - a framework for writing C++ mock classes.
  2425. //
  2426. // This file implements MOCK_METHOD.
  2427. // GOOGLETEST_CM0002 DO NOT DELETE
  2428. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
  2429. #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
  2430. #include <type_traits> // IWYU pragma: keep
  2431. #include <utility> // IWYU pragma: keep
  2432. // Copyright 2007, Google Inc.
  2433. // All rights reserved.
  2434. //
  2435. // Redistribution and use in source and binary forms, with or without
  2436. // modification, are permitted provided that the following conditions are
  2437. // met:
  2438. //
  2439. // * Redistributions of source code must retain the above copyright
  2440. // notice, this list of conditions and the following disclaimer.
  2441. // * Redistributions in binary form must reproduce the above
  2442. // copyright notice, this list of conditions and the following disclaimer
  2443. // in the documentation and/or other materials provided with the
  2444. // distribution.
  2445. // * Neither the name of Google Inc. nor the names of its
  2446. // contributors may be used to endorse or promote products derived from
  2447. // this software without specific prior written permission.
  2448. //
  2449. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2450. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2451. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2452. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2453. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2454. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2455. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2456. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2457. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2458. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2459. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2460. // Google Mock - a framework for writing C++ mock classes.
  2461. //
  2462. // This file implements the ON_CALL() and EXPECT_CALL() macros.
  2463. //
  2464. // A user can use the ON_CALL() macro to specify the default action of
  2465. // a mock method. The syntax is:
  2466. //
  2467. // ON_CALL(mock_object, Method(argument-matchers))
  2468. // .With(multi-argument-matcher)
  2469. // .WillByDefault(action);
  2470. //
  2471. // where the .With() clause is optional.
  2472. //
  2473. // A user can use the EXPECT_CALL() macro to specify an expectation on
  2474. // a mock method. The syntax is:
  2475. //
  2476. // EXPECT_CALL(mock_object, Method(argument-matchers))
  2477. // .With(multi-argument-matchers)
  2478. // .Times(cardinality)
  2479. // .InSequence(sequences)
  2480. // .After(expectations)
  2481. // .WillOnce(action)
  2482. // .WillRepeatedly(action)
  2483. // .RetiresOnSaturation();
  2484. //
  2485. // where all clauses are optional, and .InSequence()/.After()/
  2486. // .WillOnce() can appear any number of times.
  2487. // GOOGLETEST_CM0002 DO NOT DELETE
  2488. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
  2489. #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
  2490. #include <functional>
  2491. #include <map>
  2492. #include <memory>
  2493. #include <set>
  2494. #include <sstream>
  2495. #include <string>
  2496. #include <type_traits>
  2497. #include <utility>
  2498. #include <vector>
  2499. // Copyright 2007, Google Inc.
  2500. // All rights reserved.
  2501. //
  2502. // Redistribution and use in source and binary forms, with or without
  2503. // modification, are permitted provided that the following conditions are
  2504. // met:
  2505. //
  2506. // * Redistributions of source code must retain the above copyright
  2507. // notice, this list of conditions and the following disclaimer.
  2508. // * Redistributions in binary form must reproduce the above
  2509. // copyright notice, this list of conditions and the following disclaimer
  2510. // in the documentation and/or other materials provided with the
  2511. // distribution.
  2512. // * Neither the name of Google Inc. nor the names of its
  2513. // contributors may be used to endorse or promote products derived from
  2514. // this software without specific prior written permission.
  2515. //
  2516. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2517. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2518. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2519. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2520. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2521. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2522. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2523. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2524. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2525. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2526. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2527. // Google Mock - a framework for writing C++ mock classes.
  2528. //
  2529. // The MATCHER* family of macros can be used in a namespace scope to
  2530. // define custom matchers easily.
  2531. //
  2532. // Basic Usage
  2533. // ===========
  2534. //
  2535. // The syntax
  2536. //
  2537. // MATCHER(name, description_string) { statements; }
  2538. //
  2539. // defines a matcher with the given name that executes the statements,
  2540. // which must return a bool to indicate if the match succeeds. Inside
  2541. // the statements, you can refer to the value being matched by 'arg',
  2542. // and refer to its type by 'arg_type'.
  2543. //
  2544. // The description string documents what the matcher does, and is used
  2545. // to generate the failure message when the match fails. Since a
  2546. // MATCHER() is usually defined in a header file shared by multiple
  2547. // C++ source files, we require the description to be a C-string
  2548. // literal to avoid possible side effects. It can be empty, in which
  2549. // case we'll use the sequence of words in the matcher name as the
  2550. // description.
  2551. //
  2552. // For example:
  2553. //
  2554. // MATCHER(IsEven, "") { return (arg % 2) == 0; }
  2555. //
  2556. // allows you to write
  2557. //
  2558. // // Expects mock_foo.Bar(n) to be called where n is even.
  2559. // EXPECT_CALL(mock_foo, Bar(IsEven()));
  2560. //
  2561. // or,
  2562. //
  2563. // // Verifies that the value of some_expression is even.
  2564. // EXPECT_THAT(some_expression, IsEven());
  2565. //
  2566. // If the above assertion fails, it will print something like:
  2567. //
  2568. // Value of: some_expression
  2569. // Expected: is even
  2570. // Actual: 7
  2571. //
  2572. // where the description "is even" is automatically calculated from the
  2573. // matcher name IsEven.
  2574. //
  2575. // Argument Type
  2576. // =============
  2577. //
  2578. // Note that the type of the value being matched (arg_type) is
  2579. // determined by the context in which you use the matcher and is
  2580. // supplied to you by the compiler, so you don't need to worry about
  2581. // declaring it (nor can you). This allows the matcher to be
  2582. // polymorphic. For example, IsEven() can be used to match any type
  2583. // where the value of "(arg % 2) == 0" can be implicitly converted to
  2584. // a bool. In the "Bar(IsEven())" example above, if method Bar()
  2585. // takes an int, 'arg_type' will be int; if it takes an unsigned long,
  2586. // 'arg_type' will be unsigned long; and so on.
  2587. //
  2588. // Parameterizing Matchers
  2589. // =======================
  2590. //
  2591. // Sometimes you'll want to parameterize the matcher. For that you
  2592. // can use another macro:
  2593. //
  2594. // MATCHER_P(name, param_name, description_string) { statements; }
  2595. //
  2596. // For example:
  2597. //
  2598. // MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
  2599. //
  2600. // will allow you to write:
  2601. //
  2602. // EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
  2603. //
  2604. // which may lead to this message (assuming n is 10):
  2605. //
  2606. // Value of: Blah("a")
  2607. // Expected: has absolute value 10
  2608. // Actual: -9
  2609. //
  2610. // Note that both the matcher description and its parameter are
  2611. // printed, making the message human-friendly.
  2612. //
  2613. // In the matcher definition body, you can write 'foo_type' to
  2614. // reference the type of a parameter named 'foo'. For example, in the
  2615. // body of MATCHER_P(HasAbsoluteValue, value) above, you can write
  2616. // 'value_type' to refer to the type of 'value'.
  2617. //
  2618. // We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
  2619. // support multi-parameter matchers.
  2620. //
  2621. // Describing Parameterized Matchers
  2622. // =================================
  2623. //
  2624. // The last argument to MATCHER*() is a string-typed expression. The
  2625. // expression can reference all of the matcher's parameters and a
  2626. // special bool-typed variable named 'negation'. When 'negation' is
  2627. // false, the expression should evaluate to the matcher's description;
  2628. // otherwise it should evaluate to the description of the negation of
  2629. // the matcher. For example,
  2630. //
  2631. // using testing::PrintToString;
  2632. //
  2633. // MATCHER_P2(InClosedRange, low, hi,
  2634. // std::string(negation ? "is not" : "is") + " in range [" +
  2635. // PrintToString(low) + ", " + PrintToString(hi) + "]") {
  2636. // return low <= arg && arg <= hi;
  2637. // }
  2638. // ...
  2639. // EXPECT_THAT(3, InClosedRange(4, 6));
  2640. // EXPECT_THAT(3, Not(InClosedRange(2, 4)));
  2641. //
  2642. // would generate two failures that contain the text:
  2643. //
  2644. // Expected: is in range [4, 6]
  2645. // ...
  2646. // Expected: is not in range [2, 4]
  2647. //
  2648. // If you specify "" as the description, the failure message will
  2649. // contain the sequence of words in the matcher name followed by the
  2650. // parameter values printed as a tuple. For example,
  2651. //
  2652. // MATCHER_P2(InClosedRange, low, hi, "") { ... }
  2653. // ...
  2654. // EXPECT_THAT(3, InClosedRange(4, 6));
  2655. // EXPECT_THAT(3, Not(InClosedRange(2, 4)));
  2656. //
  2657. // would generate two failures that contain the text:
  2658. //
  2659. // Expected: in closed range (4, 6)
  2660. // ...
  2661. // Expected: not (in closed range (2, 4))
  2662. //
  2663. // Types of Matcher Parameters
  2664. // ===========================
  2665. //
  2666. // For the purpose of typing, you can view
  2667. //
  2668. // MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
  2669. //
  2670. // as shorthand for
  2671. //
  2672. // template <typename p1_type, ..., typename pk_type>
  2673. // FooMatcherPk<p1_type, ..., pk_type>
  2674. // Foo(p1_type p1, ..., pk_type pk) { ... }
  2675. //
  2676. // When you write Foo(v1, ..., vk), the compiler infers the types of
  2677. // the parameters v1, ..., and vk for you. If you are not happy with
  2678. // the result of the type inference, you can specify the types by
  2679. // explicitly instantiating the template, as in Foo<long, bool>(5,
  2680. // false). As said earlier, you don't get to (or need to) specify
  2681. // 'arg_type' as that's determined by the context in which the matcher
  2682. // is used. You can assign the result of expression Foo(p1, ..., pk)
  2683. // to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This
  2684. // can be useful when composing matchers.
  2685. //
  2686. // While you can instantiate a matcher template with reference types,
  2687. // passing the parameters by pointer usually makes your code more
  2688. // readable. If, however, you still want to pass a parameter by
  2689. // reference, be aware that in the failure message generated by the
  2690. // matcher you will see the value of the referenced object but not its
  2691. // address.
  2692. //
  2693. // Explaining Match Results
  2694. // ========================
  2695. //
  2696. // Sometimes the matcher description alone isn't enough to explain why
  2697. // the match has failed or succeeded. For example, when expecting a
  2698. // long string, it can be very helpful to also print the diff between
  2699. // the expected string and the actual one. To achieve that, you can
  2700. // optionally stream additional information to a special variable
  2701. // named result_listener, whose type is a pointer to class
  2702. // MatchResultListener:
  2703. //
  2704. // MATCHER_P(EqualsLongString, str, "") {
  2705. // if (arg == str) return true;
  2706. //
  2707. // *result_listener << "the difference: "
  2708. /// << DiffStrings(str, arg);
  2709. // return false;
  2710. // }
  2711. //
  2712. // Overloading Matchers
  2713. // ====================
  2714. //
  2715. // You can overload matchers with different numbers of parameters:
  2716. //
  2717. // MATCHER_P(Blah, a, description_string1) { ... }
  2718. // MATCHER_P2(Blah, a, b, description_string2) { ... }
  2719. //
  2720. // Caveats
  2721. // =======
  2722. //
  2723. // When defining a new matcher, you should also consider implementing
  2724. // MatcherInterface or using MakePolymorphicMatcher(). These
  2725. // approaches require more work than the MATCHER* macros, but also
  2726. // give you more control on the types of the value being matched and
  2727. // the matcher parameters, which may leads to better compiler error
  2728. // messages when the matcher is used wrong. They also allow
  2729. // overloading matchers based on parameter types (as opposed to just
  2730. // based on the number of parameters).
  2731. //
  2732. // MATCHER*() can only be used in a namespace scope as templates cannot be
  2733. // declared inside of a local class.
  2734. //
  2735. // More Information
  2736. // ================
  2737. //
  2738. // To learn more about using these macros, please search for 'MATCHER'
  2739. // on
  2740. // https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
  2741. //
  2742. // This file also implements some commonly used argument matchers. More
  2743. // matchers can be defined by the user implementing the
  2744. // MatcherInterface<T> interface if necessary.
  2745. //
  2746. // See googletest/include/gtest/gtest-matchers.h for the definition of class
  2747. // Matcher, class MatcherInterface, and others.
  2748. // GOOGLETEST_CM0002 DO NOT DELETE
  2749. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
  2750. #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
  2751. #include <algorithm>
  2752. #include <cmath>
  2753. #include <initializer_list>
  2754. #include <iterator>
  2755. #include <limits>
  2756. #include <memory>
  2757. #include <ostream> // NOLINT
  2758. #include <sstream>
  2759. #include <string>
  2760. #include <type_traits>
  2761. #include <utility>
  2762. #include <vector>
  2763. // MSVC warning C5046 is new as of VS2017 version 15.8.
  2764. #if defined(_MSC_VER) && _MSC_VER >= 1915
  2765. #define GMOCK_MAYBE_5046_ 5046
  2766. #else
  2767. #define GMOCK_MAYBE_5046_
  2768. #endif
  2769. GTEST_DISABLE_MSC_WARNINGS_PUSH_(
  2770. 4251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by
  2771. clients of class B */
  2772. /* Symbol involving type with internal linkage not defined */)
  2773. namespace testing {
  2774. // To implement a matcher Foo for type T, define:
  2775. // 1. a class FooMatcherImpl that implements the
  2776. // MatcherInterface<T> interface, and
  2777. // 2. a factory function that creates a Matcher<T> object from a
  2778. // FooMatcherImpl*.
  2779. //
  2780. // The two-level delegation design makes it possible to allow a user
  2781. // to write "v" instead of "Eq(v)" where a Matcher is expected, which
  2782. // is impossible if we pass matchers by pointers. It also eases
  2783. // ownership management as Matcher objects can now be copied like
  2784. // plain values.
  2785. // A match result listener that stores the explanation in a string.
  2786. class StringMatchResultListener : public MatchResultListener {
  2787. public:
  2788. StringMatchResultListener() : MatchResultListener(&ss_) {}
  2789. // Returns the explanation accumulated so far.
  2790. std::string str() const { return ss_.str(); }
  2791. // Clears the explanation accumulated so far.
  2792. void Clear() { ss_.str(""); }
  2793. private:
  2794. ::std::stringstream ss_;
  2795. GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
  2796. };
  2797. // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
  2798. // and MUST NOT BE USED IN USER CODE!!!
  2799. namespace internal {
  2800. // The MatcherCastImpl class template is a helper for implementing
  2801. // MatcherCast(). We need this helper in order to partially
  2802. // specialize the implementation of MatcherCast() (C++ allows
  2803. // class/struct templates to be partially specialized, but not
  2804. // function templates.).
  2805. // This general version is used when MatcherCast()'s argument is a
  2806. // polymorphic matcher (i.e. something that can be converted to a
  2807. // Matcher but is not one yet; for example, Eq(value)) or a value (for
  2808. // example, "hello").
  2809. template <typename T, typename M>
  2810. class MatcherCastImpl {
  2811. public:
  2812. static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
  2813. // M can be a polymorphic matcher, in which case we want to use
  2814. // its conversion operator to create Matcher<T>. Or it can be a value
  2815. // that should be passed to the Matcher<T>'s constructor.
  2816. //
  2817. // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
  2818. // polymorphic matcher because it'll be ambiguous if T has an implicit
  2819. // constructor from M (this usually happens when T has an implicit
  2820. // constructor from any type).
  2821. //
  2822. // It won't work to unconditionally implicit_cast
  2823. // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
  2824. // a user-defined conversion from M to T if one exists (assuming M is
  2825. // a value).
  2826. return CastImpl(polymorphic_matcher_or_value,
  2827. std::is_convertible<M, Matcher<T>>{},
  2828. std::is_convertible<M, T>{});
  2829. }
  2830. private:
  2831. template <bool Ignore>
  2832. static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
  2833. std::true_type /* convertible_to_matcher */,
  2834. std::integral_constant<bool, Ignore>) {
  2835. // M is implicitly convertible to Matcher<T>, which means that either
  2836. // M is a polymorphic matcher or Matcher<T> has an implicit constructor
  2837. // from M. In both cases using the implicit conversion will produce a
  2838. // matcher.
  2839. //
  2840. // Even if T has an implicit constructor from M, it won't be called because
  2841. // creating Matcher<T> would require a chain of two user-defined conversions
  2842. // (first to create T from M and then to create Matcher<T> from T).
  2843. return polymorphic_matcher_or_value;
  2844. }
  2845. // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
  2846. // matcher. It's a value of a type implicitly convertible to T. Use direct
  2847. // initialization to create a matcher.
  2848. static Matcher<T> CastImpl(const M& value,
  2849. std::false_type /* convertible_to_matcher */,
  2850. std::true_type /* convertible_to_T */) {
  2851. return Matcher<T>(ImplicitCast_<T>(value));
  2852. }
  2853. // M can't be implicitly converted to either Matcher<T> or T. Attempt to use
  2854. // polymorphic matcher Eq(value) in this case.
  2855. //
  2856. // Note that we first attempt to perform an implicit cast on the value and
  2857. // only fall back to the polymorphic Eq() matcher afterwards because the
  2858. // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end
  2859. // which might be undefined even when Rhs is implicitly convertible to Lhs
  2860. // (e.g. std::pair<const int, int> vs. std::pair<int, int>).
  2861. //
  2862. // We don't define this method inline as we need the declaration of Eq().
  2863. static Matcher<T> CastImpl(const M& value,
  2864. std::false_type /* convertible_to_matcher */,
  2865. std::false_type /* convertible_to_T */);
  2866. };
  2867. // This more specialized version is used when MatcherCast()'s argument
  2868. // is already a Matcher. This only compiles when type T can be
  2869. // statically converted to type U.
  2870. template <typename T, typename U>
  2871. class MatcherCastImpl<T, Matcher<U> > {
  2872. public:
  2873. static Matcher<T> Cast(const Matcher<U>& source_matcher) {
  2874. return Matcher<T>(new Impl(source_matcher));
  2875. }
  2876. private:
  2877. class Impl : public MatcherInterface<T> {
  2878. public:
  2879. explicit Impl(const Matcher<U>& source_matcher)
  2880. : source_matcher_(source_matcher) {}
  2881. // We delegate the matching logic to the source matcher.
  2882. bool MatchAndExplain(T x, MatchResultListener* listener) const override {
  2883. using FromType = typename std::remove_cv<typename std::remove_pointer<
  2884. typename std::remove_reference<T>::type>::type>::type;
  2885. using ToType = typename std::remove_cv<typename std::remove_pointer<
  2886. typename std::remove_reference<U>::type>::type>::type;
  2887. // Do not allow implicitly converting base*/& to derived*/&.
  2888. static_assert(
  2889. // Do not trigger if only one of them is a pointer. That implies a
  2890. // regular conversion and not a down_cast.
  2891. (std::is_pointer<typename std::remove_reference<T>::type>::value !=
  2892. std::is_pointer<typename std::remove_reference<U>::type>::value) ||
  2893. std::is_same<FromType, ToType>::value ||
  2894. !std::is_base_of<FromType, ToType>::value,
  2895. "Can't implicitly convert from <base> to <derived>");
  2896. // Do the cast to `U` explicitly if necessary.
  2897. // Otherwise, let implicit conversions do the trick.
  2898. using CastType =
  2899. typename std::conditional<std::is_convertible<T&, const U&>::value,
  2900. T&, U>::type;
  2901. return source_matcher_.MatchAndExplain(static_cast<CastType>(x),
  2902. listener);
  2903. }
  2904. void DescribeTo(::std::ostream* os) const override {
  2905. source_matcher_.DescribeTo(os);
  2906. }
  2907. void DescribeNegationTo(::std::ostream* os) const override {
  2908. source_matcher_.DescribeNegationTo(os);
  2909. }
  2910. private:
  2911. const Matcher<U> source_matcher_;
  2912. };
  2913. };
  2914. // This even more specialized version is used for efficiently casting
  2915. // a matcher to its own type.
  2916. template <typename T>
  2917. class MatcherCastImpl<T, Matcher<T> > {
  2918. public:
  2919. static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
  2920. };
  2921. // Template specialization for parameterless Matcher.
  2922. template <typename Derived>
  2923. class MatcherBaseImpl {
  2924. public:
  2925. MatcherBaseImpl() = default;
  2926. template <typename T>
  2927. operator ::testing::Matcher<T>() const { // NOLINT(runtime/explicit)
  2928. return ::testing::Matcher<T>(new
  2929. typename Derived::template gmock_Impl<T>());
  2930. }
  2931. };
  2932. // Template specialization for Matcher with parameters.
  2933. template <template <typename...> class Derived, typename... Ts>
  2934. class MatcherBaseImpl<Derived<Ts...>> {
  2935. public:
  2936. // Mark the constructor explicit for single argument T to avoid implicit
  2937. // conversions.
  2938. template <typename E = std::enable_if<sizeof...(Ts) == 1>,
  2939. typename E::type* = nullptr>
  2940. explicit MatcherBaseImpl(Ts... params)
  2941. : params_(std::forward<Ts>(params)...) {}
  2942. template <typename E = std::enable_if<sizeof...(Ts) != 1>,
  2943. typename = typename E::type>
  2944. MatcherBaseImpl(Ts... params) // NOLINT
  2945. : params_(std::forward<Ts>(params)...) {}
  2946. template <typename F>
  2947. operator ::testing::Matcher<F>() const { // NOLINT(runtime/explicit)
  2948. return Apply<F>(MakeIndexSequence<sizeof...(Ts)>{});
  2949. }
  2950. private:
  2951. template <typename F, std::size_t... tuple_ids>
  2952. ::testing::Matcher<F> Apply(IndexSequence<tuple_ids...>) const {
  2953. return ::testing::Matcher<F>(
  2954. new typename Derived<Ts...>::template gmock_Impl<F>(
  2955. std::get<tuple_ids>(params_)...));
  2956. }
  2957. const std::tuple<Ts...> params_;
  2958. };
  2959. } // namespace internal
  2960. // In order to be safe and clear, casting between different matcher
  2961. // types is done explicitly via MatcherCast<T>(m), which takes a
  2962. // matcher m and returns a Matcher<T>. It compiles only when T can be
  2963. // statically converted to the argument type of m.
  2964. template <typename T, typename M>
  2965. inline Matcher<T> MatcherCast(const M& matcher) {
  2966. return internal::MatcherCastImpl<T, M>::Cast(matcher);
  2967. }
  2968. // This overload handles polymorphic matchers and values only since
  2969. // monomorphic matchers are handled by the next one.
  2970. template <typename T, typename M>
  2971. inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher_or_value) {
  2972. return MatcherCast<T>(polymorphic_matcher_or_value);
  2973. }
  2974. // This overload handles monomorphic matchers.
  2975. //
  2976. // In general, if type T can be implicitly converted to type U, we can
  2977. // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
  2978. // contravariant): just keep a copy of the original Matcher<U>, convert the
  2979. // argument from type T to U, and then pass it to the underlying Matcher<U>.
  2980. // The only exception is when U is a reference and T is not, as the
  2981. // underlying Matcher<U> may be interested in the argument's address, which
  2982. // is not preserved in the conversion from T to U.
  2983. template <typename T, typename U>
  2984. inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
  2985. // Enforce that T can be implicitly converted to U.
  2986. static_assert(std::is_convertible<const T&, const U&>::value,
  2987. "T must be implicitly convertible to U");
  2988. // Enforce that we are not converting a non-reference type T to a reference
  2989. // type U.
  2990. GTEST_COMPILE_ASSERT_(
  2991. std::is_reference<T>::value || !std::is_reference<U>::value,
  2992. cannot_convert_non_reference_arg_to_reference);
  2993. // In case both T and U are arithmetic types, enforce that the
  2994. // conversion is not lossy.
  2995. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
  2996. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
  2997. constexpr bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
  2998. constexpr bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
  2999. GTEST_COMPILE_ASSERT_(
  3000. kTIsOther || kUIsOther ||
  3001. (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
  3002. conversion_of_arithmetic_types_must_be_lossless);
  3003. return MatcherCast<T>(matcher);
  3004. }
  3005. // A<T>() returns a matcher that matches any value of type T.
  3006. template <typename T>
  3007. Matcher<T> A();
  3008. // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
  3009. // and MUST NOT BE USED IN USER CODE!!!
  3010. namespace internal {
  3011. // If the explanation is not empty, prints it to the ostream.
  3012. inline void PrintIfNotEmpty(const std::string& explanation,
  3013. ::std::ostream* os) {
  3014. if (explanation != "" && os != nullptr) {
  3015. *os << ", " << explanation;
  3016. }
  3017. }
  3018. // Returns true if the given type name is easy to read by a human.
  3019. // This is used to decide whether printing the type of a value might
  3020. // be helpful.
  3021. inline bool IsReadableTypeName(const std::string& type_name) {
  3022. // We consider a type name readable if it's short or doesn't contain
  3023. // a template or function type.
  3024. return (type_name.length() <= 20 ||
  3025. type_name.find_first_of("<(") == std::string::npos);
  3026. }
  3027. // Matches the value against the given matcher, prints the value and explains
  3028. // the match result to the listener. Returns the match result.
  3029. // 'listener' must not be NULL.
  3030. // Value cannot be passed by const reference, because some matchers take a
  3031. // non-const argument.
  3032. template <typename Value, typename T>
  3033. bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
  3034. MatchResultListener* listener) {
  3035. if (!listener->IsInterested()) {
  3036. // If the listener is not interested, we do not need to construct the
  3037. // inner explanation.
  3038. return matcher.Matches(value);
  3039. }
  3040. StringMatchResultListener inner_listener;
  3041. const bool match = matcher.MatchAndExplain(value, &inner_listener);
  3042. UniversalPrint(value, listener->stream());
  3043. #if GTEST_HAS_RTTI
  3044. const std::string& type_name = GetTypeName<Value>();
  3045. if (IsReadableTypeName(type_name))
  3046. *listener->stream() << " (of type " << type_name << ")";
  3047. #endif
  3048. PrintIfNotEmpty(inner_listener.str(), listener->stream());
  3049. return match;
  3050. }
  3051. // An internal helper class for doing compile-time loop on a tuple's
  3052. // fields.
  3053. template <size_t N>
  3054. class TuplePrefix {
  3055. public:
  3056. // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
  3057. // if and only if the first N fields of matcher_tuple matches
  3058. // the first N fields of value_tuple, respectively.
  3059. template <typename MatcherTuple, typename ValueTuple>
  3060. static bool Matches(const MatcherTuple& matcher_tuple,
  3061. const ValueTuple& value_tuple) {
  3062. return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) &&
  3063. std::get<N - 1>(matcher_tuple).Matches(std::get<N - 1>(value_tuple));
  3064. }
  3065. // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
  3066. // describes failures in matching the first N fields of matchers
  3067. // against the first N fields of values. If there is no failure,
  3068. // nothing will be streamed to os.
  3069. template <typename MatcherTuple, typename ValueTuple>
  3070. static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
  3071. const ValueTuple& values,
  3072. ::std::ostream* os) {
  3073. // First, describes failures in the first N - 1 fields.
  3074. TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
  3075. // Then describes the failure (if any) in the (N - 1)-th (0-based)
  3076. // field.
  3077. typename std::tuple_element<N - 1, MatcherTuple>::type matcher =
  3078. std::get<N - 1>(matchers);
  3079. typedef typename std::tuple_element<N - 1, ValueTuple>::type Value;
  3080. const Value& value = std::get<N - 1>(values);
  3081. StringMatchResultListener listener;
  3082. if (!matcher.MatchAndExplain(value, &listener)) {
  3083. *os << " Expected arg #" << N - 1 << ": ";
  3084. std::get<N - 1>(matchers).DescribeTo(os);
  3085. *os << "\n Actual: ";
  3086. // We remove the reference in type Value to prevent the
  3087. // universal printer from printing the address of value, which
  3088. // isn't interesting to the user most of the time. The
  3089. // matcher's MatchAndExplain() method handles the case when
  3090. // the address is interesting.
  3091. internal::UniversalPrint(value, os);
  3092. PrintIfNotEmpty(listener.str(), os);
  3093. *os << "\n";
  3094. }
  3095. }
  3096. };
  3097. // The base case.
  3098. template <>
  3099. class TuplePrefix<0> {
  3100. public:
  3101. template <typename MatcherTuple, typename ValueTuple>
  3102. static bool Matches(const MatcherTuple& /* matcher_tuple */,
  3103. const ValueTuple& /* value_tuple */) {
  3104. return true;
  3105. }
  3106. template <typename MatcherTuple, typename ValueTuple>
  3107. static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
  3108. const ValueTuple& /* values */,
  3109. ::std::ostream* /* os */) {}
  3110. };
  3111. // TupleMatches(matcher_tuple, value_tuple) returns true if and only if
  3112. // all matchers in matcher_tuple match the corresponding fields in
  3113. // value_tuple. It is a compiler error if matcher_tuple and
  3114. // value_tuple have different number of fields or incompatible field
  3115. // types.
  3116. template <typename MatcherTuple, typename ValueTuple>
  3117. bool TupleMatches(const MatcherTuple& matcher_tuple,
  3118. const ValueTuple& value_tuple) {
  3119. // Makes sure that matcher_tuple and value_tuple have the same
  3120. // number of fields.
  3121. GTEST_COMPILE_ASSERT_(std::tuple_size<MatcherTuple>::value ==
  3122. std::tuple_size<ValueTuple>::value,
  3123. matcher_and_value_have_different_numbers_of_fields);
  3124. return TuplePrefix<std::tuple_size<ValueTuple>::value>::Matches(matcher_tuple,
  3125. value_tuple);
  3126. }
  3127. // Describes failures in matching matchers against values. If there
  3128. // is no failure, nothing will be streamed to os.
  3129. template <typename MatcherTuple, typename ValueTuple>
  3130. void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
  3131. const ValueTuple& values,
  3132. ::std::ostream* os) {
  3133. TuplePrefix<std::tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
  3134. matchers, values, os);
  3135. }
  3136. // TransformTupleValues and its helper.
  3137. //
  3138. // TransformTupleValuesHelper hides the internal machinery that
  3139. // TransformTupleValues uses to implement a tuple traversal.
  3140. template <typename Tuple, typename Func, typename OutIter>
  3141. class TransformTupleValuesHelper {
  3142. private:
  3143. typedef ::std::tuple_size<Tuple> TupleSize;
  3144. public:
  3145. // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
  3146. // Returns the final value of 'out' in case the caller needs it.
  3147. static OutIter Run(Func f, const Tuple& t, OutIter out) {
  3148. return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
  3149. }
  3150. private:
  3151. template <typename Tup, size_t kRemainingSize>
  3152. struct IterateOverTuple {
  3153. OutIter operator() (Func f, const Tup& t, OutIter out) const {
  3154. *out++ = f(::std::get<TupleSize::value - kRemainingSize>(t));
  3155. return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
  3156. }
  3157. };
  3158. template <typename Tup>
  3159. struct IterateOverTuple<Tup, 0> {
  3160. OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
  3161. return out;
  3162. }
  3163. };
  3164. };
  3165. // Successively invokes 'f(element)' on each element of the tuple 't',
  3166. // appending each result to the 'out' iterator. Returns the final value
  3167. // of 'out'.
  3168. template <typename Tuple, typename Func, typename OutIter>
  3169. OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
  3170. return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
  3171. }
  3172. // Implements _, a matcher that matches any value of any
  3173. // type. This is a polymorphic matcher, so we need a template type
  3174. // conversion operator to make it appearing as a Matcher<T> for any
  3175. // type T.
  3176. class AnythingMatcher {
  3177. public:
  3178. using is_gtest_matcher = void;
  3179. template <typename T>
  3180. bool MatchAndExplain(const T& /* x */, std::ostream* /* listener */) const {
  3181. return true;
  3182. }
  3183. void DescribeTo(std::ostream* os) const { *os << "is anything"; }
  3184. void DescribeNegationTo(::std::ostream* os) const {
  3185. // This is mostly for completeness' sake, as it's not very useful
  3186. // to write Not(A<bool>()). However we cannot completely rule out
  3187. // such a possibility, and it doesn't hurt to be prepared.
  3188. *os << "never matches";
  3189. }
  3190. };
  3191. // Implements the polymorphic IsNull() matcher, which matches any raw or smart
  3192. // pointer that is NULL.
  3193. class IsNullMatcher {
  3194. public:
  3195. template <typename Pointer>
  3196. bool MatchAndExplain(const Pointer& p,
  3197. MatchResultListener* /* listener */) const {
  3198. return p == nullptr;
  3199. }
  3200. void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
  3201. void DescribeNegationTo(::std::ostream* os) const {
  3202. *os << "isn't NULL";
  3203. }
  3204. };
  3205. // Implements the polymorphic NotNull() matcher, which matches any raw or smart
  3206. // pointer that is not NULL.
  3207. class NotNullMatcher {
  3208. public:
  3209. template <typename Pointer>
  3210. bool MatchAndExplain(const Pointer& p,
  3211. MatchResultListener* /* listener */) const {
  3212. return p != nullptr;
  3213. }
  3214. void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
  3215. void DescribeNegationTo(::std::ostream* os) const {
  3216. *os << "is NULL";
  3217. }
  3218. };
  3219. // Ref(variable) matches any argument that is a reference to
  3220. // 'variable'. This matcher is polymorphic as it can match any
  3221. // super type of the type of 'variable'.
  3222. //
  3223. // The RefMatcher template class implements Ref(variable). It can
  3224. // only be instantiated with a reference type. This prevents a user
  3225. // from mistakenly using Ref(x) to match a non-reference function
  3226. // argument. For example, the following will righteously cause a
  3227. // compiler error:
  3228. //
  3229. // int n;
  3230. // Matcher<int> m1 = Ref(n); // This won't compile.
  3231. // Matcher<int&> m2 = Ref(n); // This will compile.
  3232. template <typename T>
  3233. class RefMatcher;
  3234. template <typename T>
  3235. class RefMatcher<T&> {
  3236. // Google Mock is a generic framework and thus needs to support
  3237. // mocking any function types, including those that take non-const
  3238. // reference arguments. Therefore the template parameter T (and
  3239. // Super below) can be instantiated to either a const type or a
  3240. // non-const type.
  3241. public:
  3242. // RefMatcher() takes a T& instead of const T&, as we want the
  3243. // compiler to catch using Ref(const_value) as a matcher for a
  3244. // non-const reference.
  3245. explicit RefMatcher(T& x) : object_(x) {} // NOLINT
  3246. template <typename Super>
  3247. operator Matcher<Super&>() const {
  3248. // By passing object_ (type T&) to Impl(), which expects a Super&,
  3249. // we make sure that Super is a super type of T. In particular,
  3250. // this catches using Ref(const_value) as a matcher for a
  3251. // non-const reference, as you cannot implicitly convert a const
  3252. // reference to a non-const reference.
  3253. return MakeMatcher(new Impl<Super>(object_));
  3254. }
  3255. private:
  3256. template <typename Super>
  3257. class Impl : public MatcherInterface<Super&> {
  3258. public:
  3259. explicit Impl(Super& x) : object_(x) {} // NOLINT
  3260. // MatchAndExplain() takes a Super& (as opposed to const Super&)
  3261. // in order to match the interface MatcherInterface<Super&>.
  3262. bool MatchAndExplain(Super& x,
  3263. MatchResultListener* listener) const override {
  3264. *listener << "which is located @" << static_cast<const void*>(&x);
  3265. return &x == &object_;
  3266. }
  3267. void DescribeTo(::std::ostream* os) const override {
  3268. *os << "references the variable ";
  3269. UniversalPrinter<Super&>::Print(object_, os);
  3270. }
  3271. void DescribeNegationTo(::std::ostream* os) const override {
  3272. *os << "does not reference the variable ";
  3273. UniversalPrinter<Super&>::Print(object_, os);
  3274. }
  3275. private:
  3276. const Super& object_;
  3277. };
  3278. T& object_;
  3279. };
  3280. // Polymorphic helper functions for narrow and wide string matchers.
  3281. inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
  3282. return String::CaseInsensitiveCStringEquals(lhs, rhs);
  3283. }
  3284. inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
  3285. const wchar_t* rhs) {
  3286. return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
  3287. }
  3288. // String comparison for narrow or wide strings that can have embedded NUL
  3289. // characters.
  3290. template <typename StringType>
  3291. bool CaseInsensitiveStringEquals(const StringType& s1,
  3292. const StringType& s2) {
  3293. // Are the heads equal?
  3294. if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
  3295. return false;
  3296. }
  3297. // Skip the equal heads.
  3298. const typename StringType::value_type nul = 0;
  3299. const size_t i1 = s1.find(nul), i2 = s2.find(nul);
  3300. // Are we at the end of either s1 or s2?
  3301. if (i1 == StringType::npos || i2 == StringType::npos) {
  3302. return i1 == i2;
  3303. }
  3304. // Are the tails equal?
  3305. return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
  3306. }
  3307. // String matchers.
  3308. // Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
  3309. template <typename StringType>
  3310. class StrEqualityMatcher {
  3311. public:
  3312. StrEqualityMatcher(StringType str, bool expect_eq, bool case_sensitive)
  3313. : string_(std::move(str)),
  3314. expect_eq_(expect_eq),
  3315. case_sensitive_(case_sensitive) {}
  3316. #if GTEST_INTERNAL_HAS_STRING_VIEW
  3317. bool MatchAndExplain(const internal::StringView& s,
  3318. MatchResultListener* listener) const {
  3319. // This should fail to compile if StringView is used with wide
  3320. // strings.
  3321. const StringType& str = std::string(s);
  3322. return MatchAndExplain(str, listener);
  3323. }
  3324. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  3325. // Accepts pointer types, particularly:
  3326. // const char*
  3327. // char*
  3328. // const wchar_t*
  3329. // wchar_t*
  3330. template <typename CharType>
  3331. bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
  3332. if (s == nullptr) {
  3333. return !expect_eq_;
  3334. }
  3335. return MatchAndExplain(StringType(s), listener);
  3336. }
  3337. // Matches anything that can convert to StringType.
  3338. //
  3339. // This is a template, not just a plain function with const StringType&,
  3340. // because StringView has some interfering non-explicit constructors.
  3341. template <typename MatcheeStringType>
  3342. bool MatchAndExplain(const MatcheeStringType& s,
  3343. MatchResultListener* /* listener */) const {
  3344. const StringType s2(s);
  3345. const bool eq = case_sensitive_ ? s2 == string_ :
  3346. CaseInsensitiveStringEquals(s2, string_);
  3347. return expect_eq_ == eq;
  3348. }
  3349. void DescribeTo(::std::ostream* os) const {
  3350. DescribeToHelper(expect_eq_, os);
  3351. }
  3352. void DescribeNegationTo(::std::ostream* os) const {
  3353. DescribeToHelper(!expect_eq_, os);
  3354. }
  3355. private:
  3356. void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
  3357. *os << (expect_eq ? "is " : "isn't ");
  3358. *os << "equal to ";
  3359. if (!case_sensitive_) {
  3360. *os << "(ignoring case) ";
  3361. }
  3362. UniversalPrint(string_, os);
  3363. }
  3364. const StringType string_;
  3365. const bool expect_eq_;
  3366. const bool case_sensitive_;
  3367. };
  3368. // Implements the polymorphic HasSubstr(substring) matcher, which
  3369. // can be used as a Matcher<T> as long as T can be converted to a
  3370. // string.
  3371. template <typename StringType>
  3372. class HasSubstrMatcher {
  3373. public:
  3374. explicit HasSubstrMatcher(const StringType& substring)
  3375. : substring_(substring) {}
  3376. #if GTEST_INTERNAL_HAS_STRING_VIEW
  3377. bool MatchAndExplain(const internal::StringView& s,
  3378. MatchResultListener* listener) const {
  3379. // This should fail to compile if StringView is used with wide
  3380. // strings.
  3381. const StringType& str = std::string(s);
  3382. return MatchAndExplain(str, listener);
  3383. }
  3384. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  3385. // Accepts pointer types, particularly:
  3386. // const char*
  3387. // char*
  3388. // const wchar_t*
  3389. // wchar_t*
  3390. template <typename CharType>
  3391. bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
  3392. return s != nullptr && MatchAndExplain(StringType(s), listener);
  3393. }
  3394. // Matches anything that can convert to StringType.
  3395. //
  3396. // This is a template, not just a plain function with const StringType&,
  3397. // because StringView has some interfering non-explicit constructors.
  3398. template <typename MatcheeStringType>
  3399. bool MatchAndExplain(const MatcheeStringType& s,
  3400. MatchResultListener* /* listener */) const {
  3401. return StringType(s).find(substring_) != StringType::npos;
  3402. }
  3403. // Describes what this matcher matches.
  3404. void DescribeTo(::std::ostream* os) const {
  3405. *os << "has substring ";
  3406. UniversalPrint(substring_, os);
  3407. }
  3408. void DescribeNegationTo(::std::ostream* os) const {
  3409. *os << "has no substring ";
  3410. UniversalPrint(substring_, os);
  3411. }
  3412. private:
  3413. const StringType substring_;
  3414. };
  3415. // Implements the polymorphic StartsWith(substring) matcher, which
  3416. // can be used as a Matcher<T> as long as T can be converted to a
  3417. // string.
  3418. template <typename StringType>
  3419. class StartsWithMatcher {
  3420. public:
  3421. explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
  3422. }
  3423. #if GTEST_INTERNAL_HAS_STRING_VIEW
  3424. bool MatchAndExplain(const internal::StringView& s,
  3425. MatchResultListener* listener) const {
  3426. // This should fail to compile if StringView is used with wide
  3427. // strings.
  3428. const StringType& str = std::string(s);
  3429. return MatchAndExplain(str, listener);
  3430. }
  3431. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  3432. // Accepts pointer types, particularly:
  3433. // const char*
  3434. // char*
  3435. // const wchar_t*
  3436. // wchar_t*
  3437. template <typename CharType>
  3438. bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
  3439. return s != nullptr && MatchAndExplain(StringType(s), listener);
  3440. }
  3441. // Matches anything that can convert to StringType.
  3442. //
  3443. // This is a template, not just a plain function with const StringType&,
  3444. // because StringView has some interfering non-explicit constructors.
  3445. template <typename MatcheeStringType>
  3446. bool MatchAndExplain(const MatcheeStringType& s,
  3447. MatchResultListener* /* listener */) const {
  3448. const StringType& s2(s);
  3449. return s2.length() >= prefix_.length() &&
  3450. s2.substr(0, prefix_.length()) == prefix_;
  3451. }
  3452. void DescribeTo(::std::ostream* os) const {
  3453. *os << "starts with ";
  3454. UniversalPrint(prefix_, os);
  3455. }
  3456. void DescribeNegationTo(::std::ostream* os) const {
  3457. *os << "doesn't start with ";
  3458. UniversalPrint(prefix_, os);
  3459. }
  3460. private:
  3461. const StringType prefix_;
  3462. };
  3463. // Implements the polymorphic EndsWith(substring) matcher, which
  3464. // can be used as a Matcher<T> as long as T can be converted to a
  3465. // string.
  3466. template <typename StringType>
  3467. class EndsWithMatcher {
  3468. public:
  3469. explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
  3470. #if GTEST_INTERNAL_HAS_STRING_VIEW
  3471. bool MatchAndExplain(const internal::StringView& s,
  3472. MatchResultListener* listener) const {
  3473. // This should fail to compile if StringView is used with wide
  3474. // strings.
  3475. const StringType& str = std::string(s);
  3476. return MatchAndExplain(str, listener);
  3477. }
  3478. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  3479. // Accepts pointer types, particularly:
  3480. // const char*
  3481. // char*
  3482. // const wchar_t*
  3483. // wchar_t*
  3484. template <typename CharType>
  3485. bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
  3486. return s != nullptr && MatchAndExplain(StringType(s), listener);
  3487. }
  3488. // Matches anything that can convert to StringType.
  3489. //
  3490. // This is a template, not just a plain function with const StringType&,
  3491. // because StringView has some interfering non-explicit constructors.
  3492. template <typename MatcheeStringType>
  3493. bool MatchAndExplain(const MatcheeStringType& s,
  3494. MatchResultListener* /* listener */) const {
  3495. const StringType& s2(s);
  3496. return s2.length() >= suffix_.length() &&
  3497. s2.substr(s2.length() - suffix_.length()) == suffix_;
  3498. }
  3499. void DescribeTo(::std::ostream* os) const {
  3500. *os << "ends with ";
  3501. UniversalPrint(suffix_, os);
  3502. }
  3503. void DescribeNegationTo(::std::ostream* os) const {
  3504. *os << "doesn't end with ";
  3505. UniversalPrint(suffix_, os);
  3506. }
  3507. private:
  3508. const StringType suffix_;
  3509. };
  3510. // Implements a matcher that compares the two fields of a 2-tuple
  3511. // using one of the ==, <=, <, etc, operators. The two fields being
  3512. // compared don't have to have the same type.
  3513. //
  3514. // The matcher defined here is polymorphic (for example, Eq() can be
  3515. // used to match a std::tuple<int, short>, a std::tuple<const long&, double>,
  3516. // etc). Therefore we use a template type conversion operator in the
  3517. // implementation.
  3518. template <typename D, typename Op>
  3519. class PairMatchBase {
  3520. public:
  3521. template <typename T1, typename T2>
  3522. operator Matcher<::std::tuple<T1, T2>>() const {
  3523. return Matcher<::std::tuple<T1, T2>>(new Impl<const ::std::tuple<T1, T2>&>);
  3524. }
  3525. template <typename T1, typename T2>
  3526. operator Matcher<const ::std::tuple<T1, T2>&>() const {
  3527. return MakeMatcher(new Impl<const ::std::tuple<T1, T2>&>);
  3528. }
  3529. private:
  3530. static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
  3531. return os << D::Desc();
  3532. }
  3533. template <typename Tuple>
  3534. class Impl : public MatcherInterface<Tuple> {
  3535. public:
  3536. bool MatchAndExplain(Tuple args,
  3537. MatchResultListener* /* listener */) const override {
  3538. return Op()(::std::get<0>(args), ::std::get<1>(args));
  3539. }
  3540. void DescribeTo(::std::ostream* os) const override {
  3541. *os << "are " << GetDesc;
  3542. }
  3543. void DescribeNegationTo(::std::ostream* os) const override {
  3544. *os << "aren't " << GetDesc;
  3545. }
  3546. };
  3547. };
  3548. class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
  3549. public:
  3550. static const char* Desc() { return "an equal pair"; }
  3551. };
  3552. class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
  3553. public:
  3554. static const char* Desc() { return "an unequal pair"; }
  3555. };
  3556. class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
  3557. public:
  3558. static const char* Desc() { return "a pair where the first < the second"; }
  3559. };
  3560. class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
  3561. public:
  3562. static const char* Desc() { return "a pair where the first > the second"; }
  3563. };
  3564. class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
  3565. public:
  3566. static const char* Desc() { return "a pair where the first <= the second"; }
  3567. };
  3568. class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
  3569. public:
  3570. static const char* Desc() { return "a pair where the first >= the second"; }
  3571. };
  3572. // Implements the Not(...) matcher for a particular argument type T.
  3573. // We do not nest it inside the NotMatcher class template, as that
  3574. // will prevent different instantiations of NotMatcher from sharing
  3575. // the same NotMatcherImpl<T> class.
  3576. template <typename T>
  3577. class NotMatcherImpl : public MatcherInterface<const T&> {
  3578. public:
  3579. explicit NotMatcherImpl(const Matcher<T>& matcher)
  3580. : matcher_(matcher) {}
  3581. bool MatchAndExplain(const T& x,
  3582. MatchResultListener* listener) const override {
  3583. return !matcher_.MatchAndExplain(x, listener);
  3584. }
  3585. void DescribeTo(::std::ostream* os) const override {
  3586. matcher_.DescribeNegationTo(os);
  3587. }
  3588. void DescribeNegationTo(::std::ostream* os) const override {
  3589. matcher_.DescribeTo(os);
  3590. }
  3591. private:
  3592. const Matcher<T> matcher_;
  3593. };
  3594. // Implements the Not(m) matcher, which matches a value that doesn't
  3595. // match matcher m.
  3596. template <typename InnerMatcher>
  3597. class NotMatcher {
  3598. public:
  3599. explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
  3600. // This template type conversion operator allows Not(m) to be used
  3601. // to match any type m can match.
  3602. template <typename T>
  3603. operator Matcher<T>() const {
  3604. return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
  3605. }
  3606. private:
  3607. InnerMatcher matcher_;
  3608. };
  3609. // Implements the AllOf(m1, m2) matcher for a particular argument type
  3610. // T. We do not nest it inside the BothOfMatcher class template, as
  3611. // that will prevent different instantiations of BothOfMatcher from
  3612. // sharing the same BothOfMatcherImpl<T> class.
  3613. template <typename T>
  3614. class AllOfMatcherImpl : public MatcherInterface<const T&> {
  3615. public:
  3616. explicit AllOfMatcherImpl(std::vector<Matcher<T> > matchers)
  3617. : matchers_(std::move(matchers)) {}
  3618. void DescribeTo(::std::ostream* os) const override {
  3619. *os << "(";
  3620. for (size_t i = 0; i < matchers_.size(); ++i) {
  3621. if (i != 0) *os << ") and (";
  3622. matchers_[i].DescribeTo(os);
  3623. }
  3624. *os << ")";
  3625. }
  3626. void DescribeNegationTo(::std::ostream* os) const override {
  3627. *os << "(";
  3628. for (size_t i = 0; i < matchers_.size(); ++i) {
  3629. if (i != 0) *os << ") or (";
  3630. matchers_[i].DescribeNegationTo(os);
  3631. }
  3632. *os << ")";
  3633. }
  3634. bool MatchAndExplain(const T& x,
  3635. MatchResultListener* listener) const override {
  3636. // If either matcher1_ or matcher2_ doesn't match x, we only need
  3637. // to explain why one of them fails.
  3638. std::string all_match_result;
  3639. for (size_t i = 0; i < matchers_.size(); ++i) {
  3640. StringMatchResultListener slistener;
  3641. if (matchers_[i].MatchAndExplain(x, &slistener)) {
  3642. if (all_match_result.empty()) {
  3643. all_match_result = slistener.str();
  3644. } else {
  3645. std::string result = slistener.str();
  3646. if (!result.empty()) {
  3647. all_match_result += ", and ";
  3648. all_match_result += result;
  3649. }
  3650. }
  3651. } else {
  3652. *listener << slistener.str();
  3653. return false;
  3654. }
  3655. }
  3656. // Otherwise we need to explain why *both* of them match.
  3657. *listener << all_match_result;
  3658. return true;
  3659. }
  3660. private:
  3661. const std::vector<Matcher<T> > matchers_;
  3662. };
  3663. // VariadicMatcher is used for the variadic implementation of
  3664. // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
  3665. // CombiningMatcher<T> is used to recursively combine the provided matchers
  3666. // (of type Args...).
  3667. template <template <typename T> class CombiningMatcher, typename... Args>
  3668. class VariadicMatcher {
  3669. public:
  3670. VariadicMatcher(const Args&... matchers) // NOLINT
  3671. : matchers_(matchers...) {
  3672. static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
  3673. }
  3674. VariadicMatcher(const VariadicMatcher&) = default;
  3675. VariadicMatcher& operator=(const VariadicMatcher&) = delete;
  3676. // This template type conversion operator allows an
  3677. // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
  3678. // all of the provided matchers (Matcher1, Matcher2, ...) can match.
  3679. template <typename T>
  3680. operator Matcher<T>() const {
  3681. std::vector<Matcher<T> > values;
  3682. CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());
  3683. return Matcher<T>(new CombiningMatcher<T>(std::move(values)));
  3684. }
  3685. private:
  3686. template <typename T, size_t I>
  3687. void CreateVariadicMatcher(std::vector<Matcher<T> >* values,
  3688. std::integral_constant<size_t, I>) const {
  3689. values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));
  3690. CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());
  3691. }
  3692. template <typename T>
  3693. void CreateVariadicMatcher(
  3694. std::vector<Matcher<T> >*,
  3695. std::integral_constant<size_t, sizeof...(Args)>) const {}
  3696. std::tuple<Args...> matchers_;
  3697. };
  3698. template <typename... Args>
  3699. using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;
  3700. // Implements the AnyOf(m1, m2) matcher for a particular argument type
  3701. // T. We do not nest it inside the AnyOfMatcher class template, as
  3702. // that will prevent different instantiations of AnyOfMatcher from
  3703. // sharing the same EitherOfMatcherImpl<T> class.
  3704. template <typename T>
  3705. class AnyOfMatcherImpl : public MatcherInterface<const T&> {
  3706. public:
  3707. explicit AnyOfMatcherImpl(std::vector<Matcher<T> > matchers)
  3708. : matchers_(std::move(matchers)) {}
  3709. void DescribeTo(::std::ostream* os) const override {
  3710. *os << "(";
  3711. for (size_t i = 0; i < matchers_.size(); ++i) {
  3712. if (i != 0) *os << ") or (";
  3713. matchers_[i].DescribeTo(os);
  3714. }
  3715. *os << ")";
  3716. }
  3717. void DescribeNegationTo(::std::ostream* os) const override {
  3718. *os << "(";
  3719. for (size_t i = 0; i < matchers_.size(); ++i) {
  3720. if (i != 0) *os << ") and (";
  3721. matchers_[i].DescribeNegationTo(os);
  3722. }
  3723. *os << ")";
  3724. }
  3725. bool MatchAndExplain(const T& x,
  3726. MatchResultListener* listener) const override {
  3727. std::string no_match_result;
  3728. // If either matcher1_ or matcher2_ matches x, we just need to
  3729. // explain why *one* of them matches.
  3730. for (size_t i = 0; i < matchers_.size(); ++i) {
  3731. StringMatchResultListener slistener;
  3732. if (matchers_[i].MatchAndExplain(x, &slistener)) {
  3733. *listener << slistener.str();
  3734. return true;
  3735. } else {
  3736. if (no_match_result.empty()) {
  3737. no_match_result = slistener.str();
  3738. } else {
  3739. std::string result = slistener.str();
  3740. if (!result.empty()) {
  3741. no_match_result += ", and ";
  3742. no_match_result += result;
  3743. }
  3744. }
  3745. }
  3746. }
  3747. // Otherwise we need to explain why *both* of them fail.
  3748. *listener << no_match_result;
  3749. return false;
  3750. }
  3751. private:
  3752. const std::vector<Matcher<T> > matchers_;
  3753. };
  3754. // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
  3755. template <typename... Args>
  3756. using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;
  3757. // Wrapper for implementation of Any/AllOfArray().
  3758. template <template <class> class MatcherImpl, typename T>
  3759. class SomeOfArrayMatcher {
  3760. public:
  3761. // Constructs the matcher from a sequence of element values or
  3762. // element matchers.
  3763. template <typename Iter>
  3764. SomeOfArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
  3765. template <typename U>
  3766. operator Matcher<U>() const { // NOLINT
  3767. using RawU = typename std::decay<U>::type;
  3768. std::vector<Matcher<RawU>> matchers;
  3769. for (const auto& matcher : matchers_) {
  3770. matchers.push_back(MatcherCast<RawU>(matcher));
  3771. }
  3772. return Matcher<U>(new MatcherImpl<RawU>(std::move(matchers)));
  3773. }
  3774. private:
  3775. const ::std::vector<T> matchers_;
  3776. };
  3777. template <typename T>
  3778. using AllOfArrayMatcher = SomeOfArrayMatcher<AllOfMatcherImpl, T>;
  3779. template <typename T>
  3780. using AnyOfArrayMatcher = SomeOfArrayMatcher<AnyOfMatcherImpl, T>;
  3781. // Used for implementing Truly(pred), which turns a predicate into a
  3782. // matcher.
  3783. template <typename Predicate>
  3784. class TrulyMatcher {
  3785. public:
  3786. explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
  3787. // This method template allows Truly(pred) to be used as a matcher
  3788. // for type T where T is the argument type of predicate 'pred'. The
  3789. // argument is passed by reference as the predicate may be
  3790. // interested in the address of the argument.
  3791. template <typename T>
  3792. bool MatchAndExplain(T& x, // NOLINT
  3793. MatchResultListener* listener) const {
  3794. // Without the if-statement, MSVC sometimes warns about converting
  3795. // a value to bool (warning 4800).
  3796. //
  3797. // We cannot write 'return !!predicate_(x);' as that doesn't work
  3798. // when predicate_(x) returns a class convertible to bool but
  3799. // having no operator!().
  3800. if (predicate_(x))
  3801. return true;
  3802. *listener << "didn't satisfy the given predicate";
  3803. return false;
  3804. }
  3805. void DescribeTo(::std::ostream* os) const {
  3806. *os << "satisfies the given predicate";
  3807. }
  3808. void DescribeNegationTo(::std::ostream* os) const {
  3809. *os << "doesn't satisfy the given predicate";
  3810. }
  3811. private:
  3812. Predicate predicate_;
  3813. };
  3814. // Used for implementing Matches(matcher), which turns a matcher into
  3815. // a predicate.
  3816. template <typename M>
  3817. class MatcherAsPredicate {
  3818. public:
  3819. explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
  3820. // This template operator() allows Matches(m) to be used as a
  3821. // predicate on type T where m is a matcher on type T.
  3822. //
  3823. // The argument x is passed by reference instead of by value, as
  3824. // some matcher may be interested in its address (e.g. as in
  3825. // Matches(Ref(n))(x)).
  3826. template <typename T>
  3827. bool operator()(const T& x) const {
  3828. // We let matcher_ commit to a particular type here instead of
  3829. // when the MatcherAsPredicate object was constructed. This
  3830. // allows us to write Matches(m) where m is a polymorphic matcher
  3831. // (e.g. Eq(5)).
  3832. //
  3833. // If we write Matcher<T>(matcher_).Matches(x) here, it won't
  3834. // compile when matcher_ has type Matcher<const T&>; if we write
  3835. // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
  3836. // when matcher_ has type Matcher<T>; if we just write
  3837. // matcher_.Matches(x), it won't compile when matcher_ is
  3838. // polymorphic, e.g. Eq(5).
  3839. //
  3840. // MatcherCast<const T&>() is necessary for making the code work
  3841. // in all of the above situations.
  3842. return MatcherCast<const T&>(matcher_).Matches(x);
  3843. }
  3844. private:
  3845. M matcher_;
  3846. };
  3847. // For implementing ASSERT_THAT() and EXPECT_THAT(). The template
  3848. // argument M must be a type that can be converted to a matcher.
  3849. template <typename M>
  3850. class PredicateFormatterFromMatcher {
  3851. public:
  3852. explicit PredicateFormatterFromMatcher(M m) : matcher_(std::move(m)) {}
  3853. // This template () operator allows a PredicateFormatterFromMatcher
  3854. // object to act as a predicate-formatter suitable for using with
  3855. // Google Test's EXPECT_PRED_FORMAT1() macro.
  3856. template <typename T>
  3857. AssertionResult operator()(const char* value_text, const T& x) const {
  3858. // We convert matcher_ to a Matcher<const T&> *now* instead of
  3859. // when the PredicateFormatterFromMatcher object was constructed,
  3860. // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
  3861. // know which type to instantiate it to until we actually see the
  3862. // type of x here.
  3863. //
  3864. // We write SafeMatcherCast<const T&>(matcher_) instead of
  3865. // Matcher<const T&>(matcher_), as the latter won't compile when
  3866. // matcher_ has type Matcher<T> (e.g. An<int>()).
  3867. // We don't write MatcherCast<const T&> either, as that allows
  3868. // potentially unsafe downcasting of the matcher argument.
  3869. const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
  3870. // The expected path here is that the matcher should match (i.e. that most
  3871. // tests pass) so optimize for this case.
  3872. if (matcher.Matches(x)) {
  3873. return AssertionSuccess();
  3874. }
  3875. ::std::stringstream ss;
  3876. ss << "Value of: " << value_text << "\n"
  3877. << "Expected: ";
  3878. matcher.DescribeTo(&ss);
  3879. // Rerun the matcher to "PrintAndExplain" the failure.
  3880. StringMatchResultListener listener;
  3881. if (MatchPrintAndExplain(x, matcher, &listener)) {
  3882. ss << "\n The matcher failed on the initial attempt; but passed when "
  3883. "rerun to generate the explanation.";
  3884. }
  3885. ss << "\n Actual: " << listener.str();
  3886. return AssertionFailure() << ss.str();
  3887. }
  3888. private:
  3889. const M matcher_;
  3890. };
  3891. // A helper function for converting a matcher to a predicate-formatter
  3892. // without the user needing to explicitly write the type. This is
  3893. // used for implementing ASSERT_THAT() and EXPECT_THAT().
  3894. // Implementation detail: 'matcher' is received by-value to force decaying.
  3895. template <typename M>
  3896. inline PredicateFormatterFromMatcher<M>
  3897. MakePredicateFormatterFromMatcher(M matcher) {
  3898. return PredicateFormatterFromMatcher<M>(std::move(matcher));
  3899. }
  3900. // Implements the polymorphic IsNan() matcher, which matches any floating type
  3901. // value that is Nan.
  3902. class IsNanMatcher {
  3903. public:
  3904. template <typename FloatType>
  3905. bool MatchAndExplain(const FloatType& f,
  3906. MatchResultListener* /* listener */) const {
  3907. return (::std::isnan)(f);
  3908. }
  3909. void DescribeTo(::std::ostream* os) const { *os << "is NaN"; }
  3910. void DescribeNegationTo(::std::ostream* os) const {
  3911. *os << "isn't NaN";
  3912. }
  3913. };
  3914. // Implements the polymorphic floating point equality matcher, which matches
  3915. // two float values using ULP-based approximation or, optionally, a
  3916. // user-specified epsilon. The template is meant to be instantiated with
  3917. // FloatType being either float or double.
  3918. template <typename FloatType>
  3919. class FloatingEqMatcher {
  3920. public:
  3921. // Constructor for FloatingEqMatcher.
  3922. // The matcher's input will be compared with expected. The matcher treats two
  3923. // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
  3924. // equality comparisons between NANs will always return false. We specify a
  3925. // negative max_abs_error_ term to indicate that ULP-based approximation will
  3926. // be used for comparison.
  3927. FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
  3928. expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
  3929. }
  3930. // Constructor that supports a user-specified max_abs_error that will be used
  3931. // for comparison instead of ULP-based approximation. The max absolute
  3932. // should be non-negative.
  3933. FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
  3934. FloatType max_abs_error)
  3935. : expected_(expected),
  3936. nan_eq_nan_(nan_eq_nan),
  3937. max_abs_error_(max_abs_error) {
  3938. GTEST_CHECK_(max_abs_error >= 0)
  3939. << ", where max_abs_error is" << max_abs_error;
  3940. }
  3941. // Implements floating point equality matcher as a Matcher<T>.
  3942. template <typename T>
  3943. class Impl : public MatcherInterface<T> {
  3944. public:
  3945. Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
  3946. : expected_(expected),
  3947. nan_eq_nan_(nan_eq_nan),
  3948. max_abs_error_(max_abs_error) {}
  3949. bool MatchAndExplain(T value,
  3950. MatchResultListener* listener) const override {
  3951. const FloatingPoint<FloatType> actual(value), expected(expected_);
  3952. // Compares NaNs first, if nan_eq_nan_ is true.
  3953. if (actual.is_nan() || expected.is_nan()) {
  3954. if (actual.is_nan() && expected.is_nan()) {
  3955. return nan_eq_nan_;
  3956. }
  3957. // One is nan; the other is not nan.
  3958. return false;
  3959. }
  3960. if (HasMaxAbsError()) {
  3961. // We perform an equality check so that inf will match inf, regardless
  3962. // of error bounds. If the result of value - expected_ would result in
  3963. // overflow or if either value is inf, the default result is infinity,
  3964. // which should only match if max_abs_error_ is also infinity.
  3965. if (value == expected_) {
  3966. return true;
  3967. }
  3968. const FloatType diff = value - expected_;
  3969. if (::std::fabs(diff) <= max_abs_error_) {
  3970. return true;
  3971. }
  3972. if (listener->IsInterested()) {
  3973. *listener << "which is " << diff << " from " << expected_;
  3974. }
  3975. return false;
  3976. } else {
  3977. return actual.AlmostEquals(expected);
  3978. }
  3979. }
  3980. void DescribeTo(::std::ostream* os) const override {
  3981. // os->precision() returns the previously set precision, which we
  3982. // store to restore the ostream to its original configuration
  3983. // after outputting.
  3984. const ::std::streamsize old_precision = os->precision(
  3985. ::std::numeric_limits<FloatType>::digits10 + 2);
  3986. if (FloatingPoint<FloatType>(expected_).is_nan()) {
  3987. if (nan_eq_nan_) {
  3988. *os << "is NaN";
  3989. } else {
  3990. *os << "never matches";
  3991. }
  3992. } else {
  3993. *os << "is approximately " << expected_;
  3994. if (HasMaxAbsError()) {
  3995. *os << " (absolute error <= " << max_abs_error_ << ")";
  3996. }
  3997. }
  3998. os->precision(old_precision);
  3999. }
  4000. void DescribeNegationTo(::std::ostream* os) const override {
  4001. // As before, get original precision.
  4002. const ::std::streamsize old_precision = os->precision(
  4003. ::std::numeric_limits<FloatType>::digits10 + 2);
  4004. if (FloatingPoint<FloatType>(expected_).is_nan()) {
  4005. if (nan_eq_nan_) {
  4006. *os << "isn't NaN";
  4007. } else {
  4008. *os << "is anything";
  4009. }
  4010. } else {
  4011. *os << "isn't approximately " << expected_;
  4012. if (HasMaxAbsError()) {
  4013. *os << " (absolute error > " << max_abs_error_ << ")";
  4014. }
  4015. }
  4016. // Restore original precision.
  4017. os->precision(old_precision);
  4018. }
  4019. private:
  4020. bool HasMaxAbsError() const {
  4021. return max_abs_error_ >= 0;
  4022. }
  4023. const FloatType expected_;
  4024. const bool nan_eq_nan_;
  4025. // max_abs_error will be used for value comparison when >= 0.
  4026. const FloatType max_abs_error_;
  4027. };
  4028. // The following 3 type conversion operators allow FloatEq(expected) and
  4029. // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
  4030. // Matcher<const float&>, or a Matcher<float&>, but nothing else.
  4031. operator Matcher<FloatType>() const {
  4032. return MakeMatcher(
  4033. new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
  4034. }
  4035. operator Matcher<const FloatType&>() const {
  4036. return MakeMatcher(
  4037. new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
  4038. }
  4039. operator Matcher<FloatType&>() const {
  4040. return MakeMatcher(
  4041. new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
  4042. }
  4043. private:
  4044. const FloatType expected_;
  4045. const bool nan_eq_nan_;
  4046. // max_abs_error will be used for value comparison when >= 0.
  4047. const FloatType max_abs_error_;
  4048. };
  4049. // A 2-tuple ("binary") wrapper around FloatingEqMatcher:
  4050. // FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)
  4051. // against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)
  4052. // against y. The former implements "Eq", the latter "Near". At present, there
  4053. // is no version that compares NaNs as equal.
  4054. template <typename FloatType>
  4055. class FloatingEq2Matcher {
  4056. public:
  4057. FloatingEq2Matcher() { Init(-1, false); }
  4058. explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }
  4059. explicit FloatingEq2Matcher(FloatType max_abs_error) {
  4060. Init(max_abs_error, false);
  4061. }
  4062. FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {
  4063. Init(max_abs_error, nan_eq_nan);
  4064. }
  4065. template <typename T1, typename T2>
  4066. operator Matcher<::std::tuple<T1, T2>>() const {
  4067. return MakeMatcher(
  4068. new Impl<::std::tuple<T1, T2>>(max_abs_error_, nan_eq_nan_));
  4069. }
  4070. template <typename T1, typename T2>
  4071. operator Matcher<const ::std::tuple<T1, T2>&>() const {
  4072. return MakeMatcher(
  4073. new Impl<const ::std::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));
  4074. }
  4075. private:
  4076. static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
  4077. return os << "an almost-equal pair";
  4078. }
  4079. template <typename Tuple>
  4080. class Impl : public MatcherInterface<Tuple> {
  4081. public:
  4082. Impl(FloatType max_abs_error, bool nan_eq_nan) :
  4083. max_abs_error_(max_abs_error),
  4084. nan_eq_nan_(nan_eq_nan) {}
  4085. bool MatchAndExplain(Tuple args,
  4086. MatchResultListener* listener) const override {
  4087. if (max_abs_error_ == -1) {
  4088. FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_);
  4089. return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(
  4090. ::std::get<1>(args), listener);
  4091. } else {
  4092. FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_,
  4093. max_abs_error_);
  4094. return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(
  4095. ::std::get<1>(args), listener);
  4096. }
  4097. }
  4098. void DescribeTo(::std::ostream* os) const override {
  4099. *os << "are " << GetDesc;
  4100. }
  4101. void DescribeNegationTo(::std::ostream* os) const override {
  4102. *os << "aren't " << GetDesc;
  4103. }
  4104. private:
  4105. FloatType max_abs_error_;
  4106. const bool nan_eq_nan_;
  4107. };
  4108. void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {
  4109. max_abs_error_ = max_abs_error_val;
  4110. nan_eq_nan_ = nan_eq_nan_val;
  4111. }
  4112. FloatType max_abs_error_;
  4113. bool nan_eq_nan_;
  4114. };
  4115. // Implements the Pointee(m) matcher for matching a pointer whose
  4116. // pointee matches matcher m. The pointer can be either raw or smart.
  4117. template <typename InnerMatcher>
  4118. class PointeeMatcher {
  4119. public:
  4120. explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
  4121. // This type conversion operator template allows Pointee(m) to be
  4122. // used as a matcher for any pointer type whose pointee type is
  4123. // compatible with the inner matcher, where type Pointer can be
  4124. // either a raw pointer or a smart pointer.
  4125. //
  4126. // The reason we do this instead of relying on
  4127. // MakePolymorphicMatcher() is that the latter is not flexible
  4128. // enough for implementing the DescribeTo() method of Pointee().
  4129. template <typename Pointer>
  4130. operator Matcher<Pointer>() const {
  4131. return Matcher<Pointer>(new Impl<const Pointer&>(matcher_));
  4132. }
  4133. private:
  4134. // The monomorphic implementation that works for a particular pointer type.
  4135. template <typename Pointer>
  4136. class Impl : public MatcherInterface<Pointer> {
  4137. public:
  4138. using Pointee =
  4139. typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
  4140. Pointer)>::element_type;
  4141. explicit Impl(const InnerMatcher& matcher)
  4142. : matcher_(MatcherCast<const Pointee&>(matcher)) {}
  4143. void DescribeTo(::std::ostream* os) const override {
  4144. *os << "points to a value that ";
  4145. matcher_.DescribeTo(os);
  4146. }
  4147. void DescribeNegationTo(::std::ostream* os) const override {
  4148. *os << "does not point to a value that ";
  4149. matcher_.DescribeTo(os);
  4150. }
  4151. bool MatchAndExplain(Pointer pointer,
  4152. MatchResultListener* listener) const override {
  4153. if (GetRawPointer(pointer) == nullptr) return false;
  4154. *listener << "which points to ";
  4155. return MatchPrintAndExplain(*pointer, matcher_, listener);
  4156. }
  4157. private:
  4158. const Matcher<const Pointee&> matcher_;
  4159. };
  4160. const InnerMatcher matcher_;
  4161. };
  4162. // Implements the Pointer(m) matcher
  4163. // Implements the Pointer(m) matcher for matching a pointer that matches matcher
  4164. // m. The pointer can be either raw or smart, and will match `m` against the
  4165. // raw pointer.
  4166. template <typename InnerMatcher>
  4167. class PointerMatcher {
  4168. public:
  4169. explicit PointerMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
  4170. // This type conversion operator template allows Pointer(m) to be
  4171. // used as a matcher for any pointer type whose pointer type is
  4172. // compatible with the inner matcher, where type PointerType can be
  4173. // either a raw pointer or a smart pointer.
  4174. //
  4175. // The reason we do this instead of relying on
  4176. // MakePolymorphicMatcher() is that the latter is not flexible
  4177. // enough for implementing the DescribeTo() method of Pointer().
  4178. template <typename PointerType>
  4179. operator Matcher<PointerType>() const { // NOLINT
  4180. return Matcher<PointerType>(new Impl<const PointerType&>(matcher_));
  4181. }
  4182. private:
  4183. // The monomorphic implementation that works for a particular pointer type.
  4184. template <typename PointerType>
  4185. class Impl : public MatcherInterface<PointerType> {
  4186. public:
  4187. using Pointer =
  4188. const typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
  4189. PointerType)>::element_type*;
  4190. explicit Impl(const InnerMatcher& matcher)
  4191. : matcher_(MatcherCast<Pointer>(matcher)) {}
  4192. void DescribeTo(::std::ostream* os) const override {
  4193. *os << "is a pointer that ";
  4194. matcher_.DescribeTo(os);
  4195. }
  4196. void DescribeNegationTo(::std::ostream* os) const override {
  4197. *os << "is not a pointer that ";
  4198. matcher_.DescribeTo(os);
  4199. }
  4200. bool MatchAndExplain(PointerType pointer,
  4201. MatchResultListener* listener) const override {
  4202. *listener << "which is a pointer that ";
  4203. Pointer p = GetRawPointer(pointer);
  4204. return MatchPrintAndExplain(p, matcher_, listener);
  4205. }
  4206. private:
  4207. Matcher<Pointer> matcher_;
  4208. };
  4209. const InnerMatcher matcher_;
  4210. };
  4211. #if GTEST_HAS_RTTI
  4212. // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
  4213. // reference that matches inner_matcher when dynamic_cast<T> is applied.
  4214. // The result of dynamic_cast<To> is forwarded to the inner matcher.
  4215. // If To is a pointer and the cast fails, the inner matcher will receive NULL.
  4216. // If To is a reference and the cast fails, this matcher returns false
  4217. // immediately.
  4218. template <typename To>
  4219. class WhenDynamicCastToMatcherBase {
  4220. public:
  4221. explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
  4222. : matcher_(matcher) {}
  4223. void DescribeTo(::std::ostream* os) const {
  4224. GetCastTypeDescription(os);
  4225. matcher_.DescribeTo(os);
  4226. }
  4227. void DescribeNegationTo(::std::ostream* os) const {
  4228. GetCastTypeDescription(os);
  4229. matcher_.DescribeNegationTo(os);
  4230. }
  4231. protected:
  4232. const Matcher<To> matcher_;
  4233. static std::string GetToName() {
  4234. return GetTypeName<To>();
  4235. }
  4236. private:
  4237. static void GetCastTypeDescription(::std::ostream* os) {
  4238. *os << "when dynamic_cast to " << GetToName() << ", ";
  4239. }
  4240. };
  4241. // Primary template.
  4242. // To is a pointer. Cast and forward the result.
  4243. template <typename To>
  4244. class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
  4245. public:
  4246. explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
  4247. : WhenDynamicCastToMatcherBase<To>(matcher) {}
  4248. template <typename From>
  4249. bool MatchAndExplain(From from, MatchResultListener* listener) const {
  4250. To to = dynamic_cast<To>(from);
  4251. return MatchPrintAndExplain(to, this->matcher_, listener);
  4252. }
  4253. };
  4254. // Specialize for references.
  4255. // In this case we return false if the dynamic_cast fails.
  4256. template <typename To>
  4257. class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
  4258. public:
  4259. explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
  4260. : WhenDynamicCastToMatcherBase<To&>(matcher) {}
  4261. template <typename From>
  4262. bool MatchAndExplain(From& from, MatchResultListener* listener) const {
  4263. // We don't want an std::bad_cast here, so do the cast with pointers.
  4264. To* to = dynamic_cast<To*>(&from);
  4265. if (to == nullptr) {
  4266. *listener << "which cannot be dynamic_cast to " << this->GetToName();
  4267. return false;
  4268. }
  4269. return MatchPrintAndExplain(*to, this->matcher_, listener);
  4270. }
  4271. };
  4272. #endif // GTEST_HAS_RTTI
  4273. // Implements the Field() matcher for matching a field (i.e. member
  4274. // variable) of an object.
  4275. template <typename Class, typename FieldType>
  4276. class FieldMatcher {
  4277. public:
  4278. FieldMatcher(FieldType Class::*field,
  4279. const Matcher<const FieldType&>& matcher)
  4280. : field_(field), matcher_(matcher), whose_field_("whose given field ") {}
  4281. FieldMatcher(const std::string& field_name, FieldType Class::*field,
  4282. const Matcher<const FieldType&>& matcher)
  4283. : field_(field),
  4284. matcher_(matcher),
  4285. whose_field_("whose field `" + field_name + "` ") {}
  4286. void DescribeTo(::std::ostream* os) const {
  4287. *os << "is an object " << whose_field_;
  4288. matcher_.DescribeTo(os);
  4289. }
  4290. void DescribeNegationTo(::std::ostream* os) const {
  4291. *os << "is an object " << whose_field_;
  4292. matcher_.DescribeNegationTo(os);
  4293. }
  4294. template <typename T>
  4295. bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
  4296. // FIXME: The dispatch on std::is_pointer was introduced as a workaround for
  4297. // a compiler bug, and can now be removed.
  4298. return MatchAndExplainImpl(
  4299. typename std::is_pointer<typename std::remove_const<T>::type>::type(),
  4300. value, listener);
  4301. }
  4302. private:
  4303. bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,
  4304. const Class& obj,
  4305. MatchResultListener* listener) const {
  4306. *listener << whose_field_ << "is ";
  4307. return MatchPrintAndExplain(obj.*field_, matcher_, listener);
  4308. }
  4309. bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,
  4310. MatchResultListener* listener) const {
  4311. if (p == nullptr) return false;
  4312. *listener << "which points to an object ";
  4313. // Since *p has a field, it must be a class/struct/union type and
  4314. // thus cannot be a pointer. Therefore we pass false_type() as
  4315. // the first argument.
  4316. return MatchAndExplainImpl(std::false_type(), *p, listener);
  4317. }
  4318. const FieldType Class::*field_;
  4319. const Matcher<const FieldType&> matcher_;
  4320. // Contains either "whose given field " if the name of the field is unknown
  4321. // or "whose field `name_of_field` " if the name is known.
  4322. const std::string whose_field_;
  4323. };
  4324. // Implements the Property() matcher for matching a property
  4325. // (i.e. return value of a getter method) of an object.
  4326. //
  4327. // Property is a const-qualified member function of Class returning
  4328. // PropertyType.
  4329. template <typename Class, typename PropertyType, typename Property>
  4330. class PropertyMatcher {
  4331. public:
  4332. typedef const PropertyType& RefToConstProperty;
  4333. PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)
  4334. : property_(property),
  4335. matcher_(matcher),
  4336. whose_property_("whose given property ") {}
  4337. PropertyMatcher(const std::string& property_name, Property property,
  4338. const Matcher<RefToConstProperty>& matcher)
  4339. : property_(property),
  4340. matcher_(matcher),
  4341. whose_property_("whose property `" + property_name + "` ") {}
  4342. void DescribeTo(::std::ostream* os) const {
  4343. *os << "is an object " << whose_property_;
  4344. matcher_.DescribeTo(os);
  4345. }
  4346. void DescribeNegationTo(::std::ostream* os) const {
  4347. *os << "is an object " << whose_property_;
  4348. matcher_.DescribeNegationTo(os);
  4349. }
  4350. template <typename T>
  4351. bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
  4352. return MatchAndExplainImpl(
  4353. typename std::is_pointer<typename std::remove_const<T>::type>::type(),
  4354. value, listener);
  4355. }
  4356. private:
  4357. bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,
  4358. const Class& obj,
  4359. MatchResultListener* listener) const {
  4360. *listener << whose_property_ << "is ";
  4361. // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
  4362. // which takes a non-const reference as argument.
  4363. RefToConstProperty result = (obj.*property_)();
  4364. return MatchPrintAndExplain(result, matcher_, listener);
  4365. }
  4366. bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,
  4367. MatchResultListener* listener) const {
  4368. if (p == nullptr) return false;
  4369. *listener << "which points to an object ";
  4370. // Since *p has a property method, it must be a class/struct/union
  4371. // type and thus cannot be a pointer. Therefore we pass
  4372. // false_type() as the first argument.
  4373. return MatchAndExplainImpl(std::false_type(), *p, listener);
  4374. }
  4375. Property property_;
  4376. const Matcher<RefToConstProperty> matcher_;
  4377. // Contains either "whose given property " if the name of the property is
  4378. // unknown or "whose property `name_of_property` " if the name is known.
  4379. const std::string whose_property_;
  4380. };
  4381. // Type traits specifying various features of different functors for ResultOf.
  4382. // The default template specifies features for functor objects.
  4383. template <typename Functor>
  4384. struct CallableTraits {
  4385. typedef Functor StorageType;
  4386. static void CheckIsValid(Functor /* functor */) {}
  4387. template <typename T>
  4388. static auto Invoke(Functor f, const T& arg) -> decltype(f(arg)) {
  4389. return f(arg);
  4390. }
  4391. };
  4392. // Specialization for function pointers.
  4393. template <typename ArgType, typename ResType>
  4394. struct CallableTraits<ResType(*)(ArgType)> {
  4395. typedef ResType ResultType;
  4396. typedef ResType(*StorageType)(ArgType);
  4397. static void CheckIsValid(ResType(*f)(ArgType)) {
  4398. GTEST_CHECK_(f != nullptr)
  4399. << "NULL function pointer is passed into ResultOf().";
  4400. }
  4401. template <typename T>
  4402. static ResType Invoke(ResType(*f)(ArgType), T arg) {
  4403. return (*f)(arg);
  4404. }
  4405. };
  4406. // Implements the ResultOf() matcher for matching a return value of a
  4407. // unary function of an object.
  4408. template <typename Callable, typename InnerMatcher>
  4409. class ResultOfMatcher {
  4410. public:
  4411. ResultOfMatcher(Callable callable, InnerMatcher matcher)
  4412. : callable_(std::move(callable)), matcher_(std::move(matcher)) {
  4413. CallableTraits<Callable>::CheckIsValid(callable_);
  4414. }
  4415. template <typename T>
  4416. operator Matcher<T>() const {
  4417. return Matcher<T>(new Impl<const T&>(callable_, matcher_));
  4418. }
  4419. private:
  4420. typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
  4421. template <typename T>
  4422. class Impl : public MatcherInterface<T> {
  4423. using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>(
  4424. std::declval<CallableStorageType>(), std::declval<T>()));
  4425. public:
  4426. template <typename M>
  4427. Impl(const CallableStorageType& callable, const M& matcher)
  4428. : callable_(callable), matcher_(MatcherCast<ResultType>(matcher)) {}
  4429. void DescribeTo(::std::ostream* os) const override {
  4430. *os << "is mapped by the given callable to a value that ";
  4431. matcher_.DescribeTo(os);
  4432. }
  4433. void DescribeNegationTo(::std::ostream* os) const override {
  4434. *os << "is mapped by the given callable to a value that ";
  4435. matcher_.DescribeNegationTo(os);
  4436. }
  4437. bool MatchAndExplain(T obj, MatchResultListener* listener) const override {
  4438. *listener << "which is mapped by the given callable to ";
  4439. // Cannot pass the return value directly to MatchPrintAndExplain, which
  4440. // takes a non-const reference as argument.
  4441. // Also, specifying template argument explicitly is needed because T could
  4442. // be a non-const reference (e.g. Matcher<Uncopyable&>).
  4443. ResultType result =
  4444. CallableTraits<Callable>::template Invoke<T>(callable_, obj);
  4445. return MatchPrintAndExplain(result, matcher_, listener);
  4446. }
  4447. private:
  4448. // Functors often define operator() as non-const method even though
  4449. // they are actually stateless. But we need to use them even when
  4450. // 'this' is a const pointer. It's the user's responsibility not to
  4451. // use stateful callables with ResultOf(), which doesn't guarantee
  4452. // how many times the callable will be invoked.
  4453. mutable CallableStorageType callable_;
  4454. const Matcher<ResultType> matcher_;
  4455. }; // class Impl
  4456. const CallableStorageType callable_;
  4457. const InnerMatcher matcher_;
  4458. };
  4459. // Implements a matcher that checks the size of an STL-style container.
  4460. template <typename SizeMatcher>
  4461. class SizeIsMatcher {
  4462. public:
  4463. explicit SizeIsMatcher(const SizeMatcher& size_matcher)
  4464. : size_matcher_(size_matcher) {
  4465. }
  4466. template <typename Container>
  4467. operator Matcher<Container>() const {
  4468. return Matcher<Container>(new Impl<const Container&>(size_matcher_));
  4469. }
  4470. template <typename Container>
  4471. class Impl : public MatcherInterface<Container> {
  4472. public:
  4473. using SizeType = decltype(std::declval<Container>().size());
  4474. explicit Impl(const SizeMatcher& size_matcher)
  4475. : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
  4476. void DescribeTo(::std::ostream* os) const override {
  4477. *os << "size ";
  4478. size_matcher_.DescribeTo(os);
  4479. }
  4480. void DescribeNegationTo(::std::ostream* os) const override {
  4481. *os << "size ";
  4482. size_matcher_.DescribeNegationTo(os);
  4483. }
  4484. bool MatchAndExplain(Container container,
  4485. MatchResultListener* listener) const override {
  4486. SizeType size = container.size();
  4487. StringMatchResultListener size_listener;
  4488. const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
  4489. *listener
  4490. << "whose size " << size << (result ? " matches" : " doesn't match");
  4491. PrintIfNotEmpty(size_listener.str(), listener->stream());
  4492. return result;
  4493. }
  4494. private:
  4495. const Matcher<SizeType> size_matcher_;
  4496. };
  4497. private:
  4498. const SizeMatcher size_matcher_;
  4499. };
  4500. // Implements a matcher that checks the begin()..end() distance of an STL-style
  4501. // container.
  4502. template <typename DistanceMatcher>
  4503. class BeginEndDistanceIsMatcher {
  4504. public:
  4505. explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
  4506. : distance_matcher_(distance_matcher) {}
  4507. template <typename Container>
  4508. operator Matcher<Container>() const {
  4509. return Matcher<Container>(new Impl<const Container&>(distance_matcher_));
  4510. }
  4511. template <typename Container>
  4512. class Impl : public MatcherInterface<Container> {
  4513. public:
  4514. typedef internal::StlContainerView<
  4515. GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
  4516. typedef typename std::iterator_traits<
  4517. typename ContainerView::type::const_iterator>::difference_type
  4518. DistanceType;
  4519. explicit Impl(const DistanceMatcher& distance_matcher)
  4520. : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
  4521. void DescribeTo(::std::ostream* os) const override {
  4522. *os << "distance between begin() and end() ";
  4523. distance_matcher_.DescribeTo(os);
  4524. }
  4525. void DescribeNegationTo(::std::ostream* os) const override {
  4526. *os << "distance between begin() and end() ";
  4527. distance_matcher_.DescribeNegationTo(os);
  4528. }
  4529. bool MatchAndExplain(Container container,
  4530. MatchResultListener* listener) const override {
  4531. using std::begin;
  4532. using std::end;
  4533. DistanceType distance = std::distance(begin(container), end(container));
  4534. StringMatchResultListener distance_listener;
  4535. const bool result =
  4536. distance_matcher_.MatchAndExplain(distance, &distance_listener);
  4537. *listener << "whose distance between begin() and end() " << distance
  4538. << (result ? " matches" : " doesn't match");
  4539. PrintIfNotEmpty(distance_listener.str(), listener->stream());
  4540. return result;
  4541. }
  4542. private:
  4543. const Matcher<DistanceType> distance_matcher_;
  4544. };
  4545. private:
  4546. const DistanceMatcher distance_matcher_;
  4547. };
  4548. // Implements an equality matcher for any STL-style container whose elements
  4549. // support ==. This matcher is like Eq(), but its failure explanations provide
  4550. // more detailed information that is useful when the container is used as a set.
  4551. // The failure message reports elements that are in one of the operands but not
  4552. // the other. The failure messages do not report duplicate or out-of-order
  4553. // elements in the containers (which don't properly matter to sets, but can
  4554. // occur if the containers are vectors or lists, for example).
  4555. //
  4556. // Uses the container's const_iterator, value_type, operator ==,
  4557. // begin(), and end().
  4558. template <typename Container>
  4559. class ContainerEqMatcher {
  4560. public:
  4561. typedef internal::StlContainerView<Container> View;
  4562. typedef typename View::type StlContainer;
  4563. typedef typename View::const_reference StlContainerReference;
  4564. static_assert(!std::is_const<Container>::value,
  4565. "Container type must not be const");
  4566. static_assert(!std::is_reference<Container>::value,
  4567. "Container type must not be a reference");
  4568. // We make a copy of expected in case the elements in it are modified
  4569. // after this matcher is created.
  4570. explicit ContainerEqMatcher(const Container& expected)
  4571. : expected_(View::Copy(expected)) {}
  4572. void DescribeTo(::std::ostream* os) const {
  4573. *os << "equals ";
  4574. UniversalPrint(expected_, os);
  4575. }
  4576. void DescribeNegationTo(::std::ostream* os) const {
  4577. *os << "does not equal ";
  4578. UniversalPrint(expected_, os);
  4579. }
  4580. template <typename LhsContainer>
  4581. bool MatchAndExplain(const LhsContainer& lhs,
  4582. MatchResultListener* listener) const {
  4583. typedef internal::StlContainerView<
  4584. typename std::remove_const<LhsContainer>::type>
  4585. LhsView;
  4586. typedef typename LhsView::type LhsStlContainer;
  4587. StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
  4588. if (lhs_stl_container == expected_)
  4589. return true;
  4590. ::std::ostream* const os = listener->stream();
  4591. if (os != nullptr) {
  4592. // Something is different. Check for extra values first.
  4593. bool printed_header = false;
  4594. for (typename LhsStlContainer::const_iterator it =
  4595. lhs_stl_container.begin();
  4596. it != lhs_stl_container.end(); ++it) {
  4597. if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
  4598. expected_.end()) {
  4599. if (printed_header) {
  4600. *os << ", ";
  4601. } else {
  4602. *os << "which has these unexpected elements: ";
  4603. printed_header = true;
  4604. }
  4605. UniversalPrint(*it, os);
  4606. }
  4607. }
  4608. // Now check for missing values.
  4609. bool printed_header2 = false;
  4610. for (typename StlContainer::const_iterator it = expected_.begin();
  4611. it != expected_.end(); ++it) {
  4612. if (internal::ArrayAwareFind(
  4613. lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
  4614. lhs_stl_container.end()) {
  4615. if (printed_header2) {
  4616. *os << ", ";
  4617. } else {
  4618. *os << (printed_header ? ",\nand" : "which")
  4619. << " doesn't have these expected elements: ";
  4620. printed_header2 = true;
  4621. }
  4622. UniversalPrint(*it, os);
  4623. }
  4624. }
  4625. }
  4626. return false;
  4627. }
  4628. private:
  4629. const StlContainer expected_;
  4630. };
  4631. // A comparator functor that uses the < operator to compare two values.
  4632. struct LessComparator {
  4633. template <typename T, typename U>
  4634. bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
  4635. };
  4636. // Implements WhenSortedBy(comparator, container_matcher).
  4637. template <typename Comparator, typename ContainerMatcher>
  4638. class WhenSortedByMatcher {
  4639. public:
  4640. WhenSortedByMatcher(const Comparator& comparator,
  4641. const ContainerMatcher& matcher)
  4642. : comparator_(comparator), matcher_(matcher) {}
  4643. template <typename LhsContainer>
  4644. operator Matcher<LhsContainer>() const {
  4645. return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
  4646. }
  4647. template <typename LhsContainer>
  4648. class Impl : public MatcherInterface<LhsContainer> {
  4649. public:
  4650. typedef internal::StlContainerView<
  4651. GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
  4652. typedef typename LhsView::type LhsStlContainer;
  4653. typedef typename LhsView::const_reference LhsStlContainerReference;
  4654. // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
  4655. // so that we can match associative containers.
  4656. typedef typename RemoveConstFromKey<
  4657. typename LhsStlContainer::value_type>::type LhsValue;
  4658. Impl(const Comparator& comparator, const ContainerMatcher& matcher)
  4659. : comparator_(comparator), matcher_(matcher) {}
  4660. void DescribeTo(::std::ostream* os) const override {
  4661. *os << "(when sorted) ";
  4662. matcher_.DescribeTo(os);
  4663. }
  4664. void DescribeNegationTo(::std::ostream* os) const override {
  4665. *os << "(when sorted) ";
  4666. matcher_.DescribeNegationTo(os);
  4667. }
  4668. bool MatchAndExplain(LhsContainer lhs,
  4669. MatchResultListener* listener) const override {
  4670. LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
  4671. ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
  4672. lhs_stl_container.end());
  4673. ::std::sort(
  4674. sorted_container.begin(), sorted_container.end(), comparator_);
  4675. if (!listener->IsInterested()) {
  4676. // If the listener is not interested, we do not need to
  4677. // construct the inner explanation.
  4678. return matcher_.Matches(sorted_container);
  4679. }
  4680. *listener << "which is ";
  4681. UniversalPrint(sorted_container, listener->stream());
  4682. *listener << " when sorted";
  4683. StringMatchResultListener inner_listener;
  4684. const bool match = matcher_.MatchAndExplain(sorted_container,
  4685. &inner_listener);
  4686. PrintIfNotEmpty(inner_listener.str(), listener->stream());
  4687. return match;
  4688. }
  4689. private:
  4690. const Comparator comparator_;
  4691. const Matcher<const ::std::vector<LhsValue>&> matcher_;
  4692. GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
  4693. };
  4694. private:
  4695. const Comparator comparator_;
  4696. const ContainerMatcher matcher_;
  4697. };
  4698. // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
  4699. // must be able to be safely cast to Matcher<std::tuple<const T1&, const
  4700. // T2&> >, where T1 and T2 are the types of elements in the LHS
  4701. // container and the RHS container respectively.
  4702. template <typename TupleMatcher, typename RhsContainer>
  4703. class PointwiseMatcher {
  4704. GTEST_COMPILE_ASSERT_(
  4705. !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
  4706. use_UnorderedPointwise_with_hash_tables);
  4707. public:
  4708. typedef internal::StlContainerView<RhsContainer> RhsView;
  4709. typedef typename RhsView::type RhsStlContainer;
  4710. typedef typename RhsStlContainer::value_type RhsValue;
  4711. static_assert(!std::is_const<RhsContainer>::value,
  4712. "RhsContainer type must not be const");
  4713. static_assert(!std::is_reference<RhsContainer>::value,
  4714. "RhsContainer type must not be a reference");
  4715. // Like ContainerEq, we make a copy of rhs in case the elements in
  4716. // it are modified after this matcher is created.
  4717. PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
  4718. : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {}
  4719. template <typename LhsContainer>
  4720. operator Matcher<LhsContainer>() const {
  4721. GTEST_COMPILE_ASSERT_(
  4722. !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
  4723. use_UnorderedPointwise_with_hash_tables);
  4724. return Matcher<LhsContainer>(
  4725. new Impl<const LhsContainer&>(tuple_matcher_, rhs_));
  4726. }
  4727. template <typename LhsContainer>
  4728. class Impl : public MatcherInterface<LhsContainer> {
  4729. public:
  4730. typedef internal::StlContainerView<
  4731. GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
  4732. typedef typename LhsView::type LhsStlContainer;
  4733. typedef typename LhsView::const_reference LhsStlContainerReference;
  4734. typedef typename LhsStlContainer::value_type LhsValue;
  4735. // We pass the LHS value and the RHS value to the inner matcher by
  4736. // reference, as they may be expensive to copy. We must use tuple
  4737. // instead of pair here, as a pair cannot hold references (C++ 98,
  4738. // 20.2.2 [lib.pairs]).
  4739. typedef ::std::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
  4740. Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
  4741. // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
  4742. : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
  4743. rhs_(rhs) {}
  4744. void DescribeTo(::std::ostream* os) const override {
  4745. *os << "contains " << rhs_.size()
  4746. << " values, where each value and its corresponding value in ";
  4747. UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
  4748. *os << " ";
  4749. mono_tuple_matcher_.DescribeTo(os);
  4750. }
  4751. void DescribeNegationTo(::std::ostream* os) const override {
  4752. *os << "doesn't contain exactly " << rhs_.size()
  4753. << " values, or contains a value x at some index i"
  4754. << " where x and the i-th value of ";
  4755. UniversalPrint(rhs_, os);
  4756. *os << " ";
  4757. mono_tuple_matcher_.DescribeNegationTo(os);
  4758. }
  4759. bool MatchAndExplain(LhsContainer lhs,
  4760. MatchResultListener* listener) const override {
  4761. LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
  4762. const size_t actual_size = lhs_stl_container.size();
  4763. if (actual_size != rhs_.size()) {
  4764. *listener << "which contains " << actual_size << " values";
  4765. return false;
  4766. }
  4767. typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
  4768. typename RhsStlContainer::const_iterator right = rhs_.begin();
  4769. for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
  4770. if (listener->IsInterested()) {
  4771. StringMatchResultListener inner_listener;
  4772. // Create InnerMatcherArg as a temporarily object to avoid it outlives
  4773. // *left and *right. Dereference or the conversion to `const T&` may
  4774. // return temp objects, e.g for vector<bool>.
  4775. if (!mono_tuple_matcher_.MatchAndExplain(
  4776. InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
  4777. ImplicitCast_<const RhsValue&>(*right)),
  4778. &inner_listener)) {
  4779. *listener << "where the value pair (";
  4780. UniversalPrint(*left, listener->stream());
  4781. *listener << ", ";
  4782. UniversalPrint(*right, listener->stream());
  4783. *listener << ") at index #" << i << " don't match";
  4784. PrintIfNotEmpty(inner_listener.str(), listener->stream());
  4785. return false;
  4786. }
  4787. } else {
  4788. if (!mono_tuple_matcher_.Matches(
  4789. InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
  4790. ImplicitCast_<const RhsValue&>(*right))))
  4791. return false;
  4792. }
  4793. }
  4794. return true;
  4795. }
  4796. private:
  4797. const Matcher<InnerMatcherArg> mono_tuple_matcher_;
  4798. const RhsStlContainer rhs_;
  4799. };
  4800. private:
  4801. const TupleMatcher tuple_matcher_;
  4802. const RhsStlContainer rhs_;
  4803. };
  4804. // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
  4805. template <typename Container>
  4806. class QuantifierMatcherImpl : public MatcherInterface<Container> {
  4807. public:
  4808. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  4809. typedef StlContainerView<RawContainer> View;
  4810. typedef typename View::type StlContainer;
  4811. typedef typename View::const_reference StlContainerReference;
  4812. typedef typename StlContainer::value_type Element;
  4813. template <typename InnerMatcher>
  4814. explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
  4815. : inner_matcher_(
  4816. testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
  4817. // Checks whether:
  4818. // * All elements in the container match, if all_elements_should_match.
  4819. // * Any element in the container matches, if !all_elements_should_match.
  4820. bool MatchAndExplainImpl(bool all_elements_should_match,
  4821. Container container,
  4822. MatchResultListener* listener) const {
  4823. StlContainerReference stl_container = View::ConstReference(container);
  4824. size_t i = 0;
  4825. for (typename StlContainer::const_iterator it = stl_container.begin();
  4826. it != stl_container.end(); ++it, ++i) {
  4827. StringMatchResultListener inner_listener;
  4828. const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
  4829. if (matches != all_elements_should_match) {
  4830. *listener << "whose element #" << i
  4831. << (matches ? " matches" : " doesn't match");
  4832. PrintIfNotEmpty(inner_listener.str(), listener->stream());
  4833. return !all_elements_should_match;
  4834. }
  4835. }
  4836. return all_elements_should_match;
  4837. }
  4838. protected:
  4839. const Matcher<const Element&> inner_matcher_;
  4840. };
  4841. // Implements Contains(element_matcher) for the given argument type Container.
  4842. // Symmetric to EachMatcherImpl.
  4843. template <typename Container>
  4844. class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
  4845. public:
  4846. template <typename InnerMatcher>
  4847. explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
  4848. : QuantifierMatcherImpl<Container>(inner_matcher) {}
  4849. // Describes what this matcher does.
  4850. void DescribeTo(::std::ostream* os) const override {
  4851. *os << "contains at least one element that ";
  4852. this->inner_matcher_.DescribeTo(os);
  4853. }
  4854. void DescribeNegationTo(::std::ostream* os) const override {
  4855. *os << "doesn't contain any element that ";
  4856. this->inner_matcher_.DescribeTo(os);
  4857. }
  4858. bool MatchAndExplain(Container container,
  4859. MatchResultListener* listener) const override {
  4860. return this->MatchAndExplainImpl(false, container, listener);
  4861. }
  4862. };
  4863. // Implements Each(element_matcher) for the given argument type Container.
  4864. // Symmetric to ContainsMatcherImpl.
  4865. template <typename Container>
  4866. class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
  4867. public:
  4868. template <typename InnerMatcher>
  4869. explicit EachMatcherImpl(InnerMatcher inner_matcher)
  4870. : QuantifierMatcherImpl<Container>(inner_matcher) {}
  4871. // Describes what this matcher does.
  4872. void DescribeTo(::std::ostream* os) const override {
  4873. *os << "only contains elements that ";
  4874. this->inner_matcher_.DescribeTo(os);
  4875. }
  4876. void DescribeNegationTo(::std::ostream* os) const override {
  4877. *os << "contains some element that ";
  4878. this->inner_matcher_.DescribeNegationTo(os);
  4879. }
  4880. bool MatchAndExplain(Container container,
  4881. MatchResultListener* listener) const override {
  4882. return this->MatchAndExplainImpl(true, container, listener);
  4883. }
  4884. };
  4885. // Implements polymorphic Contains(element_matcher).
  4886. template <typename M>
  4887. class ContainsMatcher {
  4888. public:
  4889. explicit ContainsMatcher(M m) : inner_matcher_(m) {}
  4890. template <typename Container>
  4891. operator Matcher<Container>() const {
  4892. return Matcher<Container>(
  4893. new ContainsMatcherImpl<const Container&>(inner_matcher_));
  4894. }
  4895. private:
  4896. const M inner_matcher_;
  4897. };
  4898. // Implements polymorphic Each(element_matcher).
  4899. template <typename M>
  4900. class EachMatcher {
  4901. public:
  4902. explicit EachMatcher(M m) : inner_matcher_(m) {}
  4903. template <typename Container>
  4904. operator Matcher<Container>() const {
  4905. return Matcher<Container>(
  4906. new EachMatcherImpl<const Container&>(inner_matcher_));
  4907. }
  4908. private:
  4909. const M inner_matcher_;
  4910. };
  4911. struct Rank1 {};
  4912. struct Rank0 : Rank1 {};
  4913. namespace pair_getters {
  4914. using std::get;
  4915. template <typename T>
  4916. auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT
  4917. return get<0>(x);
  4918. }
  4919. template <typename T>
  4920. auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT
  4921. return x.first;
  4922. }
  4923. template <typename T>
  4924. auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT
  4925. return get<1>(x);
  4926. }
  4927. template <typename T>
  4928. auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT
  4929. return x.second;
  4930. }
  4931. } // namespace pair_getters
  4932. // Implements Key(inner_matcher) for the given argument pair type.
  4933. // Key(inner_matcher) matches an std::pair whose 'first' field matches
  4934. // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
  4935. // std::map that contains at least one element whose key is >= 5.
  4936. template <typename PairType>
  4937. class KeyMatcherImpl : public MatcherInterface<PairType> {
  4938. public:
  4939. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
  4940. typedef typename RawPairType::first_type KeyType;
  4941. template <typename InnerMatcher>
  4942. explicit KeyMatcherImpl(InnerMatcher inner_matcher)
  4943. : inner_matcher_(
  4944. testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
  4945. }
  4946. // Returns true if and only if 'key_value.first' (the key) matches the inner
  4947. // matcher.
  4948. bool MatchAndExplain(PairType key_value,
  4949. MatchResultListener* listener) const override {
  4950. StringMatchResultListener inner_listener;
  4951. const bool match = inner_matcher_.MatchAndExplain(
  4952. pair_getters::First(key_value, Rank0()), &inner_listener);
  4953. const std::string explanation = inner_listener.str();
  4954. if (explanation != "") {
  4955. *listener << "whose first field is a value " << explanation;
  4956. }
  4957. return match;
  4958. }
  4959. // Describes what this matcher does.
  4960. void DescribeTo(::std::ostream* os) const override {
  4961. *os << "has a key that ";
  4962. inner_matcher_.DescribeTo(os);
  4963. }
  4964. // Describes what the negation of this matcher does.
  4965. void DescribeNegationTo(::std::ostream* os) const override {
  4966. *os << "doesn't have a key that ";
  4967. inner_matcher_.DescribeTo(os);
  4968. }
  4969. private:
  4970. const Matcher<const KeyType&> inner_matcher_;
  4971. };
  4972. // Implements polymorphic Key(matcher_for_key).
  4973. template <typename M>
  4974. class KeyMatcher {
  4975. public:
  4976. explicit KeyMatcher(M m) : matcher_for_key_(m) {}
  4977. template <typename PairType>
  4978. operator Matcher<PairType>() const {
  4979. return Matcher<PairType>(
  4980. new KeyMatcherImpl<const PairType&>(matcher_for_key_));
  4981. }
  4982. private:
  4983. const M matcher_for_key_;
  4984. };
  4985. // Implements polymorphic Address(matcher_for_address).
  4986. template <typename InnerMatcher>
  4987. class AddressMatcher {
  4988. public:
  4989. explicit AddressMatcher(InnerMatcher m) : matcher_(m) {}
  4990. template <typename Type>
  4991. operator Matcher<Type>() const { // NOLINT
  4992. return Matcher<Type>(new Impl<const Type&>(matcher_));
  4993. }
  4994. private:
  4995. // The monomorphic implementation that works for a particular object type.
  4996. template <typename Type>
  4997. class Impl : public MatcherInterface<Type> {
  4998. public:
  4999. using Address = const GTEST_REMOVE_REFERENCE_AND_CONST_(Type) *;
  5000. explicit Impl(const InnerMatcher& matcher)
  5001. : matcher_(MatcherCast<Address>(matcher)) {}
  5002. void DescribeTo(::std::ostream* os) const override {
  5003. *os << "has address that ";
  5004. matcher_.DescribeTo(os);
  5005. }
  5006. void DescribeNegationTo(::std::ostream* os) const override {
  5007. *os << "does not have address that ";
  5008. matcher_.DescribeTo(os);
  5009. }
  5010. bool MatchAndExplain(Type object,
  5011. MatchResultListener* listener) const override {
  5012. *listener << "which has address ";
  5013. Address address = std::addressof(object);
  5014. return MatchPrintAndExplain(address, matcher_, listener);
  5015. }
  5016. private:
  5017. const Matcher<Address> matcher_;
  5018. };
  5019. const InnerMatcher matcher_;
  5020. };
  5021. // Implements Pair(first_matcher, second_matcher) for the given argument pair
  5022. // type with its two matchers. See Pair() function below.
  5023. template <typename PairType>
  5024. class PairMatcherImpl : public MatcherInterface<PairType> {
  5025. public:
  5026. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
  5027. typedef typename RawPairType::first_type FirstType;
  5028. typedef typename RawPairType::second_type SecondType;
  5029. template <typename FirstMatcher, typename SecondMatcher>
  5030. PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
  5031. : first_matcher_(
  5032. testing::SafeMatcherCast<const FirstType&>(first_matcher)),
  5033. second_matcher_(
  5034. testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
  5035. }
  5036. // Describes what this matcher does.
  5037. void DescribeTo(::std::ostream* os) const override {
  5038. *os << "has a first field that ";
  5039. first_matcher_.DescribeTo(os);
  5040. *os << ", and has a second field that ";
  5041. second_matcher_.DescribeTo(os);
  5042. }
  5043. // Describes what the negation of this matcher does.
  5044. void DescribeNegationTo(::std::ostream* os) const override {
  5045. *os << "has a first field that ";
  5046. first_matcher_.DescribeNegationTo(os);
  5047. *os << ", or has a second field that ";
  5048. second_matcher_.DescribeNegationTo(os);
  5049. }
  5050. // Returns true if and only if 'a_pair.first' matches first_matcher and
  5051. // 'a_pair.second' matches second_matcher.
  5052. bool MatchAndExplain(PairType a_pair,
  5053. MatchResultListener* listener) const override {
  5054. if (!listener->IsInterested()) {
  5055. // If the listener is not interested, we don't need to construct the
  5056. // explanation.
  5057. return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) &&
  5058. second_matcher_.Matches(pair_getters::Second(a_pair, Rank0()));
  5059. }
  5060. StringMatchResultListener first_inner_listener;
  5061. if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()),
  5062. &first_inner_listener)) {
  5063. *listener << "whose first field does not match";
  5064. PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
  5065. return false;
  5066. }
  5067. StringMatchResultListener second_inner_listener;
  5068. if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()),
  5069. &second_inner_listener)) {
  5070. *listener << "whose second field does not match";
  5071. PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
  5072. return false;
  5073. }
  5074. ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
  5075. listener);
  5076. return true;
  5077. }
  5078. private:
  5079. void ExplainSuccess(const std::string& first_explanation,
  5080. const std::string& second_explanation,
  5081. MatchResultListener* listener) const {
  5082. *listener << "whose both fields match";
  5083. if (first_explanation != "") {
  5084. *listener << ", where the first field is a value " << first_explanation;
  5085. }
  5086. if (second_explanation != "") {
  5087. *listener << ", ";
  5088. if (first_explanation != "") {
  5089. *listener << "and ";
  5090. } else {
  5091. *listener << "where ";
  5092. }
  5093. *listener << "the second field is a value " << second_explanation;
  5094. }
  5095. }
  5096. const Matcher<const FirstType&> first_matcher_;
  5097. const Matcher<const SecondType&> second_matcher_;
  5098. };
  5099. // Implements polymorphic Pair(first_matcher, second_matcher).
  5100. template <typename FirstMatcher, typename SecondMatcher>
  5101. class PairMatcher {
  5102. public:
  5103. PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
  5104. : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
  5105. template <typename PairType>
  5106. operator Matcher<PairType> () const {
  5107. return Matcher<PairType>(
  5108. new PairMatcherImpl<const PairType&>(first_matcher_, second_matcher_));
  5109. }
  5110. private:
  5111. const FirstMatcher first_matcher_;
  5112. const SecondMatcher second_matcher_;
  5113. };
  5114. template <typename T, size_t... I>
  5115. auto UnpackStructImpl(const T& t, IndexSequence<I...>, int)
  5116. -> decltype(std::tie(get<I>(t)...)) {
  5117. static_assert(std::tuple_size<T>::value == sizeof...(I),
  5118. "Number of arguments doesn't match the number of fields.");
  5119. return std::tie(get<I>(t)...);
  5120. }
  5121. #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
  5122. template <typename T>
  5123. auto UnpackStructImpl(const T& t, MakeIndexSequence<1>, char) {
  5124. const auto& [a] = t;
  5125. return std::tie(a);
  5126. }
  5127. template <typename T>
  5128. auto UnpackStructImpl(const T& t, MakeIndexSequence<2>, char) {
  5129. const auto& [a, b] = t;
  5130. return std::tie(a, b);
  5131. }
  5132. template <typename T>
  5133. auto UnpackStructImpl(const T& t, MakeIndexSequence<3>, char) {
  5134. const auto& [a, b, c] = t;
  5135. return std::tie(a, b, c);
  5136. }
  5137. template <typename T>
  5138. auto UnpackStructImpl(const T& t, MakeIndexSequence<4>, char) {
  5139. const auto& [a, b, c, d] = t;
  5140. return std::tie(a, b, c, d);
  5141. }
  5142. template <typename T>
  5143. auto UnpackStructImpl(const T& t, MakeIndexSequence<5>, char) {
  5144. const auto& [a, b, c, d, e] = t;
  5145. return std::tie(a, b, c, d, e);
  5146. }
  5147. template <typename T>
  5148. auto UnpackStructImpl(const T& t, MakeIndexSequence<6>, char) {
  5149. const auto& [a, b, c, d, e, f] = t;
  5150. return std::tie(a, b, c, d, e, f);
  5151. }
  5152. template <typename T>
  5153. auto UnpackStructImpl(const T& t, MakeIndexSequence<7>, char) {
  5154. const auto& [a, b, c, d, e, f, g] = t;
  5155. return std::tie(a, b, c, d, e, f, g);
  5156. }
  5157. template <typename T>
  5158. auto UnpackStructImpl(const T& t, MakeIndexSequence<8>, char) {
  5159. const auto& [a, b, c, d, e, f, g, h] = t;
  5160. return std::tie(a, b, c, d, e, f, g, h);
  5161. }
  5162. template <typename T>
  5163. auto UnpackStructImpl(const T& t, MakeIndexSequence<9>, char) {
  5164. const auto& [a, b, c, d, e, f, g, h, i] = t;
  5165. return std::tie(a, b, c, d, e, f, g, h, i);
  5166. }
  5167. template <typename T>
  5168. auto UnpackStructImpl(const T& t, MakeIndexSequence<10>, char) {
  5169. const auto& [a, b, c, d, e, f, g, h, i, j] = t;
  5170. return std::tie(a, b, c, d, e, f, g, h, i, j);
  5171. }
  5172. template <typename T>
  5173. auto UnpackStructImpl(const T& t, MakeIndexSequence<11>, char) {
  5174. const auto& [a, b, c, d, e, f, g, h, i, j, k] = t;
  5175. return std::tie(a, b, c, d, e, f, g, h, i, j, k);
  5176. }
  5177. template <typename T>
  5178. auto UnpackStructImpl(const T& t, MakeIndexSequence<12>, char) {
  5179. const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t;
  5180. return std::tie(a, b, c, d, e, f, g, h, i, j, k, l);
  5181. }
  5182. template <typename T>
  5183. auto UnpackStructImpl(const T& t, MakeIndexSequence<13>, char) {
  5184. const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t;
  5185. return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m);
  5186. }
  5187. template <typename T>
  5188. auto UnpackStructImpl(const T& t, MakeIndexSequence<14>, char) {
  5189. const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t;
  5190. return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
  5191. }
  5192. template <typename T>
  5193. auto UnpackStructImpl(const T& t, MakeIndexSequence<15>, char) {
  5194. const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t;
  5195. return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);
  5196. }
  5197. template <typename T>
  5198. auto UnpackStructImpl(const T& t, MakeIndexSequence<16>, char) {
  5199. const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t;
  5200. return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p);
  5201. }
  5202. #endif // defined(__cpp_structured_bindings)
  5203. template <size_t I, typename T>
  5204. auto UnpackStruct(const T& t)
  5205. -> decltype((UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0)) {
  5206. return (UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0);
  5207. }
  5208. // Helper function to do comma folding in C++11.
  5209. // The array ensures left-to-right order of evaluation.
  5210. // Usage: VariadicExpand({expr...});
  5211. template <typename T, size_t N>
  5212. void VariadicExpand(const T (&)[N]) {}
  5213. template <typename Struct, typename StructSize>
  5214. class FieldsAreMatcherImpl;
  5215. template <typename Struct, size_t... I>
  5216. class FieldsAreMatcherImpl<Struct, IndexSequence<I...>>
  5217. : public MatcherInterface<Struct> {
  5218. using UnpackedType =
  5219. decltype(UnpackStruct<sizeof...(I)>(std::declval<const Struct&>()));
  5220. using MatchersType = std::tuple<
  5221. Matcher<const typename std::tuple_element<I, UnpackedType>::type&>...>;
  5222. public:
  5223. template <typename Inner>
  5224. explicit FieldsAreMatcherImpl(const Inner& matchers)
  5225. : matchers_(testing::SafeMatcherCast<
  5226. const typename std::tuple_element<I, UnpackedType>::type&>(
  5227. std::get<I>(matchers))...) {}
  5228. void DescribeTo(::std::ostream* os) const override {
  5229. const char* separator = "";
  5230. VariadicExpand(
  5231. {(*os << separator << "has field #" << I << " that ",
  5232. std::get<I>(matchers_).DescribeTo(os), separator = ", and ")...});
  5233. }
  5234. void DescribeNegationTo(::std::ostream* os) const override {
  5235. const char* separator = "";
  5236. VariadicExpand({(*os << separator << "has field #" << I << " that ",
  5237. std::get<I>(matchers_).DescribeNegationTo(os),
  5238. separator = ", or ")...});
  5239. }
  5240. bool MatchAndExplain(Struct t, MatchResultListener* listener) const override {
  5241. return MatchInternal((UnpackStruct<sizeof...(I)>)(t), listener);
  5242. }
  5243. private:
  5244. bool MatchInternal(UnpackedType tuple, MatchResultListener* listener) const {
  5245. if (!listener->IsInterested()) {
  5246. // If the listener is not interested, we don't need to construct the
  5247. // explanation.
  5248. bool good = true;
  5249. VariadicExpand({good = good && std::get<I>(matchers_).Matches(
  5250. std::get<I>(tuple))...});
  5251. return good;
  5252. }
  5253. size_t failed_pos = ~size_t{};
  5254. std::vector<StringMatchResultListener> inner_listener(sizeof...(I));
  5255. VariadicExpand(
  5256. {failed_pos == ~size_t{} && !std::get<I>(matchers_).MatchAndExplain(
  5257. std::get<I>(tuple), &inner_listener[I])
  5258. ? failed_pos = I
  5259. : 0 ...});
  5260. if (failed_pos != ~size_t{}) {
  5261. *listener << "whose field #" << failed_pos << " does not match";
  5262. PrintIfNotEmpty(inner_listener[failed_pos].str(), listener->stream());
  5263. return false;
  5264. }
  5265. *listener << "whose all elements match";
  5266. const char* separator = ", where";
  5267. for (size_t index = 0; index < sizeof...(I); ++index) {
  5268. const std::string str = inner_listener[index].str();
  5269. if (!str.empty()) {
  5270. *listener << separator << " field #" << index << " is a value " << str;
  5271. separator = ", and";
  5272. }
  5273. }
  5274. return true;
  5275. }
  5276. MatchersType matchers_;
  5277. };
  5278. template <typename... Inner>
  5279. class FieldsAreMatcher {
  5280. public:
  5281. explicit FieldsAreMatcher(Inner... inner) : matchers_(std::move(inner)...) {}
  5282. template <typename Struct>
  5283. operator Matcher<Struct>() const { // NOLINT
  5284. return Matcher<Struct>(
  5285. new FieldsAreMatcherImpl<const Struct&, IndexSequenceFor<Inner...>>(
  5286. matchers_));
  5287. }
  5288. private:
  5289. std::tuple<Inner...> matchers_;
  5290. };
  5291. // Implements ElementsAre() and ElementsAreArray().
  5292. template <typename Container>
  5293. class ElementsAreMatcherImpl : public MatcherInterface<Container> {
  5294. public:
  5295. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  5296. typedef internal::StlContainerView<RawContainer> View;
  5297. typedef typename View::type StlContainer;
  5298. typedef typename View::const_reference StlContainerReference;
  5299. typedef typename StlContainer::value_type Element;
  5300. // Constructs the matcher from a sequence of element values or
  5301. // element matchers.
  5302. template <typename InputIter>
  5303. ElementsAreMatcherImpl(InputIter first, InputIter last) {
  5304. while (first != last) {
  5305. matchers_.push_back(MatcherCast<const Element&>(*first++));
  5306. }
  5307. }
  5308. // Describes what this matcher does.
  5309. void DescribeTo(::std::ostream* os) const override {
  5310. if (count() == 0) {
  5311. *os << "is empty";
  5312. } else if (count() == 1) {
  5313. *os << "has 1 element that ";
  5314. matchers_[0].DescribeTo(os);
  5315. } else {
  5316. *os << "has " << Elements(count()) << " where\n";
  5317. for (size_t i = 0; i != count(); ++i) {
  5318. *os << "element #" << i << " ";
  5319. matchers_[i].DescribeTo(os);
  5320. if (i + 1 < count()) {
  5321. *os << ",\n";
  5322. }
  5323. }
  5324. }
  5325. }
  5326. // Describes what the negation of this matcher does.
  5327. void DescribeNegationTo(::std::ostream* os) const override {
  5328. if (count() == 0) {
  5329. *os << "isn't empty";
  5330. return;
  5331. }
  5332. *os << "doesn't have " << Elements(count()) << ", or\n";
  5333. for (size_t i = 0; i != count(); ++i) {
  5334. *os << "element #" << i << " ";
  5335. matchers_[i].DescribeNegationTo(os);
  5336. if (i + 1 < count()) {
  5337. *os << ", or\n";
  5338. }
  5339. }
  5340. }
  5341. bool MatchAndExplain(Container container,
  5342. MatchResultListener* listener) const override {
  5343. // To work with stream-like "containers", we must only walk
  5344. // through the elements in one pass.
  5345. const bool listener_interested = listener->IsInterested();
  5346. // explanations[i] is the explanation of the element at index i.
  5347. ::std::vector<std::string> explanations(count());
  5348. StlContainerReference stl_container = View::ConstReference(container);
  5349. typename StlContainer::const_iterator it = stl_container.begin();
  5350. size_t exam_pos = 0;
  5351. bool mismatch_found = false; // Have we found a mismatched element yet?
  5352. // Go through the elements and matchers in pairs, until we reach
  5353. // the end of either the elements or the matchers, or until we find a
  5354. // mismatch.
  5355. for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
  5356. bool match; // Does the current element match the current matcher?
  5357. if (listener_interested) {
  5358. StringMatchResultListener s;
  5359. match = matchers_[exam_pos].MatchAndExplain(*it, &s);
  5360. explanations[exam_pos] = s.str();
  5361. } else {
  5362. match = matchers_[exam_pos].Matches(*it);
  5363. }
  5364. if (!match) {
  5365. mismatch_found = true;
  5366. break;
  5367. }
  5368. }
  5369. // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
  5370. // Find how many elements the actual container has. We avoid
  5371. // calling size() s.t. this code works for stream-like "containers"
  5372. // that don't define size().
  5373. size_t actual_count = exam_pos;
  5374. for (; it != stl_container.end(); ++it) {
  5375. ++actual_count;
  5376. }
  5377. if (actual_count != count()) {
  5378. // The element count doesn't match. If the container is empty,
  5379. // there's no need to explain anything as Google Mock already
  5380. // prints the empty container. Otherwise we just need to show
  5381. // how many elements there actually are.
  5382. if (listener_interested && (actual_count != 0)) {
  5383. *listener << "which has " << Elements(actual_count);
  5384. }
  5385. return false;
  5386. }
  5387. if (mismatch_found) {
  5388. // The element count matches, but the exam_pos-th element doesn't match.
  5389. if (listener_interested) {
  5390. *listener << "whose element #" << exam_pos << " doesn't match";
  5391. PrintIfNotEmpty(explanations[exam_pos], listener->stream());
  5392. }
  5393. return false;
  5394. }
  5395. // Every element matches its expectation. We need to explain why
  5396. // (the obvious ones can be skipped).
  5397. if (listener_interested) {
  5398. bool reason_printed = false;
  5399. for (size_t i = 0; i != count(); ++i) {
  5400. const std::string& s = explanations[i];
  5401. if (!s.empty()) {
  5402. if (reason_printed) {
  5403. *listener << ",\nand ";
  5404. }
  5405. *listener << "whose element #" << i << " matches, " << s;
  5406. reason_printed = true;
  5407. }
  5408. }
  5409. }
  5410. return true;
  5411. }
  5412. private:
  5413. static Message Elements(size_t count) {
  5414. return Message() << count << (count == 1 ? " element" : " elements");
  5415. }
  5416. size_t count() const { return matchers_.size(); }
  5417. ::std::vector<Matcher<const Element&> > matchers_;
  5418. };
  5419. // Connectivity matrix of (elements X matchers), in element-major order.
  5420. // Initially, there are no edges.
  5421. // Use NextGraph() to iterate over all possible edge configurations.
  5422. // Use Randomize() to generate a random edge configuration.
  5423. class GTEST_API_ MatchMatrix {
  5424. public:
  5425. MatchMatrix(size_t num_elements, size_t num_matchers)
  5426. : num_elements_(num_elements),
  5427. num_matchers_(num_matchers),
  5428. matched_(num_elements_* num_matchers_, 0) {
  5429. }
  5430. size_t LhsSize() const { return num_elements_; }
  5431. size_t RhsSize() const { return num_matchers_; }
  5432. bool HasEdge(size_t ilhs, size_t irhs) const {
  5433. return matched_[SpaceIndex(ilhs, irhs)] == 1;
  5434. }
  5435. void SetEdge(size_t ilhs, size_t irhs, bool b) {
  5436. matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
  5437. }
  5438. // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
  5439. // adds 1 to that number; returns false if incrementing the graph left it
  5440. // empty.
  5441. bool NextGraph();
  5442. void Randomize();
  5443. std::string DebugString() const;
  5444. private:
  5445. size_t SpaceIndex(size_t ilhs, size_t irhs) const {
  5446. return ilhs * num_matchers_ + irhs;
  5447. }
  5448. size_t num_elements_;
  5449. size_t num_matchers_;
  5450. // Each element is a char interpreted as bool. They are stored as a
  5451. // flattened array in lhs-major order, use 'SpaceIndex()' to translate
  5452. // a (ilhs, irhs) matrix coordinate into an offset.
  5453. ::std::vector<char> matched_;
  5454. };
  5455. typedef ::std::pair<size_t, size_t> ElementMatcherPair;
  5456. typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
  5457. // Returns a maximum bipartite matching for the specified graph 'g'.
  5458. // The matching is represented as a vector of {element, matcher} pairs.
  5459. GTEST_API_ ElementMatcherPairs
  5460. FindMaxBipartiteMatching(const MatchMatrix& g);
  5461. struct UnorderedMatcherRequire {
  5462. enum Flags {
  5463. Superset = 1 << 0,
  5464. Subset = 1 << 1,
  5465. ExactMatch = Superset | Subset,
  5466. };
  5467. };
  5468. // Untyped base class for implementing UnorderedElementsAre. By
  5469. // putting logic that's not specific to the element type here, we
  5470. // reduce binary bloat and increase compilation speed.
  5471. class GTEST_API_ UnorderedElementsAreMatcherImplBase {
  5472. protected:
  5473. explicit UnorderedElementsAreMatcherImplBase(
  5474. UnorderedMatcherRequire::Flags matcher_flags)
  5475. : match_flags_(matcher_flags) {}
  5476. // A vector of matcher describers, one for each element matcher.
  5477. // Does not own the describers (and thus can be used only when the
  5478. // element matchers are alive).
  5479. typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
  5480. // Describes this UnorderedElementsAre matcher.
  5481. void DescribeToImpl(::std::ostream* os) const;
  5482. // Describes the negation of this UnorderedElementsAre matcher.
  5483. void DescribeNegationToImpl(::std::ostream* os) const;
  5484. bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,
  5485. const MatchMatrix& matrix,
  5486. MatchResultListener* listener) const;
  5487. bool FindPairing(const MatchMatrix& matrix,
  5488. MatchResultListener* listener) const;
  5489. MatcherDescriberVec& matcher_describers() {
  5490. return matcher_describers_;
  5491. }
  5492. static Message Elements(size_t n) {
  5493. return Message() << n << " element" << (n == 1 ? "" : "s");
  5494. }
  5495. UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }
  5496. private:
  5497. UnorderedMatcherRequire::Flags match_flags_;
  5498. MatcherDescriberVec matcher_describers_;
  5499. };
  5500. // Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
  5501. // IsSupersetOf.
  5502. template <typename Container>
  5503. class UnorderedElementsAreMatcherImpl
  5504. : public MatcherInterface<Container>,
  5505. public UnorderedElementsAreMatcherImplBase {
  5506. public:
  5507. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  5508. typedef internal::StlContainerView<RawContainer> View;
  5509. typedef typename View::type StlContainer;
  5510. typedef typename View::const_reference StlContainerReference;
  5511. typedef typename StlContainer::const_iterator StlContainerConstIterator;
  5512. typedef typename StlContainer::value_type Element;
  5513. template <typename InputIter>
  5514. UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,
  5515. InputIter first, InputIter last)
  5516. : UnorderedElementsAreMatcherImplBase(matcher_flags) {
  5517. for (; first != last; ++first) {
  5518. matchers_.push_back(MatcherCast<const Element&>(*first));
  5519. }
  5520. for (const auto& m : matchers_) {
  5521. matcher_describers().push_back(m.GetDescriber());
  5522. }
  5523. }
  5524. // Describes what this matcher does.
  5525. void DescribeTo(::std::ostream* os) const override {
  5526. return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
  5527. }
  5528. // Describes what the negation of this matcher does.
  5529. void DescribeNegationTo(::std::ostream* os) const override {
  5530. return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
  5531. }
  5532. bool MatchAndExplain(Container container,
  5533. MatchResultListener* listener) const override {
  5534. StlContainerReference stl_container = View::ConstReference(container);
  5535. ::std::vector<std::string> element_printouts;
  5536. MatchMatrix matrix =
  5537. AnalyzeElements(stl_container.begin(), stl_container.end(),
  5538. &element_printouts, listener);
  5539. if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
  5540. return true;
  5541. }
  5542. if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
  5543. if (matrix.LhsSize() != matrix.RhsSize()) {
  5544. // The element count doesn't match. If the container is empty,
  5545. // there's no need to explain anything as Google Mock already
  5546. // prints the empty container. Otherwise we just need to show
  5547. // how many elements there actually are.
  5548. if (matrix.LhsSize() != 0 && listener->IsInterested()) {
  5549. *listener << "which has " << Elements(matrix.LhsSize());
  5550. }
  5551. return false;
  5552. }
  5553. }
  5554. return VerifyMatchMatrix(element_printouts, matrix, listener) &&
  5555. FindPairing(matrix, listener);
  5556. }
  5557. private:
  5558. template <typename ElementIter>
  5559. MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
  5560. ::std::vector<std::string>* element_printouts,
  5561. MatchResultListener* listener) const {
  5562. element_printouts->clear();
  5563. ::std::vector<char> did_match;
  5564. size_t num_elements = 0;
  5565. DummyMatchResultListener dummy;
  5566. for (; elem_first != elem_last; ++num_elements, ++elem_first) {
  5567. if (listener->IsInterested()) {
  5568. element_printouts->push_back(PrintToString(*elem_first));
  5569. }
  5570. for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
  5571. did_match.push_back(
  5572. matchers_[irhs].MatchAndExplain(*elem_first, &dummy));
  5573. }
  5574. }
  5575. MatchMatrix matrix(num_elements, matchers_.size());
  5576. ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
  5577. for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
  5578. for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
  5579. matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
  5580. }
  5581. }
  5582. return matrix;
  5583. }
  5584. ::std::vector<Matcher<const Element&> > matchers_;
  5585. };
  5586. // Functor for use in TransformTuple.
  5587. // Performs MatcherCast<Target> on an input argument of any type.
  5588. template <typename Target>
  5589. struct CastAndAppendTransform {
  5590. template <typename Arg>
  5591. Matcher<Target> operator()(const Arg& a) const {
  5592. return MatcherCast<Target>(a);
  5593. }
  5594. };
  5595. // Implements UnorderedElementsAre.
  5596. template <typename MatcherTuple>
  5597. class UnorderedElementsAreMatcher {
  5598. public:
  5599. explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
  5600. : matchers_(args) {}
  5601. template <typename Container>
  5602. operator Matcher<Container>() const {
  5603. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  5604. typedef typename internal::StlContainerView<RawContainer>::type View;
  5605. typedef typename View::value_type Element;
  5606. typedef ::std::vector<Matcher<const Element&> > MatcherVec;
  5607. MatcherVec matchers;
  5608. matchers.reserve(::std::tuple_size<MatcherTuple>::value);
  5609. TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
  5610. ::std::back_inserter(matchers));
  5611. return Matcher<Container>(
  5612. new UnorderedElementsAreMatcherImpl<const Container&>(
  5613. UnorderedMatcherRequire::ExactMatch, matchers.begin(),
  5614. matchers.end()));
  5615. }
  5616. private:
  5617. const MatcherTuple matchers_;
  5618. };
  5619. // Implements ElementsAre.
  5620. template <typename MatcherTuple>
  5621. class ElementsAreMatcher {
  5622. public:
  5623. explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
  5624. template <typename Container>
  5625. operator Matcher<Container>() const {
  5626. GTEST_COMPILE_ASSERT_(
  5627. !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
  5628. ::std::tuple_size<MatcherTuple>::value < 2,
  5629. use_UnorderedElementsAre_with_hash_tables);
  5630. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  5631. typedef typename internal::StlContainerView<RawContainer>::type View;
  5632. typedef typename View::value_type Element;
  5633. typedef ::std::vector<Matcher<const Element&> > MatcherVec;
  5634. MatcherVec matchers;
  5635. matchers.reserve(::std::tuple_size<MatcherTuple>::value);
  5636. TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
  5637. ::std::back_inserter(matchers));
  5638. return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(
  5639. matchers.begin(), matchers.end()));
  5640. }
  5641. private:
  5642. const MatcherTuple matchers_;
  5643. };
  5644. // Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
  5645. template <typename T>
  5646. class UnorderedElementsAreArrayMatcher {
  5647. public:
  5648. template <typename Iter>
  5649. UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,
  5650. Iter first, Iter last)
  5651. : match_flags_(match_flags), matchers_(first, last) {}
  5652. template <typename Container>
  5653. operator Matcher<Container>() const {
  5654. return Matcher<Container>(
  5655. new UnorderedElementsAreMatcherImpl<const Container&>(
  5656. match_flags_, matchers_.begin(), matchers_.end()));
  5657. }
  5658. private:
  5659. UnorderedMatcherRequire::Flags match_flags_;
  5660. ::std::vector<T> matchers_;
  5661. };
  5662. // Implements ElementsAreArray().
  5663. template <typename T>
  5664. class ElementsAreArrayMatcher {
  5665. public:
  5666. template <typename Iter>
  5667. ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
  5668. template <typename Container>
  5669. operator Matcher<Container>() const {
  5670. GTEST_COMPILE_ASSERT_(
  5671. !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
  5672. use_UnorderedElementsAreArray_with_hash_tables);
  5673. return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(
  5674. matchers_.begin(), matchers_.end()));
  5675. }
  5676. private:
  5677. const ::std::vector<T> matchers_;
  5678. };
  5679. // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
  5680. // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
  5681. // second) is a polymorphic matcher that matches a value x if and only if
  5682. // tm matches tuple (x, second). Useful for implementing
  5683. // UnorderedPointwise() in terms of UnorderedElementsAreArray().
  5684. //
  5685. // BoundSecondMatcher is copyable and assignable, as we need to put
  5686. // instances of this class in a vector when implementing
  5687. // UnorderedPointwise().
  5688. template <typename Tuple2Matcher, typename Second>
  5689. class BoundSecondMatcher {
  5690. public:
  5691. BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
  5692. : tuple2_matcher_(tm), second_value_(second) {}
  5693. BoundSecondMatcher(const BoundSecondMatcher& other) = default;
  5694. template <typename T>
  5695. operator Matcher<T>() const {
  5696. return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
  5697. }
  5698. // We have to define this for UnorderedPointwise() to compile in
  5699. // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
  5700. // which requires the elements to be assignable in C++98. The
  5701. // compiler cannot generate the operator= for us, as Tuple2Matcher
  5702. // and Second may not be assignable.
  5703. //
  5704. // However, this should never be called, so the implementation just
  5705. // need to assert.
  5706. void operator=(const BoundSecondMatcher& /*rhs*/) {
  5707. GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
  5708. }
  5709. private:
  5710. template <typename T>
  5711. class Impl : public MatcherInterface<T> {
  5712. public:
  5713. typedef ::std::tuple<T, Second> ArgTuple;
  5714. Impl(const Tuple2Matcher& tm, const Second& second)
  5715. : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
  5716. second_value_(second) {}
  5717. void DescribeTo(::std::ostream* os) const override {
  5718. *os << "and ";
  5719. UniversalPrint(second_value_, os);
  5720. *os << " ";
  5721. mono_tuple2_matcher_.DescribeTo(os);
  5722. }
  5723. bool MatchAndExplain(T x, MatchResultListener* listener) const override {
  5724. return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
  5725. listener);
  5726. }
  5727. private:
  5728. const Matcher<const ArgTuple&> mono_tuple2_matcher_;
  5729. const Second second_value_;
  5730. };
  5731. const Tuple2Matcher tuple2_matcher_;
  5732. const Second second_value_;
  5733. };
  5734. // Given a 2-tuple matcher tm and a value second,
  5735. // MatcherBindSecond(tm, second) returns a matcher that matches a
  5736. // value x if and only if tm matches tuple (x, second). Useful for
  5737. // implementing UnorderedPointwise() in terms of UnorderedElementsAreArray().
  5738. template <typename Tuple2Matcher, typename Second>
  5739. BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
  5740. const Tuple2Matcher& tm, const Second& second) {
  5741. return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
  5742. }
  5743. // Returns the description for a matcher defined using the MATCHER*()
  5744. // macro where the user-supplied description string is "", if
  5745. // 'negation' is false; otherwise returns the description of the
  5746. // negation of the matcher. 'param_values' contains a list of strings
  5747. // that are the print-out of the matcher's parameters.
  5748. GTEST_API_ std::string FormatMatcherDescription(bool negation,
  5749. const char* matcher_name,
  5750. const Strings& param_values);
  5751. // Implements a matcher that checks the value of a optional<> type variable.
  5752. template <typename ValueMatcher>
  5753. class OptionalMatcher {
  5754. public:
  5755. explicit OptionalMatcher(const ValueMatcher& value_matcher)
  5756. : value_matcher_(value_matcher) {}
  5757. template <typename Optional>
  5758. operator Matcher<Optional>() const {
  5759. return Matcher<Optional>(new Impl<const Optional&>(value_matcher_));
  5760. }
  5761. template <typename Optional>
  5762. class Impl : public MatcherInterface<Optional> {
  5763. public:
  5764. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;
  5765. typedef typename OptionalView::value_type ValueType;
  5766. explicit Impl(const ValueMatcher& value_matcher)
  5767. : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}
  5768. void DescribeTo(::std::ostream* os) const override {
  5769. *os << "value ";
  5770. value_matcher_.DescribeTo(os);
  5771. }
  5772. void DescribeNegationTo(::std::ostream* os) const override {
  5773. *os << "value ";
  5774. value_matcher_.DescribeNegationTo(os);
  5775. }
  5776. bool MatchAndExplain(Optional optional,
  5777. MatchResultListener* listener) const override {
  5778. if (!optional) {
  5779. *listener << "which is not engaged";
  5780. return false;
  5781. }
  5782. const ValueType& value = *optional;
  5783. StringMatchResultListener value_listener;
  5784. const bool match = value_matcher_.MatchAndExplain(value, &value_listener);
  5785. *listener << "whose value " << PrintToString(value)
  5786. << (match ? " matches" : " doesn't match");
  5787. PrintIfNotEmpty(value_listener.str(), listener->stream());
  5788. return match;
  5789. }
  5790. private:
  5791. const Matcher<ValueType> value_matcher_;
  5792. };
  5793. private:
  5794. const ValueMatcher value_matcher_;
  5795. };
  5796. namespace variant_matcher {
  5797. // Overloads to allow VariantMatcher to do proper ADL lookup.
  5798. template <typename T>
  5799. void holds_alternative() {}
  5800. template <typename T>
  5801. void get() {}
  5802. // Implements a matcher that checks the value of a variant<> type variable.
  5803. template <typename T>
  5804. class VariantMatcher {
  5805. public:
  5806. explicit VariantMatcher(::testing::Matcher<const T&> matcher)
  5807. : matcher_(std::move(matcher)) {}
  5808. template <typename Variant>
  5809. bool MatchAndExplain(const Variant& value,
  5810. ::testing::MatchResultListener* listener) const {
  5811. using std::get;
  5812. if (!listener->IsInterested()) {
  5813. return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));
  5814. }
  5815. if (!holds_alternative<T>(value)) {
  5816. *listener << "whose value is not of type '" << GetTypeName() << "'";
  5817. return false;
  5818. }
  5819. const T& elem = get<T>(value);
  5820. StringMatchResultListener elem_listener;
  5821. const bool match = matcher_.MatchAndExplain(elem, &elem_listener);
  5822. *listener << "whose value " << PrintToString(elem)
  5823. << (match ? " matches" : " doesn't match");
  5824. PrintIfNotEmpty(elem_listener.str(), listener->stream());
  5825. return match;
  5826. }
  5827. void DescribeTo(std::ostream* os) const {
  5828. *os << "is a variant<> with value of type '" << GetTypeName()
  5829. << "' and the value ";
  5830. matcher_.DescribeTo(os);
  5831. }
  5832. void DescribeNegationTo(std::ostream* os) const {
  5833. *os << "is a variant<> with value of type other than '" << GetTypeName()
  5834. << "' or the value ";
  5835. matcher_.DescribeNegationTo(os);
  5836. }
  5837. private:
  5838. static std::string GetTypeName() {
  5839. #if GTEST_HAS_RTTI
  5840. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
  5841. return internal::GetTypeName<T>());
  5842. #endif
  5843. return "the element type";
  5844. }
  5845. const ::testing::Matcher<const T&> matcher_;
  5846. };
  5847. } // namespace variant_matcher
  5848. namespace any_cast_matcher {
  5849. // Overloads to allow AnyCastMatcher to do proper ADL lookup.
  5850. template <typename T>
  5851. void any_cast() {}
  5852. // Implements a matcher that any_casts the value.
  5853. template <typename T>
  5854. class AnyCastMatcher {
  5855. public:
  5856. explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)
  5857. : matcher_(matcher) {}
  5858. template <typename AnyType>
  5859. bool MatchAndExplain(const AnyType& value,
  5860. ::testing::MatchResultListener* listener) const {
  5861. if (!listener->IsInterested()) {
  5862. const T* ptr = any_cast<T>(&value);
  5863. return ptr != nullptr && matcher_.Matches(*ptr);
  5864. }
  5865. const T* elem = any_cast<T>(&value);
  5866. if (elem == nullptr) {
  5867. *listener << "whose value is not of type '" << GetTypeName() << "'";
  5868. return false;
  5869. }
  5870. StringMatchResultListener elem_listener;
  5871. const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);
  5872. *listener << "whose value " << PrintToString(*elem)
  5873. << (match ? " matches" : " doesn't match");
  5874. PrintIfNotEmpty(elem_listener.str(), listener->stream());
  5875. return match;
  5876. }
  5877. void DescribeTo(std::ostream* os) const {
  5878. *os << "is an 'any' type with value of type '" << GetTypeName()
  5879. << "' and the value ";
  5880. matcher_.DescribeTo(os);
  5881. }
  5882. void DescribeNegationTo(std::ostream* os) const {
  5883. *os << "is an 'any' type with value of type other than '" << GetTypeName()
  5884. << "' or the value ";
  5885. matcher_.DescribeNegationTo(os);
  5886. }
  5887. private:
  5888. static std::string GetTypeName() {
  5889. #if GTEST_HAS_RTTI
  5890. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
  5891. return internal::GetTypeName<T>());
  5892. #endif
  5893. return "the element type";
  5894. }
  5895. const ::testing::Matcher<const T&> matcher_;
  5896. };
  5897. } // namespace any_cast_matcher
  5898. // Implements the Args() matcher.
  5899. template <class ArgsTuple, size_t... k>
  5900. class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
  5901. public:
  5902. using RawArgsTuple = typename std::decay<ArgsTuple>::type;
  5903. using SelectedArgs =
  5904. std::tuple<typename std::tuple_element<k, RawArgsTuple>::type...>;
  5905. using MonomorphicInnerMatcher = Matcher<const SelectedArgs&>;
  5906. template <typename InnerMatcher>
  5907. explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)
  5908. : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}
  5909. bool MatchAndExplain(ArgsTuple args,
  5910. MatchResultListener* listener) const override {
  5911. // Workaround spurious C4100 on MSVC<=15.7 when k is empty.
  5912. (void)args;
  5913. const SelectedArgs& selected_args =
  5914. std::forward_as_tuple(std::get<k>(args)...);
  5915. if (!listener->IsInterested()) return inner_matcher_.Matches(selected_args);
  5916. PrintIndices(listener->stream());
  5917. *listener << "are " << PrintToString(selected_args);
  5918. StringMatchResultListener inner_listener;
  5919. const bool match =
  5920. inner_matcher_.MatchAndExplain(selected_args, &inner_listener);
  5921. PrintIfNotEmpty(inner_listener.str(), listener->stream());
  5922. return match;
  5923. }
  5924. void DescribeTo(::std::ostream* os) const override {
  5925. *os << "are a tuple ";
  5926. PrintIndices(os);
  5927. inner_matcher_.DescribeTo(os);
  5928. }
  5929. void DescribeNegationTo(::std::ostream* os) const override {
  5930. *os << "are a tuple ";
  5931. PrintIndices(os);
  5932. inner_matcher_.DescribeNegationTo(os);
  5933. }
  5934. private:
  5935. // Prints the indices of the selected fields.
  5936. static void PrintIndices(::std::ostream* os) {
  5937. *os << "whose fields (";
  5938. const char* sep = "";
  5939. // Workaround spurious C4189 on MSVC<=15.7 when k is empty.
  5940. (void)sep;
  5941. const char* dummy[] = {"", (*os << sep << "#" << k, sep = ", ")...};
  5942. (void)dummy;
  5943. *os << ") ";
  5944. }
  5945. MonomorphicInnerMatcher inner_matcher_;
  5946. };
  5947. template <class InnerMatcher, size_t... k>
  5948. class ArgsMatcher {
  5949. public:
  5950. explicit ArgsMatcher(InnerMatcher inner_matcher)
  5951. : inner_matcher_(std::move(inner_matcher)) {}
  5952. template <typename ArgsTuple>
  5953. operator Matcher<ArgsTuple>() const { // NOLINT
  5954. return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k...>(inner_matcher_));
  5955. }
  5956. private:
  5957. InnerMatcher inner_matcher_;
  5958. };
  5959. } // namespace internal
  5960. // ElementsAreArray(iterator_first, iterator_last)
  5961. // ElementsAreArray(pointer, count)
  5962. // ElementsAreArray(array)
  5963. // ElementsAreArray(container)
  5964. // ElementsAreArray({ e1, e2, ..., en })
  5965. //
  5966. // The ElementsAreArray() functions are like ElementsAre(...), except
  5967. // that they are given a homogeneous sequence rather than taking each
  5968. // element as a function argument. The sequence can be specified as an
  5969. // array, a pointer and count, a vector, an initializer list, or an
  5970. // STL iterator range. In each of these cases, the underlying sequence
  5971. // can be either a sequence of values or a sequence of matchers.
  5972. //
  5973. // All forms of ElementsAreArray() make a copy of the input matcher sequence.
  5974. template <typename Iter>
  5975. inline internal::ElementsAreArrayMatcher<
  5976. typename ::std::iterator_traits<Iter>::value_type>
  5977. ElementsAreArray(Iter first, Iter last) {
  5978. typedef typename ::std::iterator_traits<Iter>::value_type T;
  5979. return internal::ElementsAreArrayMatcher<T>(first, last);
  5980. }
  5981. template <typename T>
  5982. inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
  5983. const T* pointer, size_t count) {
  5984. return ElementsAreArray(pointer, pointer + count);
  5985. }
  5986. template <typename T, size_t N>
  5987. inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
  5988. const T (&array)[N]) {
  5989. return ElementsAreArray(array, N);
  5990. }
  5991. template <typename Container>
  5992. inline internal::ElementsAreArrayMatcher<typename Container::value_type>
  5993. ElementsAreArray(const Container& container) {
  5994. return ElementsAreArray(container.begin(), container.end());
  5995. }
  5996. template <typename T>
  5997. inline internal::ElementsAreArrayMatcher<T>
  5998. ElementsAreArray(::std::initializer_list<T> xs) {
  5999. return ElementsAreArray(xs.begin(), xs.end());
  6000. }
  6001. // UnorderedElementsAreArray(iterator_first, iterator_last)
  6002. // UnorderedElementsAreArray(pointer, count)
  6003. // UnorderedElementsAreArray(array)
  6004. // UnorderedElementsAreArray(container)
  6005. // UnorderedElementsAreArray({ e1, e2, ..., en })
  6006. //
  6007. // UnorderedElementsAreArray() verifies that a bijective mapping onto a
  6008. // collection of matchers exists.
  6009. //
  6010. // The matchers can be specified as an array, a pointer and count, a container,
  6011. // an initializer list, or an STL iterator range. In each of these cases, the
  6012. // underlying matchers can be either values or matchers.
  6013. template <typename Iter>
  6014. inline internal::UnorderedElementsAreArrayMatcher<
  6015. typename ::std::iterator_traits<Iter>::value_type>
  6016. UnorderedElementsAreArray(Iter first, Iter last) {
  6017. typedef typename ::std::iterator_traits<Iter>::value_type T;
  6018. return internal::UnorderedElementsAreArrayMatcher<T>(
  6019. internal::UnorderedMatcherRequire::ExactMatch, first, last);
  6020. }
  6021. template <typename T>
  6022. inline internal::UnorderedElementsAreArrayMatcher<T>
  6023. UnorderedElementsAreArray(const T* pointer, size_t count) {
  6024. return UnorderedElementsAreArray(pointer, pointer + count);
  6025. }
  6026. template <typename T, size_t N>
  6027. inline internal::UnorderedElementsAreArrayMatcher<T>
  6028. UnorderedElementsAreArray(const T (&array)[N]) {
  6029. return UnorderedElementsAreArray(array, N);
  6030. }
  6031. template <typename Container>
  6032. inline internal::UnorderedElementsAreArrayMatcher<
  6033. typename Container::value_type>
  6034. UnorderedElementsAreArray(const Container& container) {
  6035. return UnorderedElementsAreArray(container.begin(), container.end());
  6036. }
  6037. template <typename T>
  6038. inline internal::UnorderedElementsAreArrayMatcher<T>
  6039. UnorderedElementsAreArray(::std::initializer_list<T> xs) {
  6040. return UnorderedElementsAreArray(xs.begin(), xs.end());
  6041. }
  6042. // _ is a matcher that matches anything of any type.
  6043. //
  6044. // This definition is fine as:
  6045. //
  6046. // 1. The C++ standard permits using the name _ in a namespace that
  6047. // is not the global namespace or ::std.
  6048. // 2. The AnythingMatcher class has no data member or constructor,
  6049. // so it's OK to create global variables of this type.
  6050. // 3. c-style has approved of using _ in this case.
  6051. const internal::AnythingMatcher _ = {};
  6052. // Creates a matcher that matches any value of the given type T.
  6053. template <typename T>
  6054. inline Matcher<T> A() {
  6055. return _;
  6056. }
  6057. // Creates a matcher that matches any value of the given type T.
  6058. template <typename T>
  6059. inline Matcher<T> An() {
  6060. return _;
  6061. }
  6062. template <typename T, typename M>
  6063. Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
  6064. const M& value, std::false_type /* convertible_to_matcher */,
  6065. std::false_type /* convertible_to_T */) {
  6066. return Eq(value);
  6067. }
  6068. // Creates a polymorphic matcher that matches any NULL pointer.
  6069. inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
  6070. return MakePolymorphicMatcher(internal::IsNullMatcher());
  6071. }
  6072. // Creates a polymorphic matcher that matches any non-NULL pointer.
  6073. // This is convenient as Not(NULL) doesn't compile (the compiler
  6074. // thinks that that expression is comparing a pointer with an integer).
  6075. inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
  6076. return MakePolymorphicMatcher(internal::NotNullMatcher());
  6077. }
  6078. // Creates a polymorphic matcher that matches any argument that
  6079. // references variable x.
  6080. template <typename T>
  6081. inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
  6082. return internal::RefMatcher<T&>(x);
  6083. }
  6084. // Creates a polymorphic matcher that matches any NaN floating point.
  6085. inline PolymorphicMatcher<internal::IsNanMatcher> IsNan() {
  6086. return MakePolymorphicMatcher(internal::IsNanMatcher());
  6087. }
  6088. // Creates a matcher that matches any double argument approximately
  6089. // equal to rhs, where two NANs are considered unequal.
  6090. inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
  6091. return internal::FloatingEqMatcher<double>(rhs, false);
  6092. }
  6093. // Creates a matcher that matches any double argument approximately
  6094. // equal to rhs, including NaN values when rhs is NaN.
  6095. inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
  6096. return internal::FloatingEqMatcher<double>(rhs, true);
  6097. }
  6098. // Creates a matcher that matches any double argument approximately equal to
  6099. // rhs, up to the specified max absolute error bound, where two NANs are
  6100. // considered unequal. The max absolute error bound must be non-negative.
  6101. inline internal::FloatingEqMatcher<double> DoubleNear(
  6102. double rhs, double max_abs_error) {
  6103. return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
  6104. }
  6105. // Creates a matcher that matches any double argument approximately equal to
  6106. // rhs, up to the specified max absolute error bound, including NaN values when
  6107. // rhs is NaN. The max absolute error bound must be non-negative.
  6108. inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
  6109. double rhs, double max_abs_error) {
  6110. return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
  6111. }
  6112. // Creates a matcher that matches any float argument approximately
  6113. // equal to rhs, where two NANs are considered unequal.
  6114. inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
  6115. return internal::FloatingEqMatcher<float>(rhs, false);
  6116. }
  6117. // Creates a matcher that matches any float argument approximately
  6118. // equal to rhs, including NaN values when rhs is NaN.
  6119. inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
  6120. return internal::FloatingEqMatcher<float>(rhs, true);
  6121. }
  6122. // Creates a matcher that matches any float argument approximately equal to
  6123. // rhs, up to the specified max absolute error bound, where two NANs are
  6124. // considered unequal. The max absolute error bound must be non-negative.
  6125. inline internal::FloatingEqMatcher<float> FloatNear(
  6126. float rhs, float max_abs_error) {
  6127. return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
  6128. }
  6129. // Creates a matcher that matches any float argument approximately equal to
  6130. // rhs, up to the specified max absolute error bound, including NaN values when
  6131. // rhs is NaN. The max absolute error bound must be non-negative.
  6132. inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
  6133. float rhs, float max_abs_error) {
  6134. return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
  6135. }
  6136. // Creates a matcher that matches a pointer (raw or smart) that points
  6137. // to a value that matches inner_matcher.
  6138. template <typename InnerMatcher>
  6139. inline internal::PointeeMatcher<InnerMatcher> Pointee(
  6140. const InnerMatcher& inner_matcher) {
  6141. return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
  6142. }
  6143. #if GTEST_HAS_RTTI
  6144. // Creates a matcher that matches a pointer or reference that matches
  6145. // inner_matcher when dynamic_cast<To> is applied.
  6146. // The result of dynamic_cast<To> is forwarded to the inner matcher.
  6147. // If To is a pointer and the cast fails, the inner matcher will receive NULL.
  6148. // If To is a reference and the cast fails, this matcher returns false
  6149. // immediately.
  6150. template <typename To>
  6151. inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
  6152. WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
  6153. return MakePolymorphicMatcher(
  6154. internal::WhenDynamicCastToMatcher<To>(inner_matcher));
  6155. }
  6156. #endif // GTEST_HAS_RTTI
  6157. // Creates a matcher that matches an object whose given field matches
  6158. // 'matcher'. For example,
  6159. // Field(&Foo::number, Ge(5))
  6160. // matches a Foo object x if and only if x.number >= 5.
  6161. template <typename Class, typename FieldType, typename FieldMatcher>
  6162. inline PolymorphicMatcher<
  6163. internal::FieldMatcher<Class, FieldType> > Field(
  6164. FieldType Class::*field, const FieldMatcher& matcher) {
  6165. return MakePolymorphicMatcher(
  6166. internal::FieldMatcher<Class, FieldType>(
  6167. field, MatcherCast<const FieldType&>(matcher)));
  6168. // The call to MatcherCast() is required for supporting inner
  6169. // matchers of compatible types. For example, it allows
  6170. // Field(&Foo::bar, m)
  6171. // to compile where bar is an int32 and m is a matcher for int64.
  6172. }
  6173. // Same as Field() but also takes the name of the field to provide better error
  6174. // messages.
  6175. template <typename Class, typename FieldType, typename FieldMatcher>
  6176. inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
  6177. const std::string& field_name, FieldType Class::*field,
  6178. const FieldMatcher& matcher) {
  6179. return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
  6180. field_name, field, MatcherCast<const FieldType&>(matcher)));
  6181. }
  6182. // Creates a matcher that matches an object whose given property
  6183. // matches 'matcher'. For example,
  6184. // Property(&Foo::str, StartsWith("hi"))
  6185. // matches a Foo object x if and only if x.str() starts with "hi".
  6186. template <typename Class, typename PropertyType, typename PropertyMatcher>
  6187. inline PolymorphicMatcher<internal::PropertyMatcher<
  6188. Class, PropertyType, PropertyType (Class::*)() const> >
  6189. Property(PropertyType (Class::*property)() const,
  6190. const PropertyMatcher& matcher) {
  6191. return MakePolymorphicMatcher(
  6192. internal::PropertyMatcher<Class, PropertyType,
  6193. PropertyType (Class::*)() const>(
  6194. property, MatcherCast<const PropertyType&>(matcher)));
  6195. // The call to MatcherCast() is required for supporting inner
  6196. // matchers of compatible types. For example, it allows
  6197. // Property(&Foo::bar, m)
  6198. // to compile where bar() returns an int32 and m is a matcher for int64.
  6199. }
  6200. // Same as Property() above, but also takes the name of the property to provide
  6201. // better error messages.
  6202. template <typename Class, typename PropertyType, typename PropertyMatcher>
  6203. inline PolymorphicMatcher<internal::PropertyMatcher<
  6204. Class, PropertyType, PropertyType (Class::*)() const> >
  6205. Property(const std::string& property_name,
  6206. PropertyType (Class::*property)() const,
  6207. const PropertyMatcher& matcher) {
  6208. return MakePolymorphicMatcher(
  6209. internal::PropertyMatcher<Class, PropertyType,
  6210. PropertyType (Class::*)() const>(
  6211. property_name, property, MatcherCast<const PropertyType&>(matcher)));
  6212. }
  6213. // The same as above but for reference-qualified member functions.
  6214. template <typename Class, typename PropertyType, typename PropertyMatcher>
  6215. inline PolymorphicMatcher<internal::PropertyMatcher<
  6216. Class, PropertyType, PropertyType (Class::*)() const &> >
  6217. Property(PropertyType (Class::*property)() const &,
  6218. const PropertyMatcher& matcher) {
  6219. return MakePolymorphicMatcher(
  6220. internal::PropertyMatcher<Class, PropertyType,
  6221. PropertyType (Class::*)() const&>(
  6222. property, MatcherCast<const PropertyType&>(matcher)));
  6223. }
  6224. // Three-argument form for reference-qualified member functions.
  6225. template <typename Class, typename PropertyType, typename PropertyMatcher>
  6226. inline PolymorphicMatcher<internal::PropertyMatcher<
  6227. Class, PropertyType, PropertyType (Class::*)() const &> >
  6228. Property(const std::string& property_name,
  6229. PropertyType (Class::*property)() const &,
  6230. const PropertyMatcher& matcher) {
  6231. return MakePolymorphicMatcher(
  6232. internal::PropertyMatcher<Class, PropertyType,
  6233. PropertyType (Class::*)() const&>(
  6234. property_name, property, MatcherCast<const PropertyType&>(matcher)));
  6235. }
  6236. // Creates a matcher that matches an object if and only if the result of
  6237. // applying a callable to x matches 'matcher'. For example,
  6238. // ResultOf(f, StartsWith("hi"))
  6239. // matches a Foo object x if and only if f(x) starts with "hi".
  6240. // `callable` parameter can be a function, function pointer, or a functor. It is
  6241. // required to keep no state affecting the results of the calls on it and make
  6242. // no assumptions about how many calls will be made. Any state it keeps must be
  6243. // protected from the concurrent access.
  6244. template <typename Callable, typename InnerMatcher>
  6245. internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(
  6246. Callable callable, InnerMatcher matcher) {
  6247. return internal::ResultOfMatcher<Callable, InnerMatcher>(
  6248. std::move(callable), std::move(matcher));
  6249. }
  6250. // String matchers.
  6251. // Matches a string equal to str.
  6252. template <typename T = std::string>
  6253. PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
  6254. const internal::StringLike<T>& str) {
  6255. return MakePolymorphicMatcher(
  6256. internal::StrEqualityMatcher<std::string>(std::string(str), true, true));
  6257. }
  6258. // Matches a string not equal to str.
  6259. template <typename T = std::string>
  6260. PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
  6261. const internal::StringLike<T>& str) {
  6262. return MakePolymorphicMatcher(
  6263. internal::StrEqualityMatcher<std::string>(std::string(str), false, true));
  6264. }
  6265. // Matches a string equal to str, ignoring case.
  6266. template <typename T = std::string>
  6267. PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
  6268. const internal::StringLike<T>& str) {
  6269. return MakePolymorphicMatcher(
  6270. internal::StrEqualityMatcher<std::string>(std::string(str), true, false));
  6271. }
  6272. // Matches a string not equal to str, ignoring case.
  6273. template <typename T = std::string>
  6274. PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
  6275. const internal::StringLike<T>& str) {
  6276. return MakePolymorphicMatcher(internal::StrEqualityMatcher<std::string>(
  6277. std::string(str), false, false));
  6278. }
  6279. // Creates a matcher that matches any string, std::string, or C string
  6280. // that contains the given substring.
  6281. template <typename T = std::string>
  6282. PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
  6283. const internal::StringLike<T>& substring) {
  6284. return MakePolymorphicMatcher(
  6285. internal::HasSubstrMatcher<std::string>(std::string(substring)));
  6286. }
  6287. // Matches a string that starts with 'prefix' (case-sensitive).
  6288. template <typename T = std::string>
  6289. PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
  6290. const internal::StringLike<T>& prefix) {
  6291. return MakePolymorphicMatcher(
  6292. internal::StartsWithMatcher<std::string>(std::string(prefix)));
  6293. }
  6294. // Matches a string that ends with 'suffix' (case-sensitive).
  6295. template <typename T = std::string>
  6296. PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
  6297. const internal::StringLike<T>& suffix) {
  6298. return MakePolymorphicMatcher(
  6299. internal::EndsWithMatcher<std::string>(std::string(suffix)));
  6300. }
  6301. #if GTEST_HAS_STD_WSTRING
  6302. // Wide string matchers.
  6303. // Matches a string equal to str.
  6304. inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
  6305. const std::wstring& str) {
  6306. return MakePolymorphicMatcher(
  6307. internal::StrEqualityMatcher<std::wstring>(str, true, true));
  6308. }
  6309. // Matches a string not equal to str.
  6310. inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
  6311. const std::wstring& str) {
  6312. return MakePolymorphicMatcher(
  6313. internal::StrEqualityMatcher<std::wstring>(str, false, true));
  6314. }
  6315. // Matches a string equal to str, ignoring case.
  6316. inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
  6317. StrCaseEq(const std::wstring& str) {
  6318. return MakePolymorphicMatcher(
  6319. internal::StrEqualityMatcher<std::wstring>(str, true, false));
  6320. }
  6321. // Matches a string not equal to str, ignoring case.
  6322. inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
  6323. StrCaseNe(const std::wstring& str) {
  6324. return MakePolymorphicMatcher(
  6325. internal::StrEqualityMatcher<std::wstring>(str, false, false));
  6326. }
  6327. // Creates a matcher that matches any ::wstring, std::wstring, or C wide string
  6328. // that contains the given substring.
  6329. inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
  6330. const std::wstring& substring) {
  6331. return MakePolymorphicMatcher(
  6332. internal::HasSubstrMatcher<std::wstring>(substring));
  6333. }
  6334. // Matches a string that starts with 'prefix' (case-sensitive).
  6335. inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
  6336. StartsWith(const std::wstring& prefix) {
  6337. return MakePolymorphicMatcher(
  6338. internal::StartsWithMatcher<std::wstring>(prefix));
  6339. }
  6340. // Matches a string that ends with 'suffix' (case-sensitive).
  6341. inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
  6342. const std::wstring& suffix) {
  6343. return MakePolymorphicMatcher(
  6344. internal::EndsWithMatcher<std::wstring>(suffix));
  6345. }
  6346. #endif // GTEST_HAS_STD_WSTRING
  6347. // Creates a polymorphic matcher that matches a 2-tuple where the
  6348. // first field == the second field.
  6349. inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
  6350. // Creates a polymorphic matcher that matches a 2-tuple where the
  6351. // first field >= the second field.
  6352. inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
  6353. // Creates a polymorphic matcher that matches a 2-tuple where the
  6354. // first field > the second field.
  6355. inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
  6356. // Creates a polymorphic matcher that matches a 2-tuple where the
  6357. // first field <= the second field.
  6358. inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
  6359. // Creates a polymorphic matcher that matches a 2-tuple where the
  6360. // first field < the second field.
  6361. inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
  6362. // Creates a polymorphic matcher that matches a 2-tuple where the
  6363. // first field != the second field.
  6364. inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
  6365. // Creates a polymorphic matcher that matches a 2-tuple where
  6366. // FloatEq(first field) matches the second field.
  6367. inline internal::FloatingEq2Matcher<float> FloatEq() {
  6368. return internal::FloatingEq2Matcher<float>();
  6369. }
  6370. // Creates a polymorphic matcher that matches a 2-tuple where
  6371. // DoubleEq(first field) matches the second field.
  6372. inline internal::FloatingEq2Matcher<double> DoubleEq() {
  6373. return internal::FloatingEq2Matcher<double>();
  6374. }
  6375. // Creates a polymorphic matcher that matches a 2-tuple where
  6376. // FloatEq(first field) matches the second field with NaN equality.
  6377. inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {
  6378. return internal::FloatingEq2Matcher<float>(true);
  6379. }
  6380. // Creates a polymorphic matcher that matches a 2-tuple where
  6381. // DoubleEq(first field) matches the second field with NaN equality.
  6382. inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {
  6383. return internal::FloatingEq2Matcher<double>(true);
  6384. }
  6385. // Creates a polymorphic matcher that matches a 2-tuple where
  6386. // FloatNear(first field, max_abs_error) matches the second field.
  6387. inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {
  6388. return internal::FloatingEq2Matcher<float>(max_abs_error);
  6389. }
  6390. // Creates a polymorphic matcher that matches a 2-tuple where
  6391. // DoubleNear(first field, max_abs_error) matches the second field.
  6392. inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {
  6393. return internal::FloatingEq2Matcher<double>(max_abs_error);
  6394. }
  6395. // Creates a polymorphic matcher that matches a 2-tuple where
  6396. // FloatNear(first field, max_abs_error) matches the second field with NaN
  6397. // equality.
  6398. inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(
  6399. float max_abs_error) {
  6400. return internal::FloatingEq2Matcher<float>(max_abs_error, true);
  6401. }
  6402. // Creates a polymorphic matcher that matches a 2-tuple where
  6403. // DoubleNear(first field, max_abs_error) matches the second field with NaN
  6404. // equality.
  6405. inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(
  6406. double max_abs_error) {
  6407. return internal::FloatingEq2Matcher<double>(max_abs_error, true);
  6408. }
  6409. // Creates a matcher that matches any value of type T that m doesn't
  6410. // match.
  6411. template <typename InnerMatcher>
  6412. inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
  6413. return internal::NotMatcher<InnerMatcher>(m);
  6414. }
  6415. // Returns a matcher that matches anything that satisfies the given
  6416. // predicate. The predicate can be any unary function or functor
  6417. // whose return type can be implicitly converted to bool.
  6418. template <typename Predicate>
  6419. inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
  6420. Truly(Predicate pred) {
  6421. return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
  6422. }
  6423. // Returns a matcher that matches the container size. The container must
  6424. // support both size() and size_type which all STL-like containers provide.
  6425. // Note that the parameter 'size' can be a value of type size_type as well as
  6426. // matcher. For instance:
  6427. // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
  6428. // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
  6429. template <typename SizeMatcher>
  6430. inline internal::SizeIsMatcher<SizeMatcher>
  6431. SizeIs(const SizeMatcher& size_matcher) {
  6432. return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
  6433. }
  6434. // Returns a matcher that matches the distance between the container's begin()
  6435. // iterator and its end() iterator, i.e. the size of the container. This matcher
  6436. // can be used instead of SizeIs with containers such as std::forward_list which
  6437. // do not implement size(). The container must provide const_iterator (with
  6438. // valid iterator_traits), begin() and end().
  6439. template <typename DistanceMatcher>
  6440. inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
  6441. BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
  6442. return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
  6443. }
  6444. // Returns a matcher that matches an equal container.
  6445. // This matcher behaves like Eq(), but in the event of mismatch lists the
  6446. // values that are included in one container but not the other. (Duplicate
  6447. // values and order differences are not explained.)
  6448. template <typename Container>
  6449. inline PolymorphicMatcher<internal::ContainerEqMatcher<
  6450. typename std::remove_const<Container>::type>>
  6451. ContainerEq(const Container& rhs) {
  6452. return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs));
  6453. }
  6454. // Returns a matcher that matches a container that, when sorted using
  6455. // the given comparator, matches container_matcher.
  6456. template <typename Comparator, typename ContainerMatcher>
  6457. inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
  6458. WhenSortedBy(const Comparator& comparator,
  6459. const ContainerMatcher& container_matcher) {
  6460. return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
  6461. comparator, container_matcher);
  6462. }
  6463. // Returns a matcher that matches a container that, when sorted using
  6464. // the < operator, matches container_matcher.
  6465. template <typename ContainerMatcher>
  6466. inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
  6467. WhenSorted(const ContainerMatcher& container_matcher) {
  6468. return
  6469. internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
  6470. internal::LessComparator(), container_matcher);
  6471. }
  6472. // Matches an STL-style container or a native array that contains the
  6473. // same number of elements as in rhs, where its i-th element and rhs's
  6474. // i-th element (as a pair) satisfy the given pair matcher, for all i.
  6475. // TupleMatcher must be able to be safely cast to Matcher<std::tuple<const
  6476. // T1&, const T2&> >, where T1 and T2 are the types of elements in the
  6477. // LHS container and the RHS container respectively.
  6478. template <typename TupleMatcher, typename Container>
  6479. inline internal::PointwiseMatcher<TupleMatcher,
  6480. typename std::remove_const<Container>::type>
  6481. Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
  6482. return internal::PointwiseMatcher<TupleMatcher, Container>(tuple_matcher,
  6483. rhs);
  6484. }
  6485. // Supports the Pointwise(m, {a, b, c}) syntax.
  6486. template <typename TupleMatcher, typename T>
  6487. inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
  6488. const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
  6489. return Pointwise(tuple_matcher, std::vector<T>(rhs));
  6490. }
  6491. // UnorderedPointwise(pair_matcher, rhs) matches an STL-style
  6492. // container or a native array that contains the same number of
  6493. // elements as in rhs, where in some permutation of the container, its
  6494. // i-th element and rhs's i-th element (as a pair) satisfy the given
  6495. // pair matcher, for all i. Tuple2Matcher must be able to be safely
  6496. // cast to Matcher<std::tuple<const T1&, const T2&> >, where T1 and T2 are
  6497. // the types of elements in the LHS container and the RHS container
  6498. // respectively.
  6499. //
  6500. // This is like Pointwise(pair_matcher, rhs), except that the element
  6501. // order doesn't matter.
  6502. template <typename Tuple2Matcher, typename RhsContainer>
  6503. inline internal::UnorderedElementsAreArrayMatcher<
  6504. typename internal::BoundSecondMatcher<
  6505. Tuple2Matcher,
  6506. typename internal::StlContainerView<
  6507. typename std::remove_const<RhsContainer>::type>::type::value_type>>
  6508. UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
  6509. const RhsContainer& rhs_container) {
  6510. // RhsView allows the same code to handle RhsContainer being a
  6511. // STL-style container and it being a native C-style array.
  6512. typedef typename internal::StlContainerView<RhsContainer> RhsView;
  6513. typedef typename RhsView::type RhsStlContainer;
  6514. typedef typename RhsStlContainer::value_type Second;
  6515. const RhsStlContainer& rhs_stl_container =
  6516. RhsView::ConstReference(rhs_container);
  6517. // Create a matcher for each element in rhs_container.
  6518. ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
  6519. for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
  6520. it != rhs_stl_container.end(); ++it) {
  6521. matchers.push_back(
  6522. internal::MatcherBindSecond(tuple2_matcher, *it));
  6523. }
  6524. // Delegate the work to UnorderedElementsAreArray().
  6525. return UnorderedElementsAreArray(matchers);
  6526. }
  6527. // Supports the UnorderedPointwise(m, {a, b, c}) syntax.
  6528. template <typename Tuple2Matcher, typename T>
  6529. inline internal::UnorderedElementsAreArrayMatcher<
  6530. typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
  6531. UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
  6532. std::initializer_list<T> rhs) {
  6533. return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
  6534. }
  6535. // Matches an STL-style container or a native array that contains at
  6536. // least one element matching the given value or matcher.
  6537. //
  6538. // Examples:
  6539. // ::std::set<int> page_ids;
  6540. // page_ids.insert(3);
  6541. // page_ids.insert(1);
  6542. // EXPECT_THAT(page_ids, Contains(1));
  6543. // EXPECT_THAT(page_ids, Contains(Gt(2)));
  6544. // EXPECT_THAT(page_ids, Not(Contains(4)));
  6545. //
  6546. // ::std::map<int, size_t> page_lengths;
  6547. // page_lengths[1] = 100;
  6548. // EXPECT_THAT(page_lengths,
  6549. // Contains(::std::pair<const int, size_t>(1, 100)));
  6550. //
  6551. // const char* user_ids[] = { "joe", "mike", "tom" };
  6552. // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
  6553. template <typename M>
  6554. inline internal::ContainsMatcher<M> Contains(M matcher) {
  6555. return internal::ContainsMatcher<M>(matcher);
  6556. }
  6557. // IsSupersetOf(iterator_first, iterator_last)
  6558. // IsSupersetOf(pointer, count)
  6559. // IsSupersetOf(array)
  6560. // IsSupersetOf(container)
  6561. // IsSupersetOf({e1, e2, ..., en})
  6562. //
  6563. // IsSupersetOf() verifies that a surjective partial mapping onto a collection
  6564. // of matchers exists. In other words, a container matches
  6565. // IsSupersetOf({e1, ..., en}) if and only if there is a permutation
  6566. // {y1, ..., yn} of some of the container's elements where y1 matches e1,
  6567. // ..., and yn matches en. Obviously, the size of the container must be >= n
  6568. // in order to have a match. Examples:
  6569. //
  6570. // - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and
  6571. // 1 matches Ne(0).
  6572. // - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches
  6573. // both Eq(1) and Lt(2). The reason is that different matchers must be used
  6574. // for elements in different slots of the container.
  6575. // - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches
  6576. // Eq(1) and (the second) 1 matches Lt(2).
  6577. // - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)
  6578. // Gt(1) and 3 matches (the second) Gt(1).
  6579. //
  6580. // The matchers can be specified as an array, a pointer and count, a container,
  6581. // an initializer list, or an STL iterator range. In each of these cases, the
  6582. // underlying matchers can be either values or matchers.
  6583. template <typename Iter>
  6584. inline internal::UnorderedElementsAreArrayMatcher<
  6585. typename ::std::iterator_traits<Iter>::value_type>
  6586. IsSupersetOf(Iter first, Iter last) {
  6587. typedef typename ::std::iterator_traits<Iter>::value_type T;
  6588. return internal::UnorderedElementsAreArrayMatcher<T>(
  6589. internal::UnorderedMatcherRequire::Superset, first, last);
  6590. }
  6591. template <typename T>
  6592. inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
  6593. const T* pointer, size_t count) {
  6594. return IsSupersetOf(pointer, pointer + count);
  6595. }
  6596. template <typename T, size_t N>
  6597. inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
  6598. const T (&array)[N]) {
  6599. return IsSupersetOf(array, N);
  6600. }
  6601. template <typename Container>
  6602. inline internal::UnorderedElementsAreArrayMatcher<
  6603. typename Container::value_type>
  6604. IsSupersetOf(const Container& container) {
  6605. return IsSupersetOf(container.begin(), container.end());
  6606. }
  6607. template <typename T>
  6608. inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
  6609. ::std::initializer_list<T> xs) {
  6610. return IsSupersetOf(xs.begin(), xs.end());
  6611. }
  6612. // IsSubsetOf(iterator_first, iterator_last)
  6613. // IsSubsetOf(pointer, count)
  6614. // IsSubsetOf(array)
  6615. // IsSubsetOf(container)
  6616. // IsSubsetOf({e1, e2, ..., en})
  6617. //
  6618. // IsSubsetOf() verifies that an injective mapping onto a collection of matchers
  6619. // exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and
  6620. // only if there is a subset of matchers {m1, ..., mk} which would match the
  6621. // container using UnorderedElementsAre. Obviously, the size of the container
  6622. // must be <= n in order to have a match. Examples:
  6623. //
  6624. // - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
  6625. // - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
  6626. // matches Lt(0).
  6627. // - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
  6628. // match Gt(0). The reason is that different matchers must be used for
  6629. // elements in different slots of the container.
  6630. //
  6631. // The matchers can be specified as an array, a pointer and count, a container,
  6632. // an initializer list, or an STL iterator range. In each of these cases, the
  6633. // underlying matchers can be either values or matchers.
  6634. template <typename Iter>
  6635. inline internal::UnorderedElementsAreArrayMatcher<
  6636. typename ::std::iterator_traits<Iter>::value_type>
  6637. IsSubsetOf(Iter first, Iter last) {
  6638. typedef typename ::std::iterator_traits<Iter>::value_type T;
  6639. return internal::UnorderedElementsAreArrayMatcher<T>(
  6640. internal::UnorderedMatcherRequire::Subset, first, last);
  6641. }
  6642. template <typename T>
  6643. inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
  6644. const T* pointer, size_t count) {
  6645. return IsSubsetOf(pointer, pointer + count);
  6646. }
  6647. template <typename T, size_t N>
  6648. inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
  6649. const T (&array)[N]) {
  6650. return IsSubsetOf(array, N);
  6651. }
  6652. template <typename Container>
  6653. inline internal::UnorderedElementsAreArrayMatcher<
  6654. typename Container::value_type>
  6655. IsSubsetOf(const Container& container) {
  6656. return IsSubsetOf(container.begin(), container.end());
  6657. }
  6658. template <typename T>
  6659. inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
  6660. ::std::initializer_list<T> xs) {
  6661. return IsSubsetOf(xs.begin(), xs.end());
  6662. }
  6663. // Matches an STL-style container or a native array that contains only
  6664. // elements matching the given value or matcher.
  6665. //
  6666. // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
  6667. // the messages are different.
  6668. //
  6669. // Examples:
  6670. // ::std::set<int> page_ids;
  6671. // // Each(m) matches an empty container, regardless of what m is.
  6672. // EXPECT_THAT(page_ids, Each(Eq(1)));
  6673. // EXPECT_THAT(page_ids, Each(Eq(77)));
  6674. //
  6675. // page_ids.insert(3);
  6676. // EXPECT_THAT(page_ids, Each(Gt(0)));
  6677. // EXPECT_THAT(page_ids, Not(Each(Gt(4))));
  6678. // page_ids.insert(1);
  6679. // EXPECT_THAT(page_ids, Not(Each(Lt(2))));
  6680. //
  6681. // ::std::map<int, size_t> page_lengths;
  6682. // page_lengths[1] = 100;
  6683. // page_lengths[2] = 200;
  6684. // page_lengths[3] = 300;
  6685. // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
  6686. // EXPECT_THAT(page_lengths, Each(Key(Le(3))));
  6687. //
  6688. // const char* user_ids[] = { "joe", "mike", "tom" };
  6689. // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
  6690. template <typename M>
  6691. inline internal::EachMatcher<M> Each(M matcher) {
  6692. return internal::EachMatcher<M>(matcher);
  6693. }
  6694. // Key(inner_matcher) matches an std::pair whose 'first' field matches
  6695. // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
  6696. // std::map that contains at least one element whose key is >= 5.
  6697. template <typename M>
  6698. inline internal::KeyMatcher<M> Key(M inner_matcher) {
  6699. return internal::KeyMatcher<M>(inner_matcher);
  6700. }
  6701. // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
  6702. // matches first_matcher and whose 'second' field matches second_matcher. For
  6703. // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
  6704. // to match a std::map<int, string> that contains exactly one element whose key
  6705. // is >= 5 and whose value equals "foo".
  6706. template <typename FirstMatcher, typename SecondMatcher>
  6707. inline internal::PairMatcher<FirstMatcher, SecondMatcher>
  6708. Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
  6709. return internal::PairMatcher<FirstMatcher, SecondMatcher>(
  6710. first_matcher, second_matcher);
  6711. }
  6712. namespace no_adl {
  6713. // FieldsAre(matchers...) matches piecewise the fields of compatible structs.
  6714. // These include those that support `get<I>(obj)`, and when structured bindings
  6715. // are enabled any class that supports them.
  6716. // In particular, `std::tuple`, `std::pair`, `std::array` and aggregate types.
  6717. template <typename... M>
  6718. internal::FieldsAreMatcher<typename std::decay<M>::type...> FieldsAre(
  6719. M&&... matchers) {
  6720. return internal::FieldsAreMatcher<typename std::decay<M>::type...>(
  6721. std::forward<M>(matchers)...);
  6722. }
  6723. // Creates a matcher that matches a pointer (raw or smart) that matches
  6724. // inner_matcher.
  6725. template <typename InnerMatcher>
  6726. inline internal::PointerMatcher<InnerMatcher> Pointer(
  6727. const InnerMatcher& inner_matcher) {
  6728. return internal::PointerMatcher<InnerMatcher>(inner_matcher);
  6729. }
  6730. // Creates a matcher that matches an object that has an address that matches
  6731. // inner_matcher.
  6732. template <typename InnerMatcher>
  6733. inline internal::AddressMatcher<InnerMatcher> Address(
  6734. const InnerMatcher& inner_matcher) {
  6735. return internal::AddressMatcher<InnerMatcher>(inner_matcher);
  6736. }
  6737. } // namespace no_adl
  6738. // Returns a predicate that is satisfied by anything that matches the
  6739. // given matcher.
  6740. template <typename M>
  6741. inline internal::MatcherAsPredicate<M> Matches(M matcher) {
  6742. return internal::MatcherAsPredicate<M>(matcher);
  6743. }
  6744. // Returns true if and only if the value matches the matcher.
  6745. template <typename T, typename M>
  6746. inline bool Value(const T& value, M matcher) {
  6747. return testing::Matches(matcher)(value);
  6748. }
  6749. // Matches the value against the given matcher and explains the match
  6750. // result to listener.
  6751. template <typename T, typename M>
  6752. inline bool ExplainMatchResult(
  6753. M matcher, const T& value, MatchResultListener* listener) {
  6754. return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
  6755. }
  6756. // Returns a string representation of the given matcher. Useful for description
  6757. // strings of matchers defined using MATCHER_P* macros that accept matchers as
  6758. // their arguments. For example:
  6759. //
  6760. // MATCHER_P(XAndYThat, matcher,
  6761. // "X that " + DescribeMatcher<int>(matcher, negation) +
  6762. // " and Y that " + DescribeMatcher<double>(matcher, negation)) {
  6763. // return ExplainMatchResult(matcher, arg.x(), result_listener) &&
  6764. // ExplainMatchResult(matcher, arg.y(), result_listener);
  6765. // }
  6766. template <typename T, typename M>
  6767. std::string DescribeMatcher(const M& matcher, bool negation = false) {
  6768. ::std::stringstream ss;
  6769. Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);
  6770. if (negation) {
  6771. monomorphic_matcher.DescribeNegationTo(&ss);
  6772. } else {
  6773. monomorphic_matcher.DescribeTo(&ss);
  6774. }
  6775. return ss.str();
  6776. }
  6777. template <typename... Args>
  6778. internal::ElementsAreMatcher<
  6779. std::tuple<typename std::decay<const Args&>::type...>>
  6780. ElementsAre(const Args&... matchers) {
  6781. return internal::ElementsAreMatcher<
  6782. std::tuple<typename std::decay<const Args&>::type...>>(
  6783. std::make_tuple(matchers...));
  6784. }
  6785. template <typename... Args>
  6786. internal::UnorderedElementsAreMatcher<
  6787. std::tuple<typename std::decay<const Args&>::type...>>
  6788. UnorderedElementsAre(const Args&... matchers) {
  6789. return internal::UnorderedElementsAreMatcher<
  6790. std::tuple<typename std::decay<const Args&>::type...>>(
  6791. std::make_tuple(matchers...));
  6792. }
  6793. // Define variadic matcher versions.
  6794. template <typename... Args>
  6795. internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf(
  6796. const Args&... matchers) {
  6797. return internal::AllOfMatcher<typename std::decay<const Args&>::type...>(
  6798. matchers...);
  6799. }
  6800. template <typename... Args>
  6801. internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf(
  6802. const Args&... matchers) {
  6803. return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>(
  6804. matchers...);
  6805. }
  6806. // AnyOfArray(array)
  6807. // AnyOfArray(pointer, count)
  6808. // AnyOfArray(container)
  6809. // AnyOfArray({ e1, e2, ..., en })
  6810. // AnyOfArray(iterator_first, iterator_last)
  6811. //
  6812. // AnyOfArray() verifies whether a given value matches any member of a
  6813. // collection of matchers.
  6814. //
  6815. // AllOfArray(array)
  6816. // AllOfArray(pointer, count)
  6817. // AllOfArray(container)
  6818. // AllOfArray({ e1, e2, ..., en })
  6819. // AllOfArray(iterator_first, iterator_last)
  6820. //
  6821. // AllOfArray() verifies whether a given value matches all members of a
  6822. // collection of matchers.
  6823. //
  6824. // The matchers can be specified as an array, a pointer and count, a container,
  6825. // an initializer list, or an STL iterator range. In each of these cases, the
  6826. // underlying matchers can be either values or matchers.
  6827. template <typename Iter>
  6828. inline internal::AnyOfArrayMatcher<
  6829. typename ::std::iterator_traits<Iter>::value_type>
  6830. AnyOfArray(Iter first, Iter last) {
  6831. return internal::AnyOfArrayMatcher<
  6832. typename ::std::iterator_traits<Iter>::value_type>(first, last);
  6833. }
  6834. template <typename Iter>
  6835. inline internal::AllOfArrayMatcher<
  6836. typename ::std::iterator_traits<Iter>::value_type>
  6837. AllOfArray(Iter first, Iter last) {
  6838. return internal::AllOfArrayMatcher<
  6839. typename ::std::iterator_traits<Iter>::value_type>(first, last);
  6840. }
  6841. template <typename T>
  6842. inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T* ptr, size_t count) {
  6843. return AnyOfArray(ptr, ptr + count);
  6844. }
  6845. template <typename T>
  6846. inline internal::AllOfArrayMatcher<T> AllOfArray(const T* ptr, size_t count) {
  6847. return AllOfArray(ptr, ptr + count);
  6848. }
  6849. template <typename T, size_t N>
  6850. inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T (&array)[N]) {
  6851. return AnyOfArray(array, N);
  6852. }
  6853. template <typename T, size_t N>
  6854. inline internal::AllOfArrayMatcher<T> AllOfArray(const T (&array)[N]) {
  6855. return AllOfArray(array, N);
  6856. }
  6857. template <typename Container>
  6858. inline internal::AnyOfArrayMatcher<typename Container::value_type> AnyOfArray(
  6859. const Container& container) {
  6860. return AnyOfArray(container.begin(), container.end());
  6861. }
  6862. template <typename Container>
  6863. inline internal::AllOfArrayMatcher<typename Container::value_type> AllOfArray(
  6864. const Container& container) {
  6865. return AllOfArray(container.begin(), container.end());
  6866. }
  6867. template <typename T>
  6868. inline internal::AnyOfArrayMatcher<T> AnyOfArray(
  6869. ::std::initializer_list<T> xs) {
  6870. return AnyOfArray(xs.begin(), xs.end());
  6871. }
  6872. template <typename T>
  6873. inline internal::AllOfArrayMatcher<T> AllOfArray(
  6874. ::std::initializer_list<T> xs) {
  6875. return AllOfArray(xs.begin(), xs.end());
  6876. }
  6877. // Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected
  6878. // fields of it matches a_matcher. C++ doesn't support default
  6879. // arguments for function templates, so we have to overload it.
  6880. template <size_t... k, typename InnerMatcher>
  6881. internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...> Args(
  6882. InnerMatcher&& matcher) {
  6883. return internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...>(
  6884. std::forward<InnerMatcher>(matcher));
  6885. }
  6886. // AllArgs(m) is a synonym of m. This is useful in
  6887. //
  6888. // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
  6889. //
  6890. // which is easier to read than
  6891. //
  6892. // EXPECT_CALL(foo, Bar(_, _)).With(Eq());
  6893. template <typename InnerMatcher>
  6894. inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
  6895. // Returns a matcher that matches the value of an optional<> type variable.
  6896. // The matcher implementation only uses '!arg' and requires that the optional<>
  6897. // type has a 'value_type' member type and that '*arg' is of type 'value_type'
  6898. // and is printable using 'PrintToString'. It is compatible with
  6899. // std::optional/std::experimental::optional.
  6900. // Note that to compare an optional type variable against nullopt you should
  6901. // use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the
  6902. // optional value contains an optional itself.
  6903. template <typename ValueMatcher>
  6904. inline internal::OptionalMatcher<ValueMatcher> Optional(
  6905. const ValueMatcher& value_matcher) {
  6906. return internal::OptionalMatcher<ValueMatcher>(value_matcher);
  6907. }
  6908. // Returns a matcher that matches the value of a absl::any type variable.
  6909. template <typename T>
  6910. PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
  6911. const Matcher<const T&>& matcher) {
  6912. return MakePolymorphicMatcher(
  6913. internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
  6914. }
  6915. // Returns a matcher that matches the value of a variant<> type variable.
  6916. // The matcher implementation uses ADL to find the holds_alternative and get
  6917. // functions.
  6918. // It is compatible with std::variant.
  6919. template <typename T>
  6920. PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
  6921. const Matcher<const T&>& matcher) {
  6922. return MakePolymorphicMatcher(
  6923. internal::variant_matcher::VariantMatcher<T>(matcher));
  6924. }
  6925. #if GTEST_HAS_EXCEPTIONS
  6926. // Anything inside the `internal` namespace is internal to the implementation
  6927. // and must not be used in user code!
  6928. namespace internal {
  6929. class WithWhatMatcherImpl {
  6930. public:
  6931. WithWhatMatcherImpl(Matcher<std::string> matcher)
  6932. : matcher_(std::move(matcher)) {}
  6933. void DescribeTo(std::ostream* os) const {
  6934. *os << "contains .what() that ";
  6935. matcher_.DescribeTo(os);
  6936. }
  6937. void DescribeNegationTo(std::ostream* os) const {
  6938. *os << "contains .what() that does not ";
  6939. matcher_.DescribeTo(os);
  6940. }
  6941. template <typename Err>
  6942. bool MatchAndExplain(const Err& err, MatchResultListener* listener) const {
  6943. *listener << "which contains .what() that ";
  6944. return matcher_.MatchAndExplain(err.what(), listener);
  6945. }
  6946. private:
  6947. const Matcher<std::string> matcher_;
  6948. };
  6949. inline PolymorphicMatcher<WithWhatMatcherImpl> WithWhat(
  6950. Matcher<std::string> m) {
  6951. return MakePolymorphicMatcher(WithWhatMatcherImpl(std::move(m)));
  6952. }
  6953. template <typename Err>
  6954. class ExceptionMatcherImpl {
  6955. class NeverThrown {
  6956. public:
  6957. const char* what() const noexcept {
  6958. return "this exception should never be thrown";
  6959. }
  6960. };
  6961. // If the matchee raises an exception of a wrong type, we'd like to
  6962. // catch it and print its message and type. To do that, we add an additional
  6963. // catch clause:
  6964. //
  6965. // try { ... }
  6966. // catch (const Err&) { /* an expected exception */ }
  6967. // catch (const std::exception&) { /* exception of a wrong type */ }
  6968. //
  6969. // However, if the `Err` itself is `std::exception`, we'd end up with two
  6970. // identical `catch` clauses:
  6971. //
  6972. // try { ... }
  6973. // catch (const std::exception&) { /* an expected exception */ }
  6974. // catch (const std::exception&) { /* exception of a wrong type */ }
  6975. //
  6976. // This can cause a warning or an error in some compilers. To resolve
  6977. // the issue, we use a fake error type whenever `Err` is `std::exception`:
  6978. //
  6979. // try { ... }
  6980. // catch (const std::exception&) { /* an expected exception */ }
  6981. // catch (const NeverThrown&) { /* exception of a wrong type */ }
  6982. using DefaultExceptionType = typename std::conditional<
  6983. std::is_same<typename std::remove_cv<
  6984. typename std::remove_reference<Err>::type>::type,
  6985. std::exception>::value,
  6986. const NeverThrown&, const std::exception&>::type;
  6987. public:
  6988. ExceptionMatcherImpl(Matcher<const Err&> matcher)
  6989. : matcher_(std::move(matcher)) {}
  6990. void DescribeTo(std::ostream* os) const {
  6991. *os << "throws an exception which is a " << GetTypeName<Err>();
  6992. *os << " which ";
  6993. matcher_.DescribeTo(os);
  6994. }
  6995. void DescribeNegationTo(std::ostream* os) const {
  6996. *os << "throws an exception which is not a " << GetTypeName<Err>();
  6997. *os << " which ";
  6998. matcher_.DescribeNegationTo(os);
  6999. }
  7000. template <typename T>
  7001. bool MatchAndExplain(T&& x, MatchResultListener* listener) const {
  7002. try {
  7003. (void)(std::forward<T>(x)());
  7004. } catch (const Err& err) {
  7005. *listener << "throws an exception which is a " << GetTypeName<Err>();
  7006. *listener << " ";
  7007. return matcher_.MatchAndExplain(err, listener);
  7008. } catch (DefaultExceptionType err) {
  7009. #if GTEST_HAS_RTTI
  7010. *listener << "throws an exception of type " << GetTypeName(typeid(err));
  7011. *listener << " ";
  7012. #else
  7013. *listener << "throws an std::exception-derived type ";
  7014. #endif
  7015. *listener << "with description \"" << err.what() << "\"";
  7016. return false;
  7017. } catch (...) {
  7018. *listener << "throws an exception of an unknown type";
  7019. return false;
  7020. }
  7021. *listener << "does not throw any exception";
  7022. return false;
  7023. }
  7024. private:
  7025. const Matcher<const Err&> matcher_;
  7026. };
  7027. } // namespace internal
  7028. // Throws()
  7029. // Throws(exceptionMatcher)
  7030. // ThrowsMessage(messageMatcher)
  7031. //
  7032. // This matcher accepts a callable and verifies that when invoked, it throws
  7033. // an exception with the given type and properties.
  7034. //
  7035. // Examples:
  7036. //
  7037. // EXPECT_THAT(
  7038. // []() { throw std::runtime_error("message"); },
  7039. // Throws<std::runtime_error>());
  7040. //
  7041. // EXPECT_THAT(
  7042. // []() { throw std::runtime_error("message"); },
  7043. // ThrowsMessage<std::runtime_error>(HasSubstr("message")));
  7044. //
  7045. // EXPECT_THAT(
  7046. // []() { throw std::runtime_error("message"); },
  7047. // Throws<std::runtime_error>(
  7048. // Property(&std::runtime_error::what, HasSubstr("message"))));
  7049. template <typename Err>
  7050. PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws() {
  7051. return MakePolymorphicMatcher(
  7052. internal::ExceptionMatcherImpl<Err>(A<const Err&>()));
  7053. }
  7054. template <typename Err, typename ExceptionMatcher>
  7055. PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws(
  7056. const ExceptionMatcher& exception_matcher) {
  7057. // Using matcher cast allows users to pass a matcher of a more broad type.
  7058. // For example user may want to pass Matcher<std::exception>
  7059. // to Throws<std::runtime_error>, or Matcher<int64> to Throws<int32>.
  7060. return MakePolymorphicMatcher(internal::ExceptionMatcherImpl<Err>(
  7061. SafeMatcherCast<const Err&>(exception_matcher)));
  7062. }
  7063. template <typename Err, typename MessageMatcher>
  7064. PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
  7065. MessageMatcher&& message_matcher) {
  7066. static_assert(std::is_base_of<std::exception, Err>::value,
  7067. "expected an std::exception-derived type");
  7068. return Throws<Err>(internal::WithWhat(
  7069. MatcherCast<std::string>(std::forward<MessageMatcher>(message_matcher))));
  7070. }
  7071. #endif // GTEST_HAS_EXCEPTIONS
  7072. // These macros allow using matchers to check values in Google Test
  7073. // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
  7074. // succeed if and only if the value matches the matcher. If the assertion
  7075. // fails, the value and the description of the matcher will be printed.
  7076. #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
  7077. ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
  7078. #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
  7079. ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
  7080. // MATCHER* macroses itself are listed below.
  7081. #define MATCHER(name, description) \
  7082. class name##Matcher \
  7083. : public ::testing::internal::MatcherBaseImpl<name##Matcher> { \
  7084. public: \
  7085. template <typename arg_type> \
  7086. class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
  7087. public: \
  7088. gmock_Impl() {} \
  7089. bool MatchAndExplain( \
  7090. const arg_type& arg, \
  7091. ::testing::MatchResultListener* result_listener) const override; \
  7092. void DescribeTo(::std::ostream* gmock_os) const override { \
  7093. *gmock_os << FormatDescription(false); \
  7094. } \
  7095. void DescribeNegationTo(::std::ostream* gmock_os) const override { \
  7096. *gmock_os << FormatDescription(true); \
  7097. } \
  7098. \
  7099. private: \
  7100. ::std::string FormatDescription(bool negation) const { \
  7101. ::std::string gmock_description = (description); \
  7102. if (!gmock_description.empty()) { \
  7103. return gmock_description; \
  7104. } \
  7105. return ::testing::internal::FormatMatcherDescription(negation, #name, \
  7106. {}); \
  7107. } \
  7108. }; \
  7109. }; \
  7110. GTEST_ATTRIBUTE_UNUSED_ inline name##Matcher name() { return {}; } \
  7111. template <typename arg_type> \
  7112. bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \
  7113. const arg_type& arg, \
  7114. ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) \
  7115. const
  7116. #define MATCHER_P(name, p0, description) \
  7117. GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (p0))
  7118. #define MATCHER_P2(name, p0, p1, description) \
  7119. GMOCK_INTERNAL_MATCHER(name, name##MatcherP2, description, (p0, p1))
  7120. #define MATCHER_P3(name, p0, p1, p2, description) \
  7121. GMOCK_INTERNAL_MATCHER(name, name##MatcherP3, description, (p0, p1, p2))
  7122. #define MATCHER_P4(name, p0, p1, p2, p3, description) \
  7123. GMOCK_INTERNAL_MATCHER(name, name##MatcherP4, description, (p0, p1, p2, p3))
  7124. #define MATCHER_P5(name, p0, p1, p2, p3, p4, description) \
  7125. GMOCK_INTERNAL_MATCHER(name, name##MatcherP5, description, \
  7126. (p0, p1, p2, p3, p4))
  7127. #define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description) \
  7128. GMOCK_INTERNAL_MATCHER(name, name##MatcherP6, description, \
  7129. (p0, p1, p2, p3, p4, p5))
  7130. #define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description) \
  7131. GMOCK_INTERNAL_MATCHER(name, name##MatcherP7, description, \
  7132. (p0, p1, p2, p3, p4, p5, p6))
  7133. #define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description) \
  7134. GMOCK_INTERNAL_MATCHER(name, name##MatcherP8, description, \
  7135. (p0, p1, p2, p3, p4, p5, p6, p7))
  7136. #define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description) \
  7137. GMOCK_INTERNAL_MATCHER(name, name##MatcherP9, description, \
  7138. (p0, p1, p2, p3, p4, p5, p6, p7, p8))
  7139. #define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description) \
  7140. GMOCK_INTERNAL_MATCHER(name, name##MatcherP10, description, \
  7141. (p0, p1, p2, p3, p4, p5, p6, p7, p8, p9))
  7142. #define GMOCK_INTERNAL_MATCHER(name, full_name, description, args) \
  7143. template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
  7144. class full_name : public ::testing::internal::MatcherBaseImpl< \
  7145. full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>> { \
  7146. public: \
  7147. using full_name::MatcherBaseImpl::MatcherBaseImpl; \
  7148. template <typename arg_type> \
  7149. class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
  7150. public: \
  7151. explicit gmock_Impl(GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) \
  7152. : GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) {} \
  7153. bool MatchAndExplain( \
  7154. const arg_type& arg, \
  7155. ::testing::MatchResultListener* result_listener) const override; \
  7156. void DescribeTo(::std::ostream* gmock_os) const override { \
  7157. *gmock_os << FormatDescription(false); \
  7158. } \
  7159. void DescribeNegationTo(::std::ostream* gmock_os) const override { \
  7160. *gmock_os << FormatDescription(true); \
  7161. } \
  7162. GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
  7163. \
  7164. private: \
  7165. ::std::string FormatDescription(bool negation) const { \
  7166. ::std::string gmock_description = (description); \
  7167. if (!gmock_description.empty()) { \
  7168. return gmock_description; \
  7169. } \
  7170. return ::testing::internal::FormatMatcherDescription( \
  7171. negation, #name, \
  7172. ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \
  7173. ::std::tuple<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
  7174. GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args)))); \
  7175. } \
  7176. }; \
  7177. }; \
  7178. template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
  7179. inline full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)> name( \
  7180. GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) { \
  7181. return full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
  7182. GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args)); \
  7183. } \
  7184. template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
  7185. template <typename arg_type> \
  7186. bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>::gmock_Impl< \
  7187. arg_type>::MatchAndExplain(const arg_type& arg, \
  7188. ::testing::MatchResultListener* \
  7189. result_listener GTEST_ATTRIBUTE_UNUSED_) \
  7190. const
  7191. #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \
  7192. GMOCK_PP_TAIL( \
  7193. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM, , args))
  7194. #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM(i_unused, data_unused, arg) \
  7195. , typename arg##_type
  7196. #define GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args) \
  7197. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TYPE_PARAM, , args))
  7198. #define GMOCK_INTERNAL_MATCHER_TYPE_PARAM(i_unused, data_unused, arg) \
  7199. , arg##_type
  7200. #define GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args) \
  7201. GMOCK_PP_TAIL(dummy_first GMOCK_PP_FOR_EACH( \
  7202. GMOCK_INTERNAL_MATCHER_FUNCTION_ARG, , args))
  7203. #define GMOCK_INTERNAL_MATCHER_FUNCTION_ARG(i, data_unused, arg) \
  7204. , arg##_type gmock_p##i
  7205. #define GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) \
  7206. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_FORWARD_ARG, , args))
  7207. #define GMOCK_INTERNAL_MATCHER_FORWARD_ARG(i, data_unused, arg) \
  7208. , arg(::std::forward<arg##_type>(gmock_p##i))
  7209. #define GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
  7210. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER, , args)
  7211. #define GMOCK_INTERNAL_MATCHER_MEMBER(i_unused, data_unused, arg) \
  7212. const arg##_type arg;
  7213. #define GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args) \
  7214. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER_USAGE, , args))
  7215. #define GMOCK_INTERNAL_MATCHER_MEMBER_USAGE(i_unused, data_unused, arg) , arg
  7216. #define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \
  7217. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args))
  7218. #define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg_unused) \
  7219. , gmock_p##i
  7220. // To prevent ADL on certain functions we put them on a separate namespace.
  7221. using namespace no_adl; // NOLINT
  7222. } // namespace testing
  7223. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
  7224. // Include any custom callback matchers added by the local installation.
  7225. // We must include this header at the end to make sure it can use the
  7226. // declarations from this file.
  7227. // Copyright 2015, Google Inc.
  7228. // All rights reserved.
  7229. //
  7230. // Redistribution and use in source and binary forms, with or without
  7231. // modification, are permitted provided that the following conditions are
  7232. // met:
  7233. //
  7234. // * Redistributions of source code must retain the above copyright
  7235. // notice, this list of conditions and the following disclaimer.
  7236. // * Redistributions in binary form must reproduce the above
  7237. // copyright notice, this list of conditions and the following disclaimer
  7238. // in the documentation and/or other materials provided with the
  7239. // distribution.
  7240. // * Neither the name of Google Inc. nor the names of its
  7241. // contributors may be used to endorse or promote products derived from
  7242. // this software without specific prior written permission.
  7243. //
  7244. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7245. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7246. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7247. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7248. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7249. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7250. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7251. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7252. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7253. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7254. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7255. //
  7256. // Injection point for custom user configurations. See README for details
  7257. //
  7258. // GOOGLETEST_CM0002 DO NOT DELETE
  7259. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
  7260. #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
  7261. #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
  7262. #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
  7263. #if GTEST_HAS_EXCEPTIONS
  7264. # include <stdexcept> // NOLINT
  7265. #endif
  7266. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  7267. /* class A needs to have dll-interface to be used by clients of class B */)
  7268. namespace testing {
  7269. // An abstract handle of an expectation.
  7270. class Expectation;
  7271. // A set of expectation handles.
  7272. class ExpectationSet;
  7273. // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
  7274. // and MUST NOT BE USED IN USER CODE!!!
  7275. namespace internal {
  7276. // Implements a mock function.
  7277. template <typename F> class FunctionMocker;
  7278. // Base class for expectations.
  7279. class ExpectationBase;
  7280. // Implements an expectation.
  7281. template <typename F> class TypedExpectation;
  7282. // Helper class for testing the Expectation class template.
  7283. class ExpectationTester;
  7284. // Helper classes for implementing NiceMock, StrictMock, and NaggyMock.
  7285. template <typename MockClass>
  7286. class NiceMockImpl;
  7287. template <typename MockClass>
  7288. class StrictMockImpl;
  7289. template <typename MockClass>
  7290. class NaggyMockImpl;
  7291. // Protects the mock object registry (in class Mock), all function
  7292. // mockers, and all expectations.
  7293. //
  7294. // The reason we don't use more fine-grained protection is: when a
  7295. // mock function Foo() is called, it needs to consult its expectations
  7296. // to see which one should be picked. If another thread is allowed to
  7297. // call a mock function (either Foo() or a different one) at the same
  7298. // time, it could affect the "retired" attributes of Foo()'s
  7299. // expectations when InSequence() is used, and thus affect which
  7300. // expectation gets picked. Therefore, we sequence all mock function
  7301. // calls to ensure the integrity of the mock objects' states.
  7302. GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
  7303. // Untyped base class for ActionResultHolder<R>.
  7304. class UntypedActionResultHolderBase;
  7305. // Abstract base class of FunctionMocker. This is the
  7306. // type-agnostic part of the function mocker interface. Its pure
  7307. // virtual methods are implemented by FunctionMocker.
  7308. class GTEST_API_ UntypedFunctionMockerBase {
  7309. public:
  7310. UntypedFunctionMockerBase();
  7311. virtual ~UntypedFunctionMockerBase();
  7312. // Verifies that all expectations on this mock function have been
  7313. // satisfied. Reports one or more Google Test non-fatal failures
  7314. // and returns false if not.
  7315. bool VerifyAndClearExpectationsLocked()
  7316. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
  7317. // Clears the ON_CALL()s set on this mock function.
  7318. virtual void ClearDefaultActionsLocked()
  7319. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
  7320. // In all of the following Untyped* functions, it's the caller's
  7321. // responsibility to guarantee the correctness of the arguments'
  7322. // types.
  7323. // Performs the default action with the given arguments and returns
  7324. // the action's result. The call description string will be used in
  7325. // the error message to describe the call in the case the default
  7326. // action fails.
  7327. // L = *
  7328. virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
  7329. void* untyped_args, const std::string& call_description) const = 0;
  7330. // Performs the given action with the given arguments and returns
  7331. // the action's result.
  7332. // L = *
  7333. virtual UntypedActionResultHolderBase* UntypedPerformAction(
  7334. const void* untyped_action, void* untyped_args) const = 0;
  7335. // Writes a message that the call is uninteresting (i.e. neither
  7336. // explicitly expected nor explicitly unexpected) to the given
  7337. // ostream.
  7338. virtual void UntypedDescribeUninterestingCall(
  7339. const void* untyped_args,
  7340. ::std::ostream* os) const
  7341. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
  7342. // Returns the expectation that matches the given function arguments
  7343. // (or NULL is there's no match); when a match is found,
  7344. // untyped_action is set to point to the action that should be
  7345. // performed (or NULL if the action is "do default"), and
  7346. // is_excessive is modified to indicate whether the call exceeds the
  7347. // expected number.
  7348. virtual const ExpectationBase* UntypedFindMatchingExpectation(
  7349. const void* untyped_args,
  7350. const void** untyped_action, bool* is_excessive,
  7351. ::std::ostream* what, ::std::ostream* why)
  7352. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
  7353. // Prints the given function arguments to the ostream.
  7354. virtual void UntypedPrintArgs(const void* untyped_args,
  7355. ::std::ostream* os) const = 0;
  7356. // Sets the mock object this mock method belongs to, and registers
  7357. // this information in the global mock registry. Will be called
  7358. // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
  7359. // method.
  7360. void RegisterOwner(const void* mock_obj)
  7361. GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
  7362. // Sets the mock object this mock method belongs to, and sets the
  7363. // name of the mock function. Will be called upon each invocation
  7364. // of this mock function.
  7365. void SetOwnerAndName(const void* mock_obj, const char* name)
  7366. GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
  7367. // Returns the mock object this mock method belongs to. Must be
  7368. // called after RegisterOwner() or SetOwnerAndName() has been
  7369. // called.
  7370. const void* MockObject() const
  7371. GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
  7372. // Returns the name of this mock method. Must be called after
  7373. // SetOwnerAndName() has been called.
  7374. const char* Name() const
  7375. GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
  7376. // Returns the result of invoking this mock function with the given
  7377. // arguments. This function can be safely called from multiple
  7378. // threads concurrently. The caller is responsible for deleting the
  7379. // result.
  7380. UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
  7381. GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
  7382. protected:
  7383. typedef std::vector<const void*> UntypedOnCallSpecs;
  7384. using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
  7385. // Returns an Expectation object that references and co-owns exp,
  7386. // which must be an expectation on this mock function.
  7387. Expectation GetHandleOf(ExpectationBase* exp);
  7388. // Address of the mock object this mock method belongs to. Only
  7389. // valid after this mock method has been called or
  7390. // ON_CALL/EXPECT_CALL has been invoked on it.
  7391. const void* mock_obj_; // Protected by g_gmock_mutex.
  7392. // Name of the function being mocked. Only valid after this mock
  7393. // method has been called.
  7394. const char* name_; // Protected by g_gmock_mutex.
  7395. // All default action specs for this function mocker.
  7396. UntypedOnCallSpecs untyped_on_call_specs_;
  7397. // All expectations for this function mocker.
  7398. //
  7399. // It's undefined behavior to interleave expectations (EXPECT_CALLs
  7400. // or ON_CALLs) and mock function calls. Also, the order of
  7401. // expectations is important. Therefore it's a logic race condition
  7402. // to read/write untyped_expectations_ concurrently. In order for
  7403. // tools like tsan to catch concurrent read/write accesses to
  7404. // untyped_expectations, we deliberately leave accesses to it
  7405. // unprotected.
  7406. UntypedExpectations untyped_expectations_;
  7407. }; // class UntypedFunctionMockerBase
  7408. // Untyped base class for OnCallSpec<F>.
  7409. class UntypedOnCallSpecBase {
  7410. public:
  7411. // The arguments are the location of the ON_CALL() statement.
  7412. UntypedOnCallSpecBase(const char* a_file, int a_line)
  7413. : file_(a_file), line_(a_line), last_clause_(kNone) {}
  7414. // Where in the source file was the default action spec defined?
  7415. const char* file() const { return file_; }
  7416. int line() const { return line_; }
  7417. protected:
  7418. // Gives each clause in the ON_CALL() statement a name.
  7419. enum Clause {
  7420. // Do not change the order of the enum members! The run-time
  7421. // syntax checking relies on it.
  7422. kNone,
  7423. kWith,
  7424. kWillByDefault
  7425. };
  7426. // Asserts that the ON_CALL() statement has a certain property.
  7427. void AssertSpecProperty(bool property,
  7428. const std::string& failure_message) const {
  7429. Assert(property, file_, line_, failure_message);
  7430. }
  7431. // Expects that the ON_CALL() statement has a certain property.
  7432. void ExpectSpecProperty(bool property,
  7433. const std::string& failure_message) const {
  7434. Expect(property, file_, line_, failure_message);
  7435. }
  7436. const char* file_;
  7437. int line_;
  7438. // The last clause in the ON_CALL() statement as seen so far.
  7439. // Initially kNone and changes as the statement is parsed.
  7440. Clause last_clause_;
  7441. }; // class UntypedOnCallSpecBase
  7442. // This template class implements an ON_CALL spec.
  7443. template <typename F>
  7444. class OnCallSpec : public UntypedOnCallSpecBase {
  7445. public:
  7446. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  7447. typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
  7448. // Constructs an OnCallSpec object from the information inside
  7449. // the parenthesis of an ON_CALL() statement.
  7450. OnCallSpec(const char* a_file, int a_line,
  7451. const ArgumentMatcherTuple& matchers)
  7452. : UntypedOnCallSpecBase(a_file, a_line),
  7453. matchers_(matchers),
  7454. // By default, extra_matcher_ should match anything. However,
  7455. // we cannot initialize it with _ as that causes ambiguity between
  7456. // Matcher's copy and move constructor for some argument types.
  7457. extra_matcher_(A<const ArgumentTuple&>()) {}
  7458. // Implements the .With() clause.
  7459. OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
  7460. // Makes sure this is called at most once.
  7461. ExpectSpecProperty(last_clause_ < kWith,
  7462. ".With() cannot appear "
  7463. "more than once in an ON_CALL().");
  7464. last_clause_ = kWith;
  7465. extra_matcher_ = m;
  7466. return *this;
  7467. }
  7468. // Implements the .WillByDefault() clause.
  7469. OnCallSpec& WillByDefault(const Action<F>& action) {
  7470. ExpectSpecProperty(last_clause_ < kWillByDefault,
  7471. ".WillByDefault() must appear "
  7472. "exactly once in an ON_CALL().");
  7473. last_clause_ = kWillByDefault;
  7474. ExpectSpecProperty(!action.IsDoDefault(),
  7475. "DoDefault() cannot be used in ON_CALL().");
  7476. action_ = action;
  7477. return *this;
  7478. }
  7479. // Returns true if and only if the given arguments match the matchers.
  7480. bool Matches(const ArgumentTuple& args) const {
  7481. return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
  7482. }
  7483. // Returns the action specified by the user.
  7484. const Action<F>& GetAction() const {
  7485. AssertSpecProperty(last_clause_ == kWillByDefault,
  7486. ".WillByDefault() must appear exactly "
  7487. "once in an ON_CALL().");
  7488. return action_;
  7489. }
  7490. private:
  7491. // The information in statement
  7492. //
  7493. // ON_CALL(mock_object, Method(matchers))
  7494. // .With(multi-argument-matcher)
  7495. // .WillByDefault(action);
  7496. //
  7497. // is recorded in the data members like this:
  7498. //
  7499. // source file that contains the statement => file_
  7500. // line number of the statement => line_
  7501. // matchers => matchers_
  7502. // multi-argument-matcher => extra_matcher_
  7503. // action => action_
  7504. ArgumentMatcherTuple matchers_;
  7505. Matcher<const ArgumentTuple&> extra_matcher_;
  7506. Action<F> action_;
  7507. }; // class OnCallSpec
  7508. // Possible reactions on uninteresting calls.
  7509. enum CallReaction {
  7510. kAllow,
  7511. kWarn,
  7512. kFail,
  7513. };
  7514. } // namespace internal
  7515. // Utilities for manipulating mock objects.
  7516. class GTEST_API_ Mock {
  7517. public:
  7518. // The following public methods can be called concurrently.
  7519. // Tells Google Mock to ignore mock_obj when checking for leaked
  7520. // mock objects.
  7521. static void AllowLeak(const void* mock_obj)
  7522. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  7523. // Verifies and clears all expectations on the given mock object.
  7524. // If the expectations aren't satisfied, generates one or more
  7525. // Google Test non-fatal failures and returns false.
  7526. static bool VerifyAndClearExpectations(void* mock_obj)
  7527. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  7528. // Verifies all expectations on the given mock object and clears its
  7529. // default actions and expectations. Returns true if and only if the
  7530. // verification was successful.
  7531. static bool VerifyAndClear(void* mock_obj)
  7532. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  7533. // Returns whether the mock was created as a naggy mock (default)
  7534. static bool IsNaggy(void* mock_obj)
  7535. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  7536. // Returns whether the mock was created as a nice mock
  7537. static bool IsNice(void* mock_obj)
  7538. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  7539. // Returns whether the mock was created as a strict mock
  7540. static bool IsStrict(void* mock_obj)
  7541. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  7542. private:
  7543. friend class internal::UntypedFunctionMockerBase;
  7544. // Needed for a function mocker to register itself (so that we know
  7545. // how to clear a mock object).
  7546. template <typename F>
  7547. friend class internal::FunctionMocker;
  7548. template <typename MockClass>
  7549. friend class internal::NiceMockImpl;
  7550. template <typename MockClass>
  7551. friend class internal::NaggyMockImpl;
  7552. template <typename MockClass>
  7553. friend class internal::StrictMockImpl;
  7554. // Tells Google Mock to allow uninteresting calls on the given mock
  7555. // object.
  7556. static void AllowUninterestingCalls(const void* mock_obj)
  7557. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  7558. // Tells Google Mock to warn the user about uninteresting calls on
  7559. // the given mock object.
  7560. static void WarnUninterestingCalls(const void* mock_obj)
  7561. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  7562. // Tells Google Mock to fail uninteresting calls on the given mock
  7563. // object.
  7564. static void FailUninterestingCalls(const void* mock_obj)
  7565. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  7566. // Tells Google Mock the given mock object is being destroyed and
  7567. // its entry in the call-reaction table should be removed.
  7568. static void UnregisterCallReaction(const void* mock_obj)
  7569. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  7570. // Returns the reaction Google Mock will have on uninteresting calls
  7571. // made on the given mock object.
  7572. static internal::CallReaction GetReactionOnUninterestingCalls(
  7573. const void* mock_obj)
  7574. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  7575. // Verifies that all expectations on the given mock object have been
  7576. // satisfied. Reports one or more Google Test non-fatal failures
  7577. // and returns false if not.
  7578. static bool VerifyAndClearExpectationsLocked(void* mock_obj)
  7579. GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
  7580. // Clears all ON_CALL()s set on the given mock object.
  7581. static void ClearDefaultActionsLocked(void* mock_obj)
  7582. GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
  7583. // Registers a mock object and a mock method it owns.
  7584. static void Register(
  7585. const void* mock_obj,
  7586. internal::UntypedFunctionMockerBase* mocker)
  7587. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  7588. // Tells Google Mock where in the source code mock_obj is used in an
  7589. // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
  7590. // information helps the user identify which object it is.
  7591. static void RegisterUseByOnCallOrExpectCall(
  7592. const void* mock_obj, const char* file, int line)
  7593. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  7594. // Unregisters a mock method; removes the owning mock object from
  7595. // the registry when the last mock method associated with it has
  7596. // been unregistered. This is called only in the destructor of
  7597. // FunctionMocker.
  7598. static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
  7599. GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
  7600. }; // class Mock
  7601. // An abstract handle of an expectation. Useful in the .After()
  7602. // clause of EXPECT_CALL() for setting the (partial) order of
  7603. // expectations. The syntax:
  7604. //
  7605. // Expectation e1 = EXPECT_CALL(...)...;
  7606. // EXPECT_CALL(...).After(e1)...;
  7607. //
  7608. // sets two expectations where the latter can only be matched after
  7609. // the former has been satisfied.
  7610. //
  7611. // Notes:
  7612. // - This class is copyable and has value semantics.
  7613. // - Constness is shallow: a const Expectation object itself cannot
  7614. // be modified, but the mutable methods of the ExpectationBase
  7615. // object it references can be called via expectation_base().
  7616. class GTEST_API_ Expectation {
  7617. public:
  7618. // Constructs a null object that doesn't reference any expectation.
  7619. Expectation();
  7620. Expectation(Expectation&&) = default;
  7621. Expectation(const Expectation&) = default;
  7622. Expectation& operator=(Expectation&&) = default;
  7623. Expectation& operator=(const Expectation&) = default;
  7624. ~Expectation();
  7625. // This single-argument ctor must not be explicit, in order to support the
  7626. // Expectation e = EXPECT_CALL(...);
  7627. // syntax.
  7628. //
  7629. // A TypedExpectation object stores its pre-requisites as
  7630. // Expectation objects, and needs to call the non-const Retire()
  7631. // method on the ExpectationBase objects they reference. Therefore
  7632. // Expectation must receive a *non-const* reference to the
  7633. // ExpectationBase object.
  7634. Expectation(internal::ExpectationBase& exp); // NOLINT
  7635. // The compiler-generated copy ctor and operator= work exactly as
  7636. // intended, so we don't need to define our own.
  7637. // Returns true if and only if rhs references the same expectation as this
  7638. // object does.
  7639. bool operator==(const Expectation& rhs) const {
  7640. return expectation_base_ == rhs.expectation_base_;
  7641. }
  7642. bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
  7643. private:
  7644. friend class ExpectationSet;
  7645. friend class Sequence;
  7646. friend class ::testing::internal::ExpectationBase;
  7647. friend class ::testing::internal::UntypedFunctionMockerBase;
  7648. template <typename F>
  7649. friend class ::testing::internal::FunctionMocker;
  7650. template <typename F>
  7651. friend class ::testing::internal::TypedExpectation;
  7652. // This comparator is needed for putting Expectation objects into a set.
  7653. class Less {
  7654. public:
  7655. bool operator()(const Expectation& lhs, const Expectation& rhs) const {
  7656. return lhs.expectation_base_.get() < rhs.expectation_base_.get();
  7657. }
  7658. };
  7659. typedef ::std::set<Expectation, Less> Set;
  7660. Expectation(
  7661. const std::shared_ptr<internal::ExpectationBase>& expectation_base);
  7662. // Returns the expectation this object references.
  7663. const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
  7664. return expectation_base_;
  7665. }
  7666. // A shared_ptr that co-owns the expectation this handle references.
  7667. std::shared_ptr<internal::ExpectationBase> expectation_base_;
  7668. };
  7669. // A set of expectation handles. Useful in the .After() clause of
  7670. // EXPECT_CALL() for setting the (partial) order of expectations. The
  7671. // syntax:
  7672. //
  7673. // ExpectationSet es;
  7674. // es += EXPECT_CALL(...)...;
  7675. // es += EXPECT_CALL(...)...;
  7676. // EXPECT_CALL(...).After(es)...;
  7677. //
  7678. // sets three expectations where the last one can only be matched
  7679. // after the first two have both been satisfied.
  7680. //
  7681. // This class is copyable and has value semantics.
  7682. class ExpectationSet {
  7683. public:
  7684. // A bidirectional iterator that can read a const element in the set.
  7685. typedef Expectation::Set::const_iterator const_iterator;
  7686. // An object stored in the set. This is an alias of Expectation.
  7687. typedef Expectation::Set::value_type value_type;
  7688. // Constructs an empty set.
  7689. ExpectationSet() {}
  7690. // This single-argument ctor must not be explicit, in order to support the
  7691. // ExpectationSet es = EXPECT_CALL(...);
  7692. // syntax.
  7693. ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
  7694. *this += Expectation(exp);
  7695. }
  7696. // This single-argument ctor implements implicit conversion from
  7697. // Expectation and thus must not be explicit. This allows either an
  7698. // Expectation or an ExpectationSet to be used in .After().
  7699. ExpectationSet(const Expectation& e) { // NOLINT
  7700. *this += e;
  7701. }
  7702. // The compiler-generator ctor and operator= works exactly as
  7703. // intended, so we don't need to define our own.
  7704. // Returns true if and only if rhs contains the same set of Expectation
  7705. // objects as this does.
  7706. bool operator==(const ExpectationSet& rhs) const {
  7707. return expectations_ == rhs.expectations_;
  7708. }
  7709. bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
  7710. // Implements the syntax
  7711. // expectation_set += EXPECT_CALL(...);
  7712. ExpectationSet& operator+=(const Expectation& e) {
  7713. expectations_.insert(e);
  7714. return *this;
  7715. }
  7716. int size() const { return static_cast<int>(expectations_.size()); }
  7717. const_iterator begin() const { return expectations_.begin(); }
  7718. const_iterator end() const { return expectations_.end(); }
  7719. private:
  7720. Expectation::Set expectations_;
  7721. };
  7722. // Sequence objects are used by a user to specify the relative order
  7723. // in which the expectations should match. They are copyable (we rely
  7724. // on the compiler-defined copy constructor and assignment operator).
  7725. class GTEST_API_ Sequence {
  7726. public:
  7727. // Constructs an empty sequence.
  7728. Sequence() : last_expectation_(new Expectation) {}
  7729. // Adds an expectation to this sequence. The caller must ensure
  7730. // that no other thread is accessing this Sequence object.
  7731. void AddExpectation(const Expectation& expectation) const;
  7732. private:
  7733. // The last expectation in this sequence.
  7734. std::shared_ptr<Expectation> last_expectation_;
  7735. }; // class Sequence
  7736. // An object of this type causes all EXPECT_CALL() statements
  7737. // encountered in its scope to be put in an anonymous sequence. The
  7738. // work is done in the constructor and destructor. You should only
  7739. // create an InSequence object on the stack.
  7740. //
  7741. // The sole purpose for this class is to support easy definition of
  7742. // sequential expectations, e.g.
  7743. //
  7744. // {
  7745. // InSequence dummy; // The name of the object doesn't matter.
  7746. //
  7747. // // The following expectations must match in the order they appear.
  7748. // EXPECT_CALL(a, Bar())...;
  7749. // EXPECT_CALL(a, Baz())...;
  7750. // ...
  7751. // EXPECT_CALL(b, Xyz())...;
  7752. // }
  7753. //
  7754. // You can create InSequence objects in multiple threads, as long as
  7755. // they are used to affect different mock objects. The idea is that
  7756. // each thread can create and set up its own mocks as if it's the only
  7757. // thread. However, for clarity of your tests we recommend you to set
  7758. // up mocks in the main thread unless you have a good reason not to do
  7759. // so.
  7760. class GTEST_API_ InSequence {
  7761. public:
  7762. InSequence();
  7763. ~InSequence();
  7764. private:
  7765. bool sequence_created_;
  7766. GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
  7767. } GTEST_ATTRIBUTE_UNUSED_;
  7768. namespace internal {
  7769. // Points to the implicit sequence introduced by a living InSequence
  7770. // object (if any) in the current thread or NULL.
  7771. GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
  7772. // Base class for implementing expectations.
  7773. //
  7774. // There are two reasons for having a type-agnostic base class for
  7775. // Expectation:
  7776. //
  7777. // 1. We need to store collections of expectations of different
  7778. // types (e.g. all pre-requisites of a particular expectation, all
  7779. // expectations in a sequence). Therefore these expectation objects
  7780. // must share a common base class.
  7781. //
  7782. // 2. We can avoid binary code bloat by moving methods not depending
  7783. // on the template argument of Expectation to the base class.
  7784. //
  7785. // This class is internal and mustn't be used by user code directly.
  7786. class GTEST_API_ ExpectationBase {
  7787. public:
  7788. // source_text is the EXPECT_CALL(...) source that created this Expectation.
  7789. ExpectationBase(const char* file, int line, const std::string& source_text);
  7790. virtual ~ExpectationBase();
  7791. // Where in the source file was the expectation spec defined?
  7792. const char* file() const { return file_; }
  7793. int line() const { return line_; }
  7794. const char* source_text() const { return source_text_.c_str(); }
  7795. // Returns the cardinality specified in the expectation spec.
  7796. const Cardinality& cardinality() const { return cardinality_; }
  7797. // Describes the source file location of this expectation.
  7798. void DescribeLocationTo(::std::ostream* os) const {
  7799. *os << FormatFileLocation(file(), line()) << " ";
  7800. }
  7801. // Describes how many times a function call matching this
  7802. // expectation has occurred.
  7803. void DescribeCallCountTo(::std::ostream* os) const
  7804. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
  7805. // If this mock method has an extra matcher (i.e. .With(matcher)),
  7806. // describes it to the ostream.
  7807. virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
  7808. protected:
  7809. friend class ::testing::Expectation;
  7810. friend class UntypedFunctionMockerBase;
  7811. enum Clause {
  7812. // Don't change the order of the enum members!
  7813. kNone,
  7814. kWith,
  7815. kTimes,
  7816. kInSequence,
  7817. kAfter,
  7818. kWillOnce,
  7819. kWillRepeatedly,
  7820. kRetiresOnSaturation
  7821. };
  7822. typedef std::vector<const void*> UntypedActions;
  7823. // Returns an Expectation object that references and co-owns this
  7824. // expectation.
  7825. virtual Expectation GetHandle() = 0;
  7826. // Asserts that the EXPECT_CALL() statement has the given property.
  7827. void AssertSpecProperty(bool property,
  7828. const std::string& failure_message) const {
  7829. Assert(property, file_, line_, failure_message);
  7830. }
  7831. // Expects that the EXPECT_CALL() statement has the given property.
  7832. void ExpectSpecProperty(bool property,
  7833. const std::string& failure_message) const {
  7834. Expect(property, file_, line_, failure_message);
  7835. }
  7836. // Explicitly specifies the cardinality of this expectation. Used
  7837. // by the subclasses to implement the .Times() clause.
  7838. void SpecifyCardinality(const Cardinality& cardinality);
  7839. // Returns true if and only if the user specified the cardinality
  7840. // explicitly using a .Times().
  7841. bool cardinality_specified() const { return cardinality_specified_; }
  7842. // Sets the cardinality of this expectation spec.
  7843. void set_cardinality(const Cardinality& a_cardinality) {
  7844. cardinality_ = a_cardinality;
  7845. }
  7846. // The following group of methods should only be called after the
  7847. // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
  7848. // the current thread.
  7849. // Retires all pre-requisites of this expectation.
  7850. void RetireAllPreRequisites()
  7851. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
  7852. // Returns true if and only if this expectation is retired.
  7853. bool is_retired() const
  7854. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  7855. g_gmock_mutex.AssertHeld();
  7856. return retired_;
  7857. }
  7858. // Retires this expectation.
  7859. void Retire()
  7860. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  7861. g_gmock_mutex.AssertHeld();
  7862. retired_ = true;
  7863. }
  7864. // Returns true if and only if this expectation is satisfied.
  7865. bool IsSatisfied() const
  7866. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  7867. g_gmock_mutex.AssertHeld();
  7868. return cardinality().IsSatisfiedByCallCount(call_count_);
  7869. }
  7870. // Returns true if and only if this expectation is saturated.
  7871. bool IsSaturated() const
  7872. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  7873. g_gmock_mutex.AssertHeld();
  7874. return cardinality().IsSaturatedByCallCount(call_count_);
  7875. }
  7876. // Returns true if and only if this expectation is over-saturated.
  7877. bool IsOverSaturated() const
  7878. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  7879. g_gmock_mutex.AssertHeld();
  7880. return cardinality().IsOverSaturatedByCallCount(call_count_);
  7881. }
  7882. // Returns true if and only if all pre-requisites of this expectation are
  7883. // satisfied.
  7884. bool AllPrerequisitesAreSatisfied() const
  7885. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
  7886. // Adds unsatisfied pre-requisites of this expectation to 'result'.
  7887. void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
  7888. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
  7889. // Returns the number this expectation has been invoked.
  7890. int call_count() const
  7891. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  7892. g_gmock_mutex.AssertHeld();
  7893. return call_count_;
  7894. }
  7895. // Increments the number this expectation has been invoked.
  7896. void IncrementCallCount()
  7897. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  7898. g_gmock_mutex.AssertHeld();
  7899. call_count_++;
  7900. }
  7901. // Checks the action count (i.e. the number of WillOnce() and
  7902. // WillRepeatedly() clauses) against the cardinality if this hasn't
  7903. // been done before. Prints a warning if there are too many or too
  7904. // few actions.
  7905. void CheckActionCountIfNotDone() const
  7906. GTEST_LOCK_EXCLUDED_(mutex_);
  7907. friend class ::testing::Sequence;
  7908. friend class ::testing::internal::ExpectationTester;
  7909. template <typename Function>
  7910. friend class TypedExpectation;
  7911. // Implements the .Times() clause.
  7912. void UntypedTimes(const Cardinality& a_cardinality);
  7913. // This group of fields are part of the spec and won't change after
  7914. // an EXPECT_CALL() statement finishes.
  7915. const char* file_; // The file that contains the expectation.
  7916. int line_; // The line number of the expectation.
  7917. const std::string source_text_; // The EXPECT_CALL(...) source text.
  7918. // True if and only if the cardinality is specified explicitly.
  7919. bool cardinality_specified_;
  7920. Cardinality cardinality_; // The cardinality of the expectation.
  7921. // The immediate pre-requisites (i.e. expectations that must be
  7922. // satisfied before this expectation can be matched) of this
  7923. // expectation. We use std::shared_ptr in the set because we want an
  7924. // Expectation object to be co-owned by its FunctionMocker and its
  7925. // successors. This allows multiple mock objects to be deleted at
  7926. // different times.
  7927. ExpectationSet immediate_prerequisites_;
  7928. // This group of fields are the current state of the expectation,
  7929. // and can change as the mock function is called.
  7930. int call_count_; // How many times this expectation has been invoked.
  7931. bool retired_; // True if and only if this expectation has retired.
  7932. UntypedActions untyped_actions_;
  7933. bool extra_matcher_specified_;
  7934. bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
  7935. bool retires_on_saturation_;
  7936. Clause last_clause_;
  7937. mutable bool action_count_checked_; // Under mutex_.
  7938. mutable Mutex mutex_; // Protects action_count_checked_.
  7939. }; // class ExpectationBase
  7940. // Impements an expectation for the given function type.
  7941. template <typename F>
  7942. class TypedExpectation : public ExpectationBase {
  7943. public:
  7944. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  7945. typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
  7946. typedef typename Function<F>::Result Result;
  7947. TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
  7948. const std::string& a_source_text,
  7949. const ArgumentMatcherTuple& m)
  7950. : ExpectationBase(a_file, a_line, a_source_text),
  7951. owner_(owner),
  7952. matchers_(m),
  7953. // By default, extra_matcher_ should match anything. However,
  7954. // we cannot initialize it with _ as that causes ambiguity between
  7955. // Matcher's copy and move constructor for some argument types.
  7956. extra_matcher_(A<const ArgumentTuple&>()),
  7957. repeated_action_(DoDefault()) {}
  7958. ~TypedExpectation() override {
  7959. // Check the validity of the action count if it hasn't been done
  7960. // yet (for example, if the expectation was never used).
  7961. CheckActionCountIfNotDone();
  7962. for (UntypedActions::const_iterator it = untyped_actions_.begin();
  7963. it != untyped_actions_.end(); ++it) {
  7964. delete static_cast<const Action<F>*>(*it);
  7965. }
  7966. }
  7967. // Implements the .With() clause.
  7968. TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
  7969. if (last_clause_ == kWith) {
  7970. ExpectSpecProperty(false,
  7971. ".With() cannot appear "
  7972. "more than once in an EXPECT_CALL().");
  7973. } else {
  7974. ExpectSpecProperty(last_clause_ < kWith,
  7975. ".With() must be the first "
  7976. "clause in an EXPECT_CALL().");
  7977. }
  7978. last_clause_ = kWith;
  7979. extra_matcher_ = m;
  7980. extra_matcher_specified_ = true;
  7981. return *this;
  7982. }
  7983. // Implements the .Times() clause.
  7984. TypedExpectation& Times(const Cardinality& a_cardinality) {
  7985. ExpectationBase::UntypedTimes(a_cardinality);
  7986. return *this;
  7987. }
  7988. // Implements the .Times() clause.
  7989. TypedExpectation& Times(int n) {
  7990. return Times(Exactly(n));
  7991. }
  7992. // Implements the .InSequence() clause.
  7993. TypedExpectation& InSequence(const Sequence& s) {
  7994. ExpectSpecProperty(last_clause_ <= kInSequence,
  7995. ".InSequence() cannot appear after .After(),"
  7996. " .WillOnce(), .WillRepeatedly(), or "
  7997. ".RetiresOnSaturation().");
  7998. last_clause_ = kInSequence;
  7999. s.AddExpectation(GetHandle());
  8000. return *this;
  8001. }
  8002. TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
  8003. return InSequence(s1).InSequence(s2);
  8004. }
  8005. TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
  8006. const Sequence& s3) {
  8007. return InSequence(s1, s2).InSequence(s3);
  8008. }
  8009. TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
  8010. const Sequence& s3, const Sequence& s4) {
  8011. return InSequence(s1, s2, s3).InSequence(s4);
  8012. }
  8013. TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
  8014. const Sequence& s3, const Sequence& s4,
  8015. const Sequence& s5) {
  8016. return InSequence(s1, s2, s3, s4).InSequence(s5);
  8017. }
  8018. // Implements that .After() clause.
  8019. TypedExpectation& After(const ExpectationSet& s) {
  8020. ExpectSpecProperty(last_clause_ <= kAfter,
  8021. ".After() cannot appear after .WillOnce(),"
  8022. " .WillRepeatedly(), or "
  8023. ".RetiresOnSaturation().");
  8024. last_clause_ = kAfter;
  8025. for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
  8026. immediate_prerequisites_ += *it;
  8027. }
  8028. return *this;
  8029. }
  8030. TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
  8031. return After(s1).After(s2);
  8032. }
  8033. TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
  8034. const ExpectationSet& s3) {
  8035. return After(s1, s2).After(s3);
  8036. }
  8037. TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
  8038. const ExpectationSet& s3, const ExpectationSet& s4) {
  8039. return After(s1, s2, s3).After(s4);
  8040. }
  8041. TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
  8042. const ExpectationSet& s3, const ExpectationSet& s4,
  8043. const ExpectationSet& s5) {
  8044. return After(s1, s2, s3, s4).After(s5);
  8045. }
  8046. // Implements the .WillOnce() clause.
  8047. TypedExpectation& WillOnce(const Action<F>& action) {
  8048. ExpectSpecProperty(last_clause_ <= kWillOnce,
  8049. ".WillOnce() cannot appear after "
  8050. ".WillRepeatedly() or .RetiresOnSaturation().");
  8051. last_clause_ = kWillOnce;
  8052. untyped_actions_.push_back(new Action<F>(action));
  8053. if (!cardinality_specified()) {
  8054. set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
  8055. }
  8056. return *this;
  8057. }
  8058. // Implements the .WillRepeatedly() clause.
  8059. TypedExpectation& WillRepeatedly(const Action<F>& action) {
  8060. if (last_clause_ == kWillRepeatedly) {
  8061. ExpectSpecProperty(false,
  8062. ".WillRepeatedly() cannot appear "
  8063. "more than once in an EXPECT_CALL().");
  8064. } else {
  8065. ExpectSpecProperty(last_clause_ < kWillRepeatedly,
  8066. ".WillRepeatedly() cannot appear "
  8067. "after .RetiresOnSaturation().");
  8068. }
  8069. last_clause_ = kWillRepeatedly;
  8070. repeated_action_specified_ = true;
  8071. repeated_action_ = action;
  8072. if (!cardinality_specified()) {
  8073. set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
  8074. }
  8075. // Now that no more action clauses can be specified, we check
  8076. // whether their count makes sense.
  8077. CheckActionCountIfNotDone();
  8078. return *this;
  8079. }
  8080. // Implements the .RetiresOnSaturation() clause.
  8081. TypedExpectation& RetiresOnSaturation() {
  8082. ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
  8083. ".RetiresOnSaturation() cannot appear "
  8084. "more than once.");
  8085. last_clause_ = kRetiresOnSaturation;
  8086. retires_on_saturation_ = true;
  8087. // Now that no more action clauses can be specified, we check
  8088. // whether their count makes sense.
  8089. CheckActionCountIfNotDone();
  8090. return *this;
  8091. }
  8092. // Returns the matchers for the arguments as specified inside the
  8093. // EXPECT_CALL() macro.
  8094. const ArgumentMatcherTuple& matchers() const {
  8095. return matchers_;
  8096. }
  8097. // Returns the matcher specified by the .With() clause.
  8098. const Matcher<const ArgumentTuple&>& extra_matcher() const {
  8099. return extra_matcher_;
  8100. }
  8101. // Returns the action specified by the .WillRepeatedly() clause.
  8102. const Action<F>& repeated_action() const { return repeated_action_; }
  8103. // If this mock method has an extra matcher (i.e. .With(matcher)),
  8104. // describes it to the ostream.
  8105. void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
  8106. if (extra_matcher_specified_) {
  8107. *os << " Expected args: ";
  8108. extra_matcher_.DescribeTo(os);
  8109. *os << "\n";
  8110. }
  8111. }
  8112. private:
  8113. template <typename Function>
  8114. friend class FunctionMocker;
  8115. // Returns an Expectation object that references and co-owns this
  8116. // expectation.
  8117. Expectation GetHandle() override { return owner_->GetHandleOf(this); }
  8118. // The following methods will be called only after the EXPECT_CALL()
  8119. // statement finishes and when the current thread holds
  8120. // g_gmock_mutex.
  8121. // Returns true if and only if this expectation matches the given arguments.
  8122. bool Matches(const ArgumentTuple& args) const
  8123. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  8124. g_gmock_mutex.AssertHeld();
  8125. return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
  8126. }
  8127. // Returns true if and only if this expectation should handle the given
  8128. // arguments.
  8129. bool ShouldHandleArguments(const ArgumentTuple& args) const
  8130. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  8131. g_gmock_mutex.AssertHeld();
  8132. // In case the action count wasn't checked when the expectation
  8133. // was defined (e.g. if this expectation has no WillRepeatedly()
  8134. // or RetiresOnSaturation() clause), we check it when the
  8135. // expectation is used for the first time.
  8136. CheckActionCountIfNotDone();
  8137. return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
  8138. }
  8139. // Describes the result of matching the arguments against this
  8140. // expectation to the given ostream.
  8141. void ExplainMatchResultTo(
  8142. const ArgumentTuple& args,
  8143. ::std::ostream* os) const
  8144. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  8145. g_gmock_mutex.AssertHeld();
  8146. if (is_retired()) {
  8147. *os << " Expected: the expectation is active\n"
  8148. << " Actual: it is retired\n";
  8149. } else if (!Matches(args)) {
  8150. if (!TupleMatches(matchers_, args)) {
  8151. ExplainMatchFailureTupleTo(matchers_, args, os);
  8152. }
  8153. StringMatchResultListener listener;
  8154. if (!extra_matcher_.MatchAndExplain(args, &listener)) {
  8155. *os << " Expected args: ";
  8156. extra_matcher_.DescribeTo(os);
  8157. *os << "\n Actual: don't match";
  8158. internal::PrintIfNotEmpty(listener.str(), os);
  8159. *os << "\n";
  8160. }
  8161. } else if (!AllPrerequisitesAreSatisfied()) {
  8162. *os << " Expected: all pre-requisites are satisfied\n"
  8163. << " Actual: the following immediate pre-requisites "
  8164. << "are not satisfied:\n";
  8165. ExpectationSet unsatisfied_prereqs;
  8166. FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
  8167. int i = 0;
  8168. for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
  8169. it != unsatisfied_prereqs.end(); ++it) {
  8170. it->expectation_base()->DescribeLocationTo(os);
  8171. *os << "pre-requisite #" << i++ << "\n";
  8172. }
  8173. *os << " (end of pre-requisites)\n";
  8174. } else {
  8175. // This line is here just for completeness' sake. It will never
  8176. // be executed as currently the ExplainMatchResultTo() function
  8177. // is called only when the mock function call does NOT match the
  8178. // expectation.
  8179. *os << "The call matches the expectation.\n";
  8180. }
  8181. }
  8182. // Returns the action that should be taken for the current invocation.
  8183. const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
  8184. const ArgumentTuple& args) const
  8185. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  8186. g_gmock_mutex.AssertHeld();
  8187. const int count = call_count();
  8188. Assert(count >= 1, __FILE__, __LINE__,
  8189. "call_count() is <= 0 when GetCurrentAction() is "
  8190. "called - this should never happen.");
  8191. const int action_count = static_cast<int>(untyped_actions_.size());
  8192. if (action_count > 0 && !repeated_action_specified_ &&
  8193. count > action_count) {
  8194. // If there is at least one WillOnce() and no WillRepeatedly(),
  8195. // we warn the user when the WillOnce() clauses ran out.
  8196. ::std::stringstream ss;
  8197. DescribeLocationTo(&ss);
  8198. ss << "Actions ran out in " << source_text() << "...\n"
  8199. << "Called " << count << " times, but only "
  8200. << action_count << " WillOnce()"
  8201. << (action_count == 1 ? " is" : "s are") << " specified - ";
  8202. mocker->DescribeDefaultActionTo(args, &ss);
  8203. Log(kWarning, ss.str(), 1);
  8204. }
  8205. return count <= action_count
  8206. ? *static_cast<const Action<F>*>(
  8207. untyped_actions_[static_cast<size_t>(count - 1)])
  8208. : repeated_action();
  8209. }
  8210. // Given the arguments of a mock function call, if the call will
  8211. // over-saturate this expectation, returns the default action;
  8212. // otherwise, returns the next action in this expectation. Also
  8213. // describes *what* happened to 'what', and explains *why* Google
  8214. // Mock does it to 'why'. This method is not const as it calls
  8215. // IncrementCallCount(). A return value of NULL means the default
  8216. // action.
  8217. const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
  8218. const ArgumentTuple& args,
  8219. ::std::ostream* what,
  8220. ::std::ostream* why)
  8221. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  8222. g_gmock_mutex.AssertHeld();
  8223. if (IsSaturated()) {
  8224. // We have an excessive call.
  8225. IncrementCallCount();
  8226. *what << "Mock function called more times than expected - ";
  8227. mocker->DescribeDefaultActionTo(args, what);
  8228. DescribeCallCountTo(why);
  8229. return nullptr;
  8230. }
  8231. IncrementCallCount();
  8232. RetireAllPreRequisites();
  8233. if (retires_on_saturation_ && IsSaturated()) {
  8234. Retire();
  8235. }
  8236. // Must be done after IncrementCount()!
  8237. *what << "Mock function call matches " << source_text() <<"...\n";
  8238. return &(GetCurrentAction(mocker, args));
  8239. }
  8240. // All the fields below won't change once the EXPECT_CALL()
  8241. // statement finishes.
  8242. FunctionMocker<F>* const owner_;
  8243. ArgumentMatcherTuple matchers_;
  8244. Matcher<const ArgumentTuple&> extra_matcher_;
  8245. Action<F> repeated_action_;
  8246. GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
  8247. }; // class TypedExpectation
  8248. // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
  8249. // specifying the default behavior of, or expectation on, a mock
  8250. // function.
  8251. // Note: class MockSpec really belongs to the ::testing namespace.
  8252. // However if we define it in ::testing, MSVC will complain when
  8253. // classes in ::testing::internal declare it as a friend class
  8254. // template. To workaround this compiler bug, we define MockSpec in
  8255. // ::testing::internal and import it into ::testing.
  8256. // Logs a message including file and line number information.
  8257. GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
  8258. const char* file, int line,
  8259. const std::string& message);
  8260. template <typename F>
  8261. class MockSpec {
  8262. public:
  8263. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  8264. typedef typename internal::Function<F>::ArgumentMatcherTuple
  8265. ArgumentMatcherTuple;
  8266. // Constructs a MockSpec object, given the function mocker object
  8267. // that the spec is associated with.
  8268. MockSpec(internal::FunctionMocker<F>* function_mocker,
  8269. const ArgumentMatcherTuple& matchers)
  8270. : function_mocker_(function_mocker), matchers_(matchers) {}
  8271. // Adds a new default action spec to the function mocker and returns
  8272. // the newly created spec.
  8273. internal::OnCallSpec<F>& InternalDefaultActionSetAt(
  8274. const char* file, int line, const char* obj, const char* call) {
  8275. LogWithLocation(internal::kInfo, file, line,
  8276. std::string("ON_CALL(") + obj + ", " + call + ") invoked");
  8277. return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
  8278. }
  8279. // Adds a new expectation spec to the function mocker and returns
  8280. // the newly created spec.
  8281. internal::TypedExpectation<F>& InternalExpectedAt(
  8282. const char* file, int line, const char* obj, const char* call) {
  8283. const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
  8284. call + ")");
  8285. LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
  8286. return function_mocker_->AddNewExpectation(
  8287. file, line, source_text, matchers_);
  8288. }
  8289. // This operator overload is used to swallow the superfluous parameter list
  8290. // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
  8291. // explanation.
  8292. MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
  8293. return *this;
  8294. }
  8295. private:
  8296. template <typename Function>
  8297. friend class internal::FunctionMocker;
  8298. // The function mocker that owns this spec.
  8299. internal::FunctionMocker<F>* const function_mocker_;
  8300. // The argument matchers specified in the spec.
  8301. ArgumentMatcherTuple matchers_;
  8302. }; // class MockSpec
  8303. // Wrapper type for generically holding an ordinary value or lvalue reference.
  8304. // If T is not a reference type, it must be copyable or movable.
  8305. // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
  8306. // T is a move-only value type (which means that it will always be copyable
  8307. // if the current platform does not support move semantics).
  8308. //
  8309. // The primary template defines handling for values, but function header
  8310. // comments describe the contract for the whole template (including
  8311. // specializations).
  8312. template <typename T>
  8313. class ReferenceOrValueWrapper {
  8314. public:
  8315. // Constructs a wrapper from the given value/reference.
  8316. explicit ReferenceOrValueWrapper(T value)
  8317. : value_(std::move(value)) {
  8318. }
  8319. // Unwraps and returns the underlying value/reference, exactly as
  8320. // originally passed. The behavior of calling this more than once on
  8321. // the same object is unspecified.
  8322. T Unwrap() { return std::move(value_); }
  8323. // Provides nondestructive access to the underlying value/reference.
  8324. // Always returns a const reference (more precisely,
  8325. // const std::add_lvalue_reference<T>::type). The behavior of calling this
  8326. // after calling Unwrap on the same object is unspecified.
  8327. const T& Peek() const {
  8328. return value_;
  8329. }
  8330. private:
  8331. T value_;
  8332. };
  8333. // Specialization for lvalue reference types. See primary template
  8334. // for documentation.
  8335. template <typename T>
  8336. class ReferenceOrValueWrapper<T&> {
  8337. public:
  8338. // Workaround for debatable pass-by-reference lint warning (c-library-team
  8339. // policy precludes NOLINT in this context)
  8340. typedef T& reference;
  8341. explicit ReferenceOrValueWrapper(reference ref)
  8342. : value_ptr_(&ref) {}
  8343. T& Unwrap() { return *value_ptr_; }
  8344. const T& Peek() const { return *value_ptr_; }
  8345. private:
  8346. T* value_ptr_;
  8347. };
  8348. // C++ treats the void type specially. For example, you cannot define
  8349. // a void-typed variable or pass a void value to a function.
  8350. // ActionResultHolder<T> holds a value of type T, where T must be a
  8351. // copyable type or void (T doesn't need to be default-constructable).
  8352. // It hides the syntactic difference between void and other types, and
  8353. // is used to unify the code for invoking both void-returning and
  8354. // non-void-returning mock functions.
  8355. // Untyped base class for ActionResultHolder<T>.
  8356. class UntypedActionResultHolderBase {
  8357. public:
  8358. virtual ~UntypedActionResultHolderBase() {}
  8359. // Prints the held value as an action's result to os.
  8360. virtual void PrintAsActionResult(::std::ostream* os) const = 0;
  8361. };
  8362. // This generic definition is used when T is not void.
  8363. template <typename T>
  8364. class ActionResultHolder : public UntypedActionResultHolderBase {
  8365. public:
  8366. // Returns the held value. Must not be called more than once.
  8367. T Unwrap() {
  8368. return result_.Unwrap();
  8369. }
  8370. // Prints the held value as an action's result to os.
  8371. void PrintAsActionResult(::std::ostream* os) const override {
  8372. *os << "\n Returns: ";
  8373. // T may be a reference type, so we don't use UniversalPrint().
  8374. UniversalPrinter<T>::Print(result_.Peek(), os);
  8375. }
  8376. // Performs the given mock function's default action and returns the
  8377. // result in a new-ed ActionResultHolder.
  8378. template <typename F>
  8379. static ActionResultHolder* PerformDefaultAction(
  8380. const FunctionMocker<F>* func_mocker,
  8381. typename Function<F>::ArgumentTuple&& args,
  8382. const std::string& call_description) {
  8383. return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
  8384. std::move(args), call_description)));
  8385. }
  8386. // Performs the given action and returns the result in a new-ed
  8387. // ActionResultHolder.
  8388. template <typename F>
  8389. static ActionResultHolder* PerformAction(
  8390. const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
  8391. return new ActionResultHolder(
  8392. Wrapper(action.Perform(std::move(args))));
  8393. }
  8394. private:
  8395. typedef ReferenceOrValueWrapper<T> Wrapper;
  8396. explicit ActionResultHolder(Wrapper result)
  8397. : result_(std::move(result)) {
  8398. }
  8399. Wrapper result_;
  8400. GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
  8401. };
  8402. // Specialization for T = void.
  8403. template <>
  8404. class ActionResultHolder<void> : public UntypedActionResultHolderBase {
  8405. public:
  8406. void Unwrap() { }
  8407. void PrintAsActionResult(::std::ostream* /* os */) const override {}
  8408. // Performs the given mock function's default action and returns ownership
  8409. // of an empty ActionResultHolder*.
  8410. template <typename F>
  8411. static ActionResultHolder* PerformDefaultAction(
  8412. const FunctionMocker<F>* func_mocker,
  8413. typename Function<F>::ArgumentTuple&& args,
  8414. const std::string& call_description) {
  8415. func_mocker->PerformDefaultAction(std::move(args), call_description);
  8416. return new ActionResultHolder;
  8417. }
  8418. // Performs the given action and returns ownership of an empty
  8419. // ActionResultHolder*.
  8420. template <typename F>
  8421. static ActionResultHolder* PerformAction(
  8422. const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
  8423. action.Perform(std::move(args));
  8424. return new ActionResultHolder;
  8425. }
  8426. private:
  8427. ActionResultHolder() {}
  8428. GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
  8429. };
  8430. template <typename F>
  8431. class FunctionMocker;
  8432. template <typename R, typename... Args>
  8433. class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
  8434. using F = R(Args...);
  8435. public:
  8436. using Result = R;
  8437. using ArgumentTuple = std::tuple<Args...>;
  8438. using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
  8439. FunctionMocker() {}
  8440. // There is no generally useful and implementable semantics of
  8441. // copying a mock object, so copying a mock is usually a user error.
  8442. // Thus we disallow copying function mockers. If the user really
  8443. // wants to copy a mock object, they should implement their own copy
  8444. // operation, for example:
  8445. //
  8446. // class MockFoo : public Foo {
  8447. // public:
  8448. // // Defines a copy constructor explicitly.
  8449. // MockFoo(const MockFoo& src) {}
  8450. // ...
  8451. // };
  8452. FunctionMocker(const FunctionMocker&) = delete;
  8453. FunctionMocker& operator=(const FunctionMocker&) = delete;
  8454. // The destructor verifies that all expectations on this mock
  8455. // function have been satisfied. If not, it will report Google Test
  8456. // non-fatal failures for the violations.
  8457. ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  8458. MutexLock l(&g_gmock_mutex);
  8459. VerifyAndClearExpectationsLocked();
  8460. Mock::UnregisterLocked(this);
  8461. ClearDefaultActionsLocked();
  8462. }
  8463. // Returns the ON_CALL spec that matches this mock function with the
  8464. // given arguments; returns NULL if no matching ON_CALL is found.
  8465. // L = *
  8466. const OnCallSpec<F>* FindOnCallSpec(
  8467. const ArgumentTuple& args) const {
  8468. for (UntypedOnCallSpecs::const_reverse_iterator it
  8469. = untyped_on_call_specs_.rbegin();
  8470. it != untyped_on_call_specs_.rend(); ++it) {
  8471. const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
  8472. if (spec->Matches(args))
  8473. return spec;
  8474. }
  8475. return nullptr;
  8476. }
  8477. // Performs the default action of this mock function on the given
  8478. // arguments and returns the result. Asserts (or throws if
  8479. // exceptions are enabled) with a helpful call descrption if there
  8480. // is no valid return value. This method doesn't depend on the
  8481. // mutable state of this object, and thus can be called concurrently
  8482. // without locking.
  8483. // L = *
  8484. Result PerformDefaultAction(ArgumentTuple&& args,
  8485. const std::string& call_description) const {
  8486. const OnCallSpec<F>* const spec =
  8487. this->FindOnCallSpec(args);
  8488. if (spec != nullptr) {
  8489. return spec->GetAction().Perform(std::move(args));
  8490. }
  8491. const std::string message =
  8492. call_description +
  8493. "\n The mock function has no default action "
  8494. "set, and its return type has no default value set.";
  8495. #if GTEST_HAS_EXCEPTIONS
  8496. if (!DefaultValue<Result>::Exists()) {
  8497. throw std::runtime_error(message);
  8498. }
  8499. #else
  8500. Assert(DefaultValue<Result>::Exists(), "", -1, message);
  8501. #endif
  8502. return DefaultValue<Result>::Get();
  8503. }
  8504. // Performs the default action with the given arguments and returns
  8505. // the action's result. The call description string will be used in
  8506. // the error message to describe the call in the case the default
  8507. // action fails. The caller is responsible for deleting the result.
  8508. // L = *
  8509. UntypedActionResultHolderBase* UntypedPerformDefaultAction(
  8510. void* untyped_args, // must point to an ArgumentTuple
  8511. const std::string& call_description) const override {
  8512. ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
  8513. return ResultHolder::PerformDefaultAction(this, std::move(*args),
  8514. call_description);
  8515. }
  8516. // Performs the given action with the given arguments and returns
  8517. // the action's result. The caller is responsible for deleting the
  8518. // result.
  8519. // L = *
  8520. UntypedActionResultHolderBase* UntypedPerformAction(
  8521. const void* untyped_action, void* untyped_args) const override {
  8522. // Make a copy of the action before performing it, in case the
  8523. // action deletes the mock object (and thus deletes itself).
  8524. const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
  8525. ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
  8526. return ResultHolder::PerformAction(action, std::move(*args));
  8527. }
  8528. // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
  8529. // clears the ON_CALL()s set on this mock function.
  8530. void ClearDefaultActionsLocked() override
  8531. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  8532. g_gmock_mutex.AssertHeld();
  8533. // Deleting our default actions may trigger other mock objects to be
  8534. // deleted, for example if an action contains a reference counted smart
  8535. // pointer to that mock object, and that is the last reference. So if we
  8536. // delete our actions within the context of the global mutex we may deadlock
  8537. // when this method is called again. Instead, make a copy of the set of
  8538. // actions to delete, clear our set within the mutex, and then delete the
  8539. // actions outside of the mutex.
  8540. UntypedOnCallSpecs specs_to_delete;
  8541. untyped_on_call_specs_.swap(specs_to_delete);
  8542. g_gmock_mutex.Unlock();
  8543. for (UntypedOnCallSpecs::const_iterator it =
  8544. specs_to_delete.begin();
  8545. it != specs_to_delete.end(); ++it) {
  8546. delete static_cast<const OnCallSpec<F>*>(*it);
  8547. }
  8548. // Lock the mutex again, since the caller expects it to be locked when we
  8549. // return.
  8550. g_gmock_mutex.Lock();
  8551. }
  8552. // Returns the result of invoking this mock function with the given
  8553. // arguments. This function can be safely called from multiple
  8554. // threads concurrently.
  8555. Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  8556. ArgumentTuple tuple(std::forward<Args>(args)...);
  8557. std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
  8558. this->UntypedInvokeWith(static_cast<void*>(&tuple))));
  8559. return holder->Unwrap();
  8560. }
  8561. MockSpec<F> With(Matcher<Args>... m) {
  8562. return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
  8563. }
  8564. protected:
  8565. template <typename Function>
  8566. friend class MockSpec;
  8567. typedef ActionResultHolder<Result> ResultHolder;
  8568. // Adds and returns a default action spec for this mock function.
  8569. OnCallSpec<F>& AddNewOnCallSpec(
  8570. const char* file, int line,
  8571. const ArgumentMatcherTuple& m)
  8572. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  8573. Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
  8574. OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
  8575. untyped_on_call_specs_.push_back(on_call_spec);
  8576. return *on_call_spec;
  8577. }
  8578. // Adds and returns an expectation spec for this mock function.
  8579. TypedExpectation<F>& AddNewExpectation(const char* file, int line,
  8580. const std::string& source_text,
  8581. const ArgumentMatcherTuple& m)
  8582. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  8583. Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
  8584. TypedExpectation<F>* const expectation =
  8585. new TypedExpectation<F>(this, file, line, source_text, m);
  8586. const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
  8587. // See the definition of untyped_expectations_ for why access to
  8588. // it is unprotected here.
  8589. untyped_expectations_.push_back(untyped_expectation);
  8590. // Adds this expectation into the implicit sequence if there is one.
  8591. Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
  8592. if (implicit_sequence != nullptr) {
  8593. implicit_sequence->AddExpectation(Expectation(untyped_expectation));
  8594. }
  8595. return *expectation;
  8596. }
  8597. private:
  8598. template <typename Func> friend class TypedExpectation;
  8599. // Some utilities needed for implementing UntypedInvokeWith().
  8600. // Describes what default action will be performed for the given
  8601. // arguments.
  8602. // L = *
  8603. void DescribeDefaultActionTo(const ArgumentTuple& args,
  8604. ::std::ostream* os) const {
  8605. const OnCallSpec<F>* const spec = FindOnCallSpec(args);
  8606. if (spec == nullptr) {
  8607. *os << (std::is_void<Result>::value ? "returning directly.\n"
  8608. : "returning default value.\n");
  8609. } else {
  8610. *os << "taking default action specified at:\n"
  8611. << FormatFileLocation(spec->file(), spec->line()) << "\n";
  8612. }
  8613. }
  8614. // Writes a message that the call is uninteresting (i.e. neither
  8615. // explicitly expected nor explicitly unexpected) to the given
  8616. // ostream.
  8617. void UntypedDescribeUninterestingCall(const void* untyped_args,
  8618. ::std::ostream* os) const override
  8619. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  8620. const ArgumentTuple& args =
  8621. *static_cast<const ArgumentTuple*>(untyped_args);
  8622. *os << "Uninteresting mock function call - ";
  8623. DescribeDefaultActionTo(args, os);
  8624. *os << " Function call: " << Name();
  8625. UniversalPrint(args, os);
  8626. }
  8627. // Returns the expectation that matches the given function arguments
  8628. // (or NULL is there's no match); when a match is found,
  8629. // untyped_action is set to point to the action that should be
  8630. // performed (or NULL if the action is "do default"), and
  8631. // is_excessive is modified to indicate whether the call exceeds the
  8632. // expected number.
  8633. //
  8634. // Critical section: We must find the matching expectation and the
  8635. // corresponding action that needs to be taken in an ATOMIC
  8636. // transaction. Otherwise another thread may call this mock
  8637. // method in the middle and mess up the state.
  8638. //
  8639. // However, performing the action has to be left out of the critical
  8640. // section. The reason is that we have no control on what the
  8641. // action does (it can invoke an arbitrary user function or even a
  8642. // mock function) and excessive locking could cause a dead lock.
  8643. const ExpectationBase* UntypedFindMatchingExpectation(
  8644. const void* untyped_args, const void** untyped_action, bool* is_excessive,
  8645. ::std::ostream* what, ::std::ostream* why) override
  8646. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  8647. const ArgumentTuple& args =
  8648. *static_cast<const ArgumentTuple*>(untyped_args);
  8649. MutexLock l(&g_gmock_mutex);
  8650. TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
  8651. if (exp == nullptr) { // A match wasn't found.
  8652. this->FormatUnexpectedCallMessageLocked(args, what, why);
  8653. return nullptr;
  8654. }
  8655. // This line must be done before calling GetActionForArguments(),
  8656. // which will increment the call count for *exp and thus affect
  8657. // its saturation status.
  8658. *is_excessive = exp->IsSaturated();
  8659. const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
  8660. if (action != nullptr && action->IsDoDefault())
  8661. action = nullptr; // Normalize "do default" to NULL.
  8662. *untyped_action = action;
  8663. return exp;
  8664. }
  8665. // Prints the given function arguments to the ostream.
  8666. void UntypedPrintArgs(const void* untyped_args,
  8667. ::std::ostream* os) const override {
  8668. const ArgumentTuple& args =
  8669. *static_cast<const ArgumentTuple*>(untyped_args);
  8670. UniversalPrint(args, os);
  8671. }
  8672. // Returns the expectation that matches the arguments, or NULL if no
  8673. // expectation matches them.
  8674. TypedExpectation<F>* FindMatchingExpectationLocked(
  8675. const ArgumentTuple& args) const
  8676. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  8677. g_gmock_mutex.AssertHeld();
  8678. // See the definition of untyped_expectations_ for why access to
  8679. // it is unprotected here.
  8680. for (typename UntypedExpectations::const_reverse_iterator it =
  8681. untyped_expectations_.rbegin();
  8682. it != untyped_expectations_.rend(); ++it) {
  8683. TypedExpectation<F>* const exp =
  8684. static_cast<TypedExpectation<F>*>(it->get());
  8685. if (exp->ShouldHandleArguments(args)) {
  8686. return exp;
  8687. }
  8688. }
  8689. return nullptr;
  8690. }
  8691. // Returns a message that the arguments don't match any expectation.
  8692. void FormatUnexpectedCallMessageLocked(
  8693. const ArgumentTuple& args,
  8694. ::std::ostream* os,
  8695. ::std::ostream* why) const
  8696. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  8697. g_gmock_mutex.AssertHeld();
  8698. *os << "\nUnexpected mock function call - ";
  8699. DescribeDefaultActionTo(args, os);
  8700. PrintTriedExpectationsLocked(args, why);
  8701. }
  8702. // Prints a list of expectations that have been tried against the
  8703. // current mock function call.
  8704. void PrintTriedExpectationsLocked(
  8705. const ArgumentTuple& args,
  8706. ::std::ostream* why) const
  8707. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  8708. g_gmock_mutex.AssertHeld();
  8709. const size_t count = untyped_expectations_.size();
  8710. *why << "Google Mock tried the following " << count << " "
  8711. << (count == 1 ? "expectation, but it didn't match" :
  8712. "expectations, but none matched")
  8713. << ":\n";
  8714. for (size_t i = 0; i < count; i++) {
  8715. TypedExpectation<F>* const expectation =
  8716. static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
  8717. *why << "\n";
  8718. expectation->DescribeLocationTo(why);
  8719. if (count > 1) {
  8720. *why << "tried expectation #" << i << ": ";
  8721. }
  8722. *why << expectation->source_text() << "...\n";
  8723. expectation->ExplainMatchResultTo(args, why);
  8724. expectation->DescribeCallCountTo(why);
  8725. }
  8726. }
  8727. }; // class FunctionMocker
  8728. // Reports an uninteresting call (whose description is in msg) in the
  8729. // manner specified by 'reaction'.
  8730. void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
  8731. } // namespace internal
  8732. namespace internal {
  8733. template <typename F>
  8734. class MockFunction;
  8735. template <typename R, typename... Args>
  8736. class MockFunction<R(Args...)> {
  8737. public:
  8738. MockFunction(const MockFunction&) = delete;
  8739. MockFunction& operator=(const MockFunction&) = delete;
  8740. std::function<R(Args...)> AsStdFunction() {
  8741. return [this](Args... args) -> R {
  8742. return this->Call(std::forward<Args>(args)...);
  8743. };
  8744. }
  8745. // Implementation detail: the expansion of the MOCK_METHOD macro.
  8746. R Call(Args... args) {
  8747. mock_.SetOwnerAndName(this, "Call");
  8748. return mock_.Invoke(std::forward<Args>(args)...);
  8749. }
  8750. MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
  8751. mock_.RegisterOwner(this);
  8752. return mock_.With(std::move(m)...);
  8753. }
  8754. MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
  8755. return this->gmock_Call(::testing::A<Args>()...);
  8756. }
  8757. protected:
  8758. MockFunction() = default;
  8759. ~MockFunction() = default;
  8760. private:
  8761. FunctionMocker<R(Args...)> mock_;
  8762. };
  8763. /*
  8764. The SignatureOf<F> struct is a meta-function returning function signature
  8765. corresponding to the provided F argument.
  8766. It makes use of MockFunction easier by allowing it to accept more F arguments
  8767. than just function signatures.
  8768. Specializations provided here cover only a signature type itself and
  8769. std::function. However, if need be it can be easily extended to cover also other
  8770. types (like for example boost::function).
  8771. */
  8772. template <typename F>
  8773. struct SignatureOf;
  8774. template <typename R, typename... Args>
  8775. struct SignatureOf<R(Args...)> {
  8776. using type = R(Args...);
  8777. };
  8778. template <typename F>
  8779. struct SignatureOf<std::function<F>> : SignatureOf<F> {};
  8780. template <typename F>
  8781. using SignatureOfT = typename SignatureOf<F>::type;
  8782. } // namespace internal
  8783. // A MockFunction<F> type has one mock method whose type is
  8784. // internal::SignatureOfT<F>. It is useful when you just want your
  8785. // test code to emit some messages and have Google Mock verify the
  8786. // right messages are sent (and perhaps at the right times). For
  8787. // example, if you are exercising code:
  8788. //
  8789. // Foo(1);
  8790. // Foo(2);
  8791. // Foo(3);
  8792. //
  8793. // and want to verify that Foo(1) and Foo(3) both invoke
  8794. // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
  8795. //
  8796. // TEST(FooTest, InvokesBarCorrectly) {
  8797. // MyMock mock;
  8798. // MockFunction<void(string check_point_name)> check;
  8799. // {
  8800. // InSequence s;
  8801. //
  8802. // EXPECT_CALL(mock, Bar("a"));
  8803. // EXPECT_CALL(check, Call("1"));
  8804. // EXPECT_CALL(check, Call("2"));
  8805. // EXPECT_CALL(mock, Bar("a"));
  8806. // }
  8807. // Foo(1);
  8808. // check.Call("1");
  8809. // Foo(2);
  8810. // check.Call("2");
  8811. // Foo(3);
  8812. // }
  8813. //
  8814. // The expectation spec says that the first Bar("a") must happen
  8815. // before check point "1", the second Bar("a") must happen after check
  8816. // point "2", and nothing should happen between the two check
  8817. // points. The explicit check points make it easy to tell which
  8818. // Bar("a") is called by which call to Foo().
  8819. //
  8820. // MockFunction<F> can also be used to exercise code that accepts
  8821. // std::function<internal::SignatureOfT<F>> callbacks. To do so, use
  8822. // AsStdFunction() method to create std::function proxy forwarding to
  8823. // original object's Call. Example:
  8824. //
  8825. // TEST(FooTest, RunsCallbackWithBarArgument) {
  8826. // MockFunction<int(string)> callback;
  8827. // EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
  8828. // Foo(callback.AsStdFunction());
  8829. // }
  8830. //
  8831. // The internal::SignatureOfT<F> indirection allows to use other types
  8832. // than just function signature type. This is typically useful when
  8833. // providing a mock for a predefined std::function type. Example:
  8834. //
  8835. // using FilterPredicate = std::function<bool(string)>;
  8836. // void MyFilterAlgorithm(FilterPredicate predicate);
  8837. //
  8838. // TEST(FooTest, FilterPredicateAlwaysAccepts) {
  8839. // MockFunction<FilterPredicate> predicateMock;
  8840. // EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));
  8841. // MyFilterAlgorithm(predicateMock.AsStdFunction());
  8842. // }
  8843. template <typename F>
  8844. class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
  8845. using Base = internal::MockFunction<internal::SignatureOfT<F>>;
  8846. public:
  8847. using Base::Base;
  8848. };
  8849. // The style guide prohibits "using" statements in a namespace scope
  8850. // inside a header file. However, the MockSpec class template is
  8851. // meant to be defined in the ::testing namespace. The following line
  8852. // is just a trick for working around a bug in MSVC 8.0, which cannot
  8853. // handle it if we define MockSpec in ::testing.
  8854. using internal::MockSpec;
  8855. // Const(x) is a convenient function for obtaining a const reference
  8856. // to x. This is useful for setting expectations on an overloaded
  8857. // const mock method, e.g.
  8858. //
  8859. // class MockFoo : public FooInterface {
  8860. // public:
  8861. // MOCK_METHOD0(Bar, int());
  8862. // MOCK_CONST_METHOD0(Bar, int&());
  8863. // };
  8864. //
  8865. // MockFoo foo;
  8866. // // Expects a call to non-const MockFoo::Bar().
  8867. // EXPECT_CALL(foo, Bar());
  8868. // // Expects a call to const MockFoo::Bar().
  8869. // EXPECT_CALL(Const(foo), Bar());
  8870. template <typename T>
  8871. inline const T& Const(const T& x) { return x; }
  8872. // Constructs an Expectation object that references and co-owns exp.
  8873. inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
  8874. : expectation_base_(exp.GetHandle().expectation_base()) {}
  8875. } // namespace testing
  8876. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  8877. // Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
  8878. // required to avoid compile errors when the name of the method used in call is
  8879. // a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
  8880. // tests in internal/gmock-spec-builders_test.cc for more details.
  8881. //
  8882. // This macro supports statements both with and without parameter matchers. If
  8883. // the parameter list is omitted, gMock will accept any parameters, which allows
  8884. // tests to be written that don't need to encode the number of method
  8885. // parameter. This technique may only be used for non-overloaded methods.
  8886. //
  8887. // // These are the same:
  8888. // ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
  8889. // ON_CALL(mock, NoArgsMethod).WillByDefault(...);
  8890. //
  8891. // // As are these:
  8892. // ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
  8893. // ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
  8894. //
  8895. // // Can also specify args if you want, of course:
  8896. // ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
  8897. //
  8898. // // Overloads work as long as you specify parameters:
  8899. // ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
  8900. // ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
  8901. //
  8902. // // Oops! Which overload did you want?
  8903. // ON_CALL(mock, OverloadedMethod).WillByDefault(...);
  8904. // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
  8905. //
  8906. // How this works: The mock class uses two overloads of the gmock_Method
  8907. // expectation setter method plus an operator() overload on the MockSpec object.
  8908. // In the matcher list form, the macro expands to:
  8909. //
  8910. // // This statement:
  8911. // ON_CALL(mock, TwoArgsMethod(_, 45))...
  8912. //
  8913. // // ...expands to:
  8914. // mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
  8915. // |-------------v---------------||------------v-------------|
  8916. // invokes first overload swallowed by operator()
  8917. //
  8918. // // ...which is essentially:
  8919. // mock.gmock_TwoArgsMethod(_, 45)...
  8920. //
  8921. // Whereas the form without a matcher list:
  8922. //
  8923. // // This statement:
  8924. // ON_CALL(mock, TwoArgsMethod)...
  8925. //
  8926. // // ...expands to:
  8927. // mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
  8928. // |-----------------------v--------------------------|
  8929. // invokes second overload
  8930. //
  8931. // // ...which is essentially:
  8932. // mock.gmock_TwoArgsMethod(_, _)...
  8933. //
  8934. // The WithoutMatchers() argument is used to disambiguate overloads and to
  8935. // block the caller from accidentally invoking the second overload directly. The
  8936. // second argument is an internal type derived from the method signature. The
  8937. // failure to disambiguate two overloads of this method in the ON_CALL statement
  8938. // is how we block callers from setting expectations on overloaded methods.
  8939. #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
  8940. ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
  8941. nullptr) \
  8942. .Setter(__FILE__, __LINE__, #mock_expr, #call)
  8943. #define ON_CALL(obj, call) \
  8944. GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
  8945. #define EXPECT_CALL(obj, call) \
  8946. GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
  8947. #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
  8948. namespace testing {
  8949. namespace internal {
  8950. template <typename T>
  8951. using identity_t = T;
  8952. template <typename Pattern>
  8953. struct ThisRefAdjuster {
  8954. template <typename T>
  8955. using AdjustT = typename std::conditional<
  8956. std::is_const<typename std::remove_reference<Pattern>::type>::value,
  8957. typename std::conditional<std::is_lvalue_reference<Pattern>::value,
  8958. const T&, const T&&>::type,
  8959. typename std::conditional<std::is_lvalue_reference<Pattern>::value, T&,
  8960. T&&>::type>::type;
  8961. template <typename MockType>
  8962. static AdjustT<MockType> Adjust(const MockType& mock) {
  8963. return static_cast<AdjustT<MockType>>(const_cast<MockType&>(mock));
  8964. }
  8965. };
  8966. } // namespace internal
  8967. // The style guide prohibits "using" statements in a namespace scope
  8968. // inside a header file. However, the FunctionMocker class template
  8969. // is meant to be defined in the ::testing namespace. The following
  8970. // line is just a trick for working around a bug in MSVC 8.0, which
  8971. // cannot handle it if we define FunctionMocker in ::testing.
  8972. using internal::FunctionMocker;
  8973. } // namespace testing
  8974. #define MOCK_METHOD(...) \
  8975. GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__)
  8976. #define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \
  8977. GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
  8978. #define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \
  8979. GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
  8980. #define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \
  8981. GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ())
  8982. #define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \
  8983. GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \
  8984. GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \
  8985. GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
  8986. GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \
  8987. GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
  8988. GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
  8989. GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \
  8990. GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \
  8991. GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \
  8992. GMOCK_INTERNAL_GET_CALLTYPE(_Spec), GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \
  8993. (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)))
  8994. #define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \
  8995. GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
  8996. #define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \
  8997. GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
  8998. #define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \
  8999. GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
  9000. #define GMOCK_INTERNAL_WRONG_ARITY(...) \
  9001. static_assert( \
  9002. false, \
  9003. "MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \
  9004. "_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \
  9005. "enclosed in parentheses. If _Ret is a type with unprotected commas, " \
  9006. "it must also be enclosed in parentheses.")
  9007. #define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \
  9008. static_assert( \
  9009. GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \
  9010. GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.")
  9011. #define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \
  9012. static_assert( \
  9013. std::is_function<__VA_ARGS__>::value, \
  9014. "Signature must be a function type, maybe return type contains " \
  9015. "unprotected comma."); \
  9016. static_assert( \
  9017. ::testing::tuple_size<typename ::testing::internal::Function< \
  9018. __VA_ARGS__>::ArgumentTuple>::value == _N, \
  9019. "This method does not take " GMOCK_PP_STRINGIZE( \
  9020. _N) " arguments. Parenthesize all types with unprotected commas.")
  9021. #define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
  9022. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec)
  9023. #define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \
  9024. _Override, _Final, _NoexceptSpec, \
  9025. _CallType, _RefSpec, _Signature) \
  9026. typename ::testing::internal::Function<GMOCK_PP_REMOVE_PARENS( \
  9027. _Signature)>::Result \
  9028. GMOCK_INTERNAL_EXPAND(_CallType) \
  9029. _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \
  9030. GMOCK_PP_IF(_Constness, const, ) _RefSpec _NoexceptSpec \
  9031. GMOCK_PP_IF(_Override, override, ) GMOCK_PP_IF(_Final, final, ) { \
  9032. GMOCK_MOCKER_(_N, _Constness, _MethodName) \
  9033. .SetOwnerAndName(this, #_MethodName); \
  9034. return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
  9035. .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \
  9036. } \
  9037. ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
  9038. GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \
  9039. GMOCK_PP_IF(_Constness, const, ) _RefSpec { \
  9040. GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \
  9041. return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
  9042. .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \
  9043. } \
  9044. ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
  9045. const ::testing::internal::WithoutMatchers&, \
  9046. GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \
  9047. GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \
  9048. return ::testing::internal::ThisRefAdjuster<GMOCK_PP_IF( \
  9049. _Constness, const, ) int _RefSpec>::Adjust(*this) \
  9050. .gmock_##_MethodName(GMOCK_PP_REPEAT( \
  9051. GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \
  9052. } \
  9053. mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \
  9054. GMOCK_MOCKER_(_N, _Constness, _MethodName)
  9055. #define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__
  9056. // Five Valid modifiers.
  9057. #define GMOCK_INTERNAL_HAS_CONST(_Tuple) \
  9058. GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple))
  9059. #define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \
  9060. GMOCK_PP_HAS_COMMA( \
  9061. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple))
  9062. #define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \
  9063. GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple))
  9064. #define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \
  9065. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple)
  9066. #define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \
  9067. GMOCK_PP_IF( \
  9068. GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \
  9069. _elem, )
  9070. #define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \
  9071. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple)
  9072. #define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \
  9073. GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \
  9074. GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )
  9075. #define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \
  9076. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple)
  9077. #define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \
  9078. static_assert( \
  9079. (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \
  9080. GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \
  9081. GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \
  9082. GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \
  9083. GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \
  9084. GMOCK_INTERNAL_IS_CALLTYPE(_elem)) == 1, \
  9085. GMOCK_PP_STRINGIZE( \
  9086. _elem) " cannot be recognized as a valid specification modifier.");
  9087. // Modifiers implementation.
  9088. #define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \
  9089. GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem)
  9090. #define GMOCK_INTERNAL_DETECT_CONST_I_const ,
  9091. #define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \
  9092. GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem)
  9093. #define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override ,
  9094. #define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \
  9095. GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem)
  9096. #define GMOCK_INTERNAL_DETECT_FINAL_I_final ,
  9097. #define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \
  9098. GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem)
  9099. #define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept ,
  9100. #define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \
  9101. GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem)
  9102. #define GMOCK_INTERNAL_DETECT_REF_I_ref ,
  9103. #define GMOCK_INTERNAL_UNPACK_ref(x) x
  9104. #define GMOCK_INTERNAL_GET_CALLTYPE_IMPL(_i, _, _elem) \
  9105. GMOCK_PP_IF(GMOCK_INTERNAL_IS_CALLTYPE(_elem), \
  9106. GMOCK_INTERNAL_GET_VALUE_CALLTYPE, GMOCK_PP_EMPTY) \
  9107. (_elem)
  9108. // TODO(iserna): GMOCK_INTERNAL_IS_CALLTYPE and
  9109. // GMOCK_INTERNAL_GET_VALUE_CALLTYPE needed more expansions to work on windows
  9110. // maybe they can be simplified somehow.
  9111. #define GMOCK_INTERNAL_IS_CALLTYPE(_arg) \
  9112. GMOCK_INTERNAL_IS_CALLTYPE_I( \
  9113. GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
  9114. #define GMOCK_INTERNAL_IS_CALLTYPE_I(_arg) GMOCK_PP_IS_ENCLOSED_PARENS(_arg)
  9115. #define GMOCK_INTERNAL_GET_VALUE_CALLTYPE(_arg) \
  9116. GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I( \
  9117. GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
  9118. #define GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I(_arg) \
  9119. GMOCK_PP_IDENTITY _arg
  9120. #define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype
  9121. // Note: The use of `identity_t` here allows _Ret to represent return types that
  9122. // would normally need to be specified in a different way. For example, a method
  9123. // returning a function pointer must be written as
  9124. //
  9125. // fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...)
  9126. //
  9127. // But we only support placing the return type at the beginning. To handle this,
  9128. // we wrap all calls in identity_t, so that a declaration will be expanded to
  9129. //
  9130. // identity_t<fn_ptr_return_t (*)(fn_ptr_args_t...)> method(method_args_t...)
  9131. //
  9132. // This allows us to work around the syntactic oddities of function/method
  9133. // types.
  9134. #define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \
  9135. ::testing::internal::identity_t<GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), \
  9136. GMOCK_PP_REMOVE_PARENS, \
  9137. GMOCK_PP_IDENTITY)(_Ret)>( \
  9138. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args))
  9139. #define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \
  9140. GMOCK_PP_COMMA_IF(_i) \
  9141. GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \
  9142. GMOCK_PP_IDENTITY) \
  9143. (_elem)
  9144. #define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \
  9145. GMOCK_PP_COMMA_IF(_i) \
  9146. GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
  9147. gmock_a##_i
  9148. #define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \
  9149. GMOCK_PP_COMMA_IF(_i) \
  9150. ::std::forward<GMOCK_INTERNAL_ARG_O( \
  9151. _i, GMOCK_PP_REMOVE_PARENS(_Signature))>(gmock_a##_i)
  9152. #define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \
  9153. GMOCK_PP_COMMA_IF(_i) \
  9154. GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
  9155. gmock_a##_i
  9156. #define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \
  9157. GMOCK_PP_COMMA_IF(_i) \
  9158. gmock_a##_i
  9159. #define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \
  9160. GMOCK_PP_COMMA_IF(_i) \
  9161. ::testing::A<GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature))>()
  9162. #define GMOCK_INTERNAL_ARG_O(_i, ...) \
  9163. typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type
  9164. #define GMOCK_INTERNAL_MATCHER_O(_i, ...) \
  9165. const ::testing::Matcher<typename ::testing::internal::Function< \
  9166. __VA_ARGS__>::template Arg<_i>::type>&
  9167. #define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__)
  9168. #define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__)
  9169. #define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__)
  9170. #define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__)
  9171. #define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__)
  9172. #define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__)
  9173. #define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__)
  9174. #define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__)
  9175. #define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__)
  9176. #define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__)
  9177. #define MOCK_METHOD10(m, ...) \
  9178. GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__)
  9179. #define MOCK_CONST_METHOD0(m, ...) \
  9180. GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__)
  9181. #define MOCK_CONST_METHOD1(m, ...) \
  9182. GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__)
  9183. #define MOCK_CONST_METHOD2(m, ...) \
  9184. GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__)
  9185. #define MOCK_CONST_METHOD3(m, ...) \
  9186. GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__)
  9187. #define MOCK_CONST_METHOD4(m, ...) \
  9188. GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__)
  9189. #define MOCK_CONST_METHOD5(m, ...) \
  9190. GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__)
  9191. #define MOCK_CONST_METHOD6(m, ...) \
  9192. GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__)
  9193. #define MOCK_CONST_METHOD7(m, ...) \
  9194. GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__)
  9195. #define MOCK_CONST_METHOD8(m, ...) \
  9196. GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__)
  9197. #define MOCK_CONST_METHOD9(m, ...) \
  9198. GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__)
  9199. #define MOCK_CONST_METHOD10(m, ...) \
  9200. GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__)
  9201. #define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__)
  9202. #define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__)
  9203. #define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__)
  9204. #define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__)
  9205. #define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__)
  9206. #define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__)
  9207. #define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__)
  9208. #define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__)
  9209. #define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__)
  9210. #define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__)
  9211. #define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__)
  9212. #define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__)
  9213. #define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__)
  9214. #define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__)
  9215. #define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__)
  9216. #define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__)
  9217. #define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__)
  9218. #define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__)
  9219. #define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__)
  9220. #define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__)
  9221. #define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__)
  9222. #define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__)
  9223. #define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
  9224. GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__)
  9225. #define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
  9226. GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__)
  9227. #define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
  9228. GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__)
  9229. #define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
  9230. GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__)
  9231. #define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
  9232. GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__)
  9233. #define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
  9234. GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__)
  9235. #define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
  9236. GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__)
  9237. #define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
  9238. GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__)
  9239. #define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
  9240. GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__)
  9241. #define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
  9242. GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__)
  9243. #define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
  9244. GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__)
  9245. #define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
  9246. GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__)
  9247. #define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
  9248. GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__)
  9249. #define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
  9250. GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__)
  9251. #define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
  9252. GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__)
  9253. #define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
  9254. GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__)
  9255. #define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
  9256. GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__)
  9257. #define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
  9258. GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__)
  9259. #define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
  9260. GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__)
  9261. #define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
  9262. GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__)
  9263. #define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
  9264. GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__)
  9265. #define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
  9266. GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__)
  9267. #define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
  9268. MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9269. #define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
  9270. MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9271. #define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
  9272. MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9273. #define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
  9274. MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9275. #define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
  9276. MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9277. #define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
  9278. MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9279. #define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
  9280. MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9281. #define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
  9282. MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9283. #define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
  9284. MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9285. #define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
  9286. MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9287. #define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
  9288. MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9289. #define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
  9290. MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9291. #define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
  9292. MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9293. #define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
  9294. MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9295. #define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
  9296. MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9297. #define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
  9298. MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9299. #define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
  9300. MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9301. #define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
  9302. MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9303. #define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
  9304. MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9305. #define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
  9306. MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9307. #define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
  9308. MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9309. #define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
  9310. MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
  9311. #define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \
  9312. GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
  9313. args_num, ::testing::internal::identity_t<__VA_ARGS__>); \
  9314. GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
  9315. args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \
  9316. (::testing::internal::identity_t<__VA_ARGS__>))
  9317. #define GMOCK_MOCKER_(arity, constness, Method) \
  9318. GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
  9319. #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_
  9320. // Copyright 2007, Google Inc.
  9321. // All rights reserved.
  9322. //
  9323. // Redistribution and use in source and binary forms, with or without
  9324. // modification, are permitted provided that the following conditions are
  9325. // met:
  9326. //
  9327. // * Redistributions of source code must retain the above copyright
  9328. // notice, this list of conditions and the following disclaimer.
  9329. // * Redistributions in binary form must reproduce the above
  9330. // copyright notice, this list of conditions and the following disclaimer
  9331. // in the documentation and/or other materials provided with the
  9332. // distribution.
  9333. // * Neither the name of Google Inc. nor the names of its
  9334. // contributors may be used to endorse or promote products derived from
  9335. // this software without specific prior written permission.
  9336. //
  9337. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  9338. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  9339. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  9340. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9341. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  9342. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9343. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  9344. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9345. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  9346. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  9347. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9348. // Google Mock - a framework for writing C++ mock classes.
  9349. //
  9350. // This file implements some commonly used variadic actions.
  9351. // GOOGLETEST_CM0002 DO NOT DELETE
  9352. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
  9353. #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
  9354. #include <memory>
  9355. #include <utility>
  9356. // Include any custom callback actions added by the local installation.
  9357. // GOOGLETEST_CM0002 DO NOT DELETE
  9358. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
  9359. #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
  9360. #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
  9361. // Sometimes you want to give an action explicit template parameters
  9362. // that cannot be inferred from its value parameters. ACTION() and
  9363. // ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that
  9364. // and can be viewed as an extension to ACTION() and ACTION_P*().
  9365. //
  9366. // The syntax:
  9367. //
  9368. // ACTION_TEMPLATE(ActionName,
  9369. // HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
  9370. // AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
  9371. //
  9372. // defines an action template that takes m explicit template
  9373. // parameters and n value parameters. name_i is the name of the i-th
  9374. // template parameter, and kind_i specifies whether it's a typename,
  9375. // an integral constant, or a template. p_i is the name of the i-th
  9376. // value parameter.
  9377. //
  9378. // Example:
  9379. //
  9380. // // DuplicateArg<k, T>(output) converts the k-th argument of the mock
  9381. // // function to type T and copies it to *output.
  9382. // ACTION_TEMPLATE(DuplicateArg,
  9383. // HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
  9384. // AND_1_VALUE_PARAMS(output)) {
  9385. // *output = T(::std::get<k>(args));
  9386. // }
  9387. // ...
  9388. // int n;
  9389. // EXPECT_CALL(mock, Foo(_, _))
  9390. // .WillOnce(DuplicateArg<1, unsigned char>(&n));
  9391. //
  9392. // To create an instance of an action template, write:
  9393. //
  9394. // ActionName<t1, ..., t_m>(v1, ..., v_n)
  9395. //
  9396. // where the ts are the template arguments and the vs are the value
  9397. // arguments. The value argument types are inferred by the compiler.
  9398. // If you want to explicitly specify the value argument types, you can
  9399. // provide additional template arguments:
  9400. //
  9401. // ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
  9402. //
  9403. // where u_i is the desired type of v_i.
  9404. //
  9405. // ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the
  9406. // number of value parameters, but not on the number of template
  9407. // parameters. Without the restriction, the meaning of the following
  9408. // is unclear:
  9409. //
  9410. // OverloadedAction<int, bool>(x);
  9411. //
  9412. // Are we using a single-template-parameter action where 'bool' refers
  9413. // to the type of x, or are we using a two-template-parameter action
  9414. // where the compiler is asked to infer the type of x?
  9415. //
  9416. // Implementation notes:
  9417. //
  9418. // GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and
  9419. // GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for
  9420. // implementing ACTION_TEMPLATE. The main trick we use is to create
  9421. // new macro invocations when expanding a macro. For example, we have
  9422. //
  9423. // #define ACTION_TEMPLATE(name, template_params, value_params)
  9424. // ... GMOCK_INTERNAL_DECL_##template_params ...
  9425. //
  9426. // which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)
  9427. // to expand to
  9428. //
  9429. // ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...
  9430. //
  9431. // Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the
  9432. // preprocessor will continue to expand it to
  9433. //
  9434. // ... typename T ...
  9435. //
  9436. // This technique conforms to the C++ standard and is portable. It
  9437. // allows us to implement action templates using O(N) code, where N is
  9438. // the maximum number of template/value parameters supported. Without
  9439. // using it, we'd have to devote O(N^2) amount of code to implement all
  9440. // combinations of m and n.
  9441. // Declares the template parameters.
  9442. #define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0
  9443. #define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
  9444. name1) kind0 name0, kind1 name1
  9445. #define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9446. kind2, name2) kind0 name0, kind1 name1, kind2 name2
  9447. #define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9448. kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \
  9449. kind3 name3
  9450. #define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9451. kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \
  9452. kind2 name2, kind3 name3, kind4 name4
  9453. #define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9454. kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \
  9455. kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
  9456. #define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9457. kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
  9458. name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
  9459. kind5 name5, kind6 name6
  9460. #define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9461. kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
  9462. kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \
  9463. kind4 name4, kind5 name5, kind6 name6, kind7 name7
  9464. #define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9465. kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
  9466. kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \
  9467. kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \
  9468. kind8 name8
  9469. #define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
  9470. name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
  9471. name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \
  9472. kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \
  9473. kind6 name6, kind7 name7, kind8 name8, kind9 name9
  9474. // Lists the template parameters.
  9475. #define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0
  9476. #define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
  9477. name1) name0, name1
  9478. #define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9479. kind2, name2) name0, name1, name2
  9480. #define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9481. kind2, name2, kind3, name3) name0, name1, name2, name3
  9482. #define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9483. kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \
  9484. name4
  9485. #define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9486. kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \
  9487. name2, name3, name4, name5
  9488. #define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9489. kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
  9490. name6) name0, name1, name2, name3, name4, name5, name6
  9491. #define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9492. kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
  9493. kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7
  9494. #define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
  9495. kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
  9496. kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \
  9497. name6, name7, name8
  9498. #define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
  9499. name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
  9500. name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \
  9501. name3, name4, name5, name6, name7, name8, name9
  9502. // Declares the types of value parameters.
  9503. #define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS()
  9504. #define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type
  9505. #define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \
  9506. typename p0##_type, typename p1##_type
  9507. #define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \
  9508. typename p0##_type, typename p1##_type, typename p2##_type
  9509. #define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
  9510. typename p0##_type, typename p1##_type, typename p2##_type, \
  9511. typename p3##_type
  9512. #define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
  9513. typename p0##_type, typename p1##_type, typename p2##_type, \
  9514. typename p3##_type, typename p4##_type
  9515. #define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
  9516. typename p0##_type, typename p1##_type, typename p2##_type, \
  9517. typename p3##_type, typename p4##_type, typename p5##_type
  9518. #define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
  9519. p6) , typename p0##_type, typename p1##_type, typename p2##_type, \
  9520. typename p3##_type, typename p4##_type, typename p5##_type, \
  9521. typename p6##_type
  9522. #define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
  9523. p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \
  9524. typename p3##_type, typename p4##_type, typename p5##_type, \
  9525. typename p6##_type, typename p7##_type
  9526. #define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
  9527. p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \
  9528. typename p3##_type, typename p4##_type, typename p5##_type, \
  9529. typename p6##_type, typename p7##_type, typename p8##_type
  9530. #define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
  9531. p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \
  9532. typename p2##_type, typename p3##_type, typename p4##_type, \
  9533. typename p5##_type, typename p6##_type, typename p7##_type, \
  9534. typename p8##_type, typename p9##_type
  9535. // Initializes the value parameters.
  9536. #define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\
  9537. ()
  9538. #define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\
  9539. (p0##_type gmock_p0) : p0(::std::move(gmock_p0))
  9540. #define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\
  9541. (p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \
  9542. p1(::std::move(gmock_p1))
  9543. #define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\
  9544. (p0##_type gmock_p0, p1##_type gmock_p1, \
  9545. p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \
  9546. p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2))
  9547. #define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\
  9548. (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
  9549. p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \
  9550. p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
  9551. p3(::std::move(gmock_p3))
  9552. #define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\
  9553. (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
  9554. p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \
  9555. p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
  9556. p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4))
  9557. #define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\
  9558. (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
  9559. p3##_type gmock_p3, p4##_type gmock_p4, \
  9560. p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \
  9561. p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
  9562. p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
  9563. p5(::std::move(gmock_p5))
  9564. #define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\
  9565. (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
  9566. p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
  9567. p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \
  9568. p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
  9569. p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
  9570. p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6))
  9571. #define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\
  9572. (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
  9573. p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
  9574. p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \
  9575. p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
  9576. p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
  9577. p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
  9578. p7(::std::move(gmock_p7))
  9579. #define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9580. p7, p8)\
  9581. (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
  9582. p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
  9583. p6##_type gmock_p6, p7##_type gmock_p7, \
  9584. p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \
  9585. p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
  9586. p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
  9587. p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
  9588. p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8))
  9589. #define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9590. p7, p8, p9)\
  9591. (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
  9592. p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
  9593. p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
  9594. p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \
  9595. p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
  9596. p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
  9597. p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
  9598. p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \
  9599. p9(::std::move(gmock_p9))
  9600. // Defines the copy constructor
  9601. #define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \
  9602. {} // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134
  9603. #define GMOCK_INTERNAL_DEFN_COPY_AND_1_VALUE_PARAMS(...) = default;
  9604. #define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default;
  9605. #define GMOCK_INTERNAL_DEFN_COPY_AND_3_VALUE_PARAMS(...) = default;
  9606. #define GMOCK_INTERNAL_DEFN_COPY_AND_4_VALUE_PARAMS(...) = default;
  9607. #define GMOCK_INTERNAL_DEFN_COPY_AND_5_VALUE_PARAMS(...) = default;
  9608. #define GMOCK_INTERNAL_DEFN_COPY_AND_6_VALUE_PARAMS(...) = default;
  9609. #define GMOCK_INTERNAL_DEFN_COPY_AND_7_VALUE_PARAMS(...) = default;
  9610. #define GMOCK_INTERNAL_DEFN_COPY_AND_8_VALUE_PARAMS(...) = default;
  9611. #define GMOCK_INTERNAL_DEFN_COPY_AND_9_VALUE_PARAMS(...) = default;
  9612. #define GMOCK_INTERNAL_DEFN_COPY_AND_10_VALUE_PARAMS(...) = default;
  9613. // Declares the fields for storing the value parameters.
  9614. #define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()
  9615. #define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0;
  9616. #define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \
  9617. p1##_type p1;
  9618. #define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \
  9619. p1##_type p1; p2##_type p2;
  9620. #define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \
  9621. p1##_type p1; p2##_type p2; p3##_type p3;
  9622. #define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
  9623. p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4;
  9624. #define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
  9625. p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
  9626. p5##_type p5;
  9627. #define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
  9628. p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
  9629. p5##_type p5; p6##_type p6;
  9630. #define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9631. p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
  9632. p5##_type p5; p6##_type p6; p7##_type p7;
  9633. #define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9634. p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
  9635. p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8;
  9636. #define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9637. p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
  9638. p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \
  9639. p9##_type p9;
  9640. // Lists the value parameters.
  9641. #define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()
  9642. #define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0
  9643. #define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1
  9644. #define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2
  9645. #define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3
  9646. #define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \
  9647. p2, p3, p4
  9648. #define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \
  9649. p1, p2, p3, p4, p5
  9650. #define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
  9651. p6) p0, p1, p2, p3, p4, p5, p6
  9652. #define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9653. p7) p0, p1, p2, p3, p4, p5, p6, p7
  9654. #define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9655. p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8
  9656. #define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9657. p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
  9658. // Lists the value parameter types.
  9659. #define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS()
  9660. #define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type
  9661. #define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \
  9662. p1##_type
  9663. #define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \
  9664. p1##_type, p2##_type
  9665. #define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
  9666. p0##_type, p1##_type, p2##_type, p3##_type
  9667. #define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
  9668. p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
  9669. #define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
  9670. p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
  9671. #define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
  9672. p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
  9673. p6##_type
  9674. #define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
  9675. p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
  9676. p5##_type, p6##_type, p7##_type
  9677. #define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
  9678. p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
  9679. p5##_type, p6##_type, p7##_type, p8##_type
  9680. #define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
  9681. p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
  9682. p5##_type, p6##_type, p7##_type, p8##_type, p9##_type
  9683. // Declares the value parameters.
  9684. #define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS()
  9685. #define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0
  9686. #define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \
  9687. p1##_type p1
  9688. #define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \
  9689. p1##_type p1, p2##_type p2
  9690. #define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \
  9691. p1##_type p1, p2##_type p2, p3##_type p3
  9692. #define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
  9693. p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
  9694. #define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
  9695. p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
  9696. p5##_type p5
  9697. #define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
  9698. p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
  9699. p5##_type p5, p6##_type p6
  9700. #define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9701. p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
  9702. p5##_type p5, p6##_type p6, p7##_type p7
  9703. #define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9704. p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
  9705. p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
  9706. #define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9707. p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
  9708. p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
  9709. p9##_type p9
  9710. // The suffix of the class template implementing the action template.
  9711. #define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
  9712. #define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P
  9713. #define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2
  9714. #define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3
  9715. #define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4
  9716. #define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5
  9717. #define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6
  9718. #define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7
  9719. #define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9720. p7) P8
  9721. #define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9722. p7, p8) P9
  9723. #define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
  9724. p7, p8, p9) P10
  9725. // The name of the class template implementing the action template.
  9726. #define GMOCK_ACTION_CLASS_(name, value_params)\
  9727. GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
  9728. #define ACTION_TEMPLATE(name, template_params, value_params) \
  9729. template <GMOCK_INTERNAL_DECL_##template_params \
  9730. GMOCK_INTERNAL_DECL_TYPE_##value_params> \
  9731. class GMOCK_ACTION_CLASS_(name, value_params) { \
  9732. public: \
  9733. explicit GMOCK_ACTION_CLASS_(name, value_params)( \
  9734. GMOCK_INTERNAL_DECL_##value_params) \
  9735. GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
  9736. = default; , \
  9737. : impl_(std::make_shared<gmock_Impl>( \
  9738. GMOCK_INTERNAL_LIST_##value_params)) { }) \
  9739. GMOCK_ACTION_CLASS_(name, value_params)( \
  9740. const GMOCK_ACTION_CLASS_(name, value_params)&) noexcept \
  9741. GMOCK_INTERNAL_DEFN_COPY_##value_params \
  9742. GMOCK_ACTION_CLASS_(name, value_params)( \
  9743. GMOCK_ACTION_CLASS_(name, value_params)&&) noexcept \
  9744. GMOCK_INTERNAL_DEFN_COPY_##value_params \
  9745. template <typename F> \
  9746. operator ::testing::Action<F>() const { \
  9747. return GMOCK_PP_IF( \
  9748. GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
  9749. (::testing::internal::MakeAction<F, gmock_Impl>()), \
  9750. (::testing::internal::MakeAction<F>(impl_))); \
  9751. } \
  9752. private: \
  9753. class gmock_Impl { \
  9754. public: \
  9755. explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {} \
  9756. template <typename function_type, typename return_type, \
  9757. typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  9758. return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
  9759. GMOCK_INTERNAL_DEFN_##value_params \
  9760. }; \
  9761. GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
  9762. , std::shared_ptr<const gmock_Impl> impl_;) \
  9763. }; \
  9764. template <GMOCK_INTERNAL_DECL_##template_params \
  9765. GMOCK_INTERNAL_DECL_TYPE_##value_params> \
  9766. GMOCK_ACTION_CLASS_(name, value_params)< \
  9767. GMOCK_INTERNAL_LIST_##template_params \
  9768. GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
  9769. GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \
  9770. template <GMOCK_INTERNAL_DECL_##template_params \
  9771. GMOCK_INTERNAL_DECL_TYPE_##value_params> \
  9772. inline GMOCK_ACTION_CLASS_(name, value_params)< \
  9773. GMOCK_INTERNAL_LIST_##template_params \
  9774. GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
  9775. GMOCK_INTERNAL_DECL_##value_params) { \
  9776. return GMOCK_ACTION_CLASS_(name, value_params)< \
  9777. GMOCK_INTERNAL_LIST_##template_params \
  9778. GMOCK_INTERNAL_LIST_TYPE_##value_params>( \
  9779. GMOCK_INTERNAL_LIST_##value_params); \
  9780. } \
  9781. template <GMOCK_INTERNAL_DECL_##template_params \
  9782. GMOCK_INTERNAL_DECL_TYPE_##value_params> \
  9783. template <typename function_type, typename return_type, typename args_type, \
  9784. GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  9785. return_type GMOCK_ACTION_CLASS_(name, value_params)< \
  9786. GMOCK_INTERNAL_LIST_##template_params \
  9787. GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::gmock_PerformImpl( \
  9788. GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
  9789. namespace testing {
  9790. // The ACTION*() macros trigger warning C4100 (unreferenced formal
  9791. // parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
  9792. // the macro definition, as the warnings are generated when the macro
  9793. // is expanded and macro expansion cannot contain #pragma. Therefore
  9794. // we suppress them here.
  9795. #ifdef _MSC_VER
  9796. # pragma warning(push)
  9797. # pragma warning(disable:4100)
  9798. #endif
  9799. namespace internal {
  9800. // internal::InvokeArgument - a helper for InvokeArgument action.
  9801. // The basic overloads are provided here for generic functors.
  9802. // Overloads for other custom-callables are provided in the
  9803. // internal/custom/gmock-generated-actions.h header.
  9804. template <typename F, typename... Args>
  9805. auto InvokeArgument(F f, Args... args) -> decltype(f(args...)) {
  9806. return f(args...);
  9807. }
  9808. template <std::size_t index, typename... Params>
  9809. struct InvokeArgumentAction {
  9810. template <typename... Args>
  9811. auto operator()(Args&&... args) const -> decltype(internal::InvokeArgument(
  9812. std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)),
  9813. std::declval<const Params&>()...)) {
  9814. internal::FlatTuple<Args&&...> args_tuple(FlatTupleConstructTag{},
  9815. std::forward<Args>(args)...);
  9816. return params.Apply([&](const Params&... unpacked_params) {
  9817. auto&& callable = args_tuple.template Get<index>();
  9818. return internal::InvokeArgument(
  9819. std::forward<decltype(callable)>(callable), unpacked_params...);
  9820. });
  9821. }
  9822. internal::FlatTuple<Params...> params;
  9823. };
  9824. } // namespace internal
  9825. // The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th
  9826. // (0-based) argument, which must be a k-ary callable, of the mock
  9827. // function, with arguments a1, a2, ..., a_k.
  9828. //
  9829. // Notes:
  9830. //
  9831. // 1. The arguments are passed by value by default. If you need to
  9832. // pass an argument by reference, wrap it inside std::ref(). For
  9833. // example,
  9834. //
  9835. // InvokeArgument<1>(5, string("Hello"), std::ref(foo))
  9836. //
  9837. // passes 5 and string("Hello") by value, and passes foo by
  9838. // reference.
  9839. //
  9840. // 2. If the callable takes an argument by reference but std::ref() is
  9841. // not used, it will receive the reference to a copy of the value,
  9842. // instead of the original value. For example, when the 0-th
  9843. // argument of the mock function takes a const string&, the action
  9844. //
  9845. // InvokeArgument<0>(string("Hello"))
  9846. //
  9847. // makes a copy of the temporary string("Hello") object and passes a
  9848. // reference of the copy, instead of the original temporary object,
  9849. // to the callable. This makes it easy for a user to define an
  9850. // InvokeArgument action from temporary values and have it performed
  9851. // later.
  9852. template <std::size_t index, typename... Params>
  9853. internal::InvokeArgumentAction<index, typename std::decay<Params>::type...>
  9854. InvokeArgument(Params&&... params) {
  9855. return {internal::FlatTuple<typename std::decay<Params>::type...>(
  9856. internal::FlatTupleConstructTag{}, std::forward<Params>(params)...)};
  9857. }
  9858. #ifdef _MSC_VER
  9859. # pragma warning(pop)
  9860. #endif
  9861. } // namespace testing
  9862. #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
  9863. // Copyright 2013, Google Inc.
  9864. // All rights reserved.
  9865. //
  9866. // Redistribution and use in source and binary forms, with or without
  9867. // modification, are permitted provided that the following conditions are
  9868. // met:
  9869. //
  9870. // * Redistributions of source code must retain the above copyright
  9871. // notice, this list of conditions and the following disclaimer.
  9872. // * Redistributions in binary form must reproduce the above
  9873. // copyright notice, this list of conditions and the following disclaimer
  9874. // in the documentation and/or other materials provided with the
  9875. // distribution.
  9876. // * Neither the name of Google Inc. nor the names of its
  9877. // contributors may be used to endorse or promote products derived from
  9878. // this software without specific prior written permission.
  9879. //
  9880. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  9881. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  9882. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  9883. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9884. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  9885. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9886. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  9887. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9888. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  9889. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  9890. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9891. // Google Mock - a framework for writing C++ mock classes.
  9892. //
  9893. // This file implements some matchers that depend on gmock-matchers.h.
  9894. //
  9895. // Note that tests are implemented in gmock-matchers_test.cc rather than
  9896. // gmock-more-matchers-test.cc.
  9897. // GOOGLETEST_CM0002 DO NOT DELETE
  9898. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
  9899. #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
  9900. namespace testing {
  9901. // Silence C4100 (unreferenced formal
  9902. // parameter) for MSVC
  9903. #ifdef _MSC_VER
  9904. # pragma warning(push)
  9905. # pragma warning(disable:4100)
  9906. #if (_MSC_VER == 1900)
  9907. // and silence C4800 (C4800: 'int *const ': forcing value
  9908. // to bool 'true' or 'false') for MSVC 14
  9909. # pragma warning(disable:4800)
  9910. #endif
  9911. #endif
  9912. // Defines a matcher that matches an empty container. The container must
  9913. // support both size() and empty(), which all STL-like containers provide.
  9914. MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") {
  9915. if (arg.empty()) {
  9916. return true;
  9917. }
  9918. *result_listener << "whose size is " << arg.size();
  9919. return false;
  9920. }
  9921. // Define a matcher that matches a value that evaluates in boolean
  9922. // context to true. Useful for types that define "explicit operator
  9923. // bool" operators and so can't be compared for equality with true
  9924. // and false.
  9925. MATCHER(IsTrue, negation ? "is false" : "is true") {
  9926. return static_cast<bool>(arg);
  9927. }
  9928. // Define a matcher that matches a value that evaluates in boolean
  9929. // context to false. Useful for types that define "explicit operator
  9930. // bool" operators and so can't be compared for equality with true
  9931. // and false.
  9932. MATCHER(IsFalse, negation ? "is true" : "is false") {
  9933. return !static_cast<bool>(arg);
  9934. }
  9935. #ifdef _MSC_VER
  9936. # pragma warning(pop)
  9937. #endif
  9938. } // namespace testing
  9939. #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
  9940. // Copyright 2008, Google Inc.
  9941. // All rights reserved.
  9942. //
  9943. // Redistribution and use in source and binary forms, with or without
  9944. // modification, are permitted provided that the following conditions are
  9945. // met:
  9946. //
  9947. // * Redistributions of source code must retain the above copyright
  9948. // notice, this list of conditions and the following disclaimer.
  9949. // * Redistributions in binary form must reproduce the above
  9950. // copyright notice, this list of conditions and the following disclaimer
  9951. // in the documentation and/or other materials provided with the
  9952. // distribution.
  9953. // * Neither the name of Google Inc. nor the names of its
  9954. // contributors may be used to endorse or promote products derived from
  9955. // this software without specific prior written permission.
  9956. //
  9957. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  9958. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  9959. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  9960. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9961. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  9962. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9963. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  9964. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9965. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  9966. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  9967. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9968. // Implements class templates NiceMock, NaggyMock, and StrictMock.
  9969. //
  9970. // Given a mock class MockFoo that is created using Google Mock,
  9971. // NiceMock<MockFoo> is a subclass of MockFoo that allows
  9972. // uninteresting calls (i.e. calls to mock methods that have no
  9973. // EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo
  9974. // that prints a warning when an uninteresting call occurs, and
  9975. // StrictMock<MockFoo> is a subclass of MockFoo that treats all
  9976. // uninteresting calls as errors.
  9977. //
  9978. // Currently a mock is naggy by default, so MockFoo and
  9979. // NaggyMock<MockFoo> behave like the same. However, we will soon
  9980. // switch the default behavior of mocks to be nice, as that in general
  9981. // leads to more maintainable tests. When that happens, MockFoo will
  9982. // stop behaving like NaggyMock<MockFoo> and start behaving like
  9983. // NiceMock<MockFoo>.
  9984. //
  9985. // NiceMock, NaggyMock, and StrictMock "inherit" the constructors of
  9986. // their respective base class. Therefore you can write
  9987. // NiceMock<MockFoo>(5, "a") to construct a nice mock where MockFoo
  9988. // has a constructor that accepts (int, const char*), for example.
  9989. //
  9990. // A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>,
  9991. // and StrictMock<MockFoo> only works for mock methods defined using
  9992. // the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class.
  9993. // If a mock method is defined in a base class of MockFoo, the "nice"
  9994. // or "strict" modifier may not affect it, depending on the compiler.
  9995. // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT
  9996. // supported.
  9997. // GOOGLETEST_CM0002 DO NOT DELETE
  9998. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
  9999. #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
  10000. #include <type_traits>
  10001. namespace testing {
  10002. template <class MockClass>
  10003. class NiceMock;
  10004. template <class MockClass>
  10005. class NaggyMock;
  10006. template <class MockClass>
  10007. class StrictMock;
  10008. namespace internal {
  10009. template <typename T>
  10010. std::true_type StrictnessModifierProbe(const NiceMock<T>&);
  10011. template <typename T>
  10012. std::true_type StrictnessModifierProbe(const NaggyMock<T>&);
  10013. template <typename T>
  10014. std::true_type StrictnessModifierProbe(const StrictMock<T>&);
  10015. std::false_type StrictnessModifierProbe(...);
  10016. template <typename T>
  10017. constexpr bool HasStrictnessModifier() {
  10018. return decltype(StrictnessModifierProbe(std::declval<const T&>()))::value;
  10019. }
  10020. // Base classes that register and deregister with testing::Mock to alter the
  10021. // default behavior around uninteresting calls. Inheriting from one of these
  10022. // classes first and then MockClass ensures the MockClass constructor is run
  10023. // after registration, and that the MockClass destructor runs before
  10024. // deregistration. This guarantees that MockClass's constructor and destructor
  10025. // run with the same level of strictness as its instance methods.
  10026. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW && \
  10027. (defined(_MSC_VER) || defined(__clang__))
  10028. // We need to mark these classes with this declspec to ensure that
  10029. // the empty base class optimization is performed.
  10030. #define GTEST_INTERNAL_EMPTY_BASE_CLASS __declspec(empty_bases)
  10031. #else
  10032. #define GTEST_INTERNAL_EMPTY_BASE_CLASS
  10033. #endif
  10034. template <typename Base>
  10035. class NiceMockImpl {
  10036. public:
  10037. NiceMockImpl() { ::testing::Mock::AllowUninterestingCalls(this); }
  10038. ~NiceMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
  10039. };
  10040. template <typename Base>
  10041. class NaggyMockImpl {
  10042. public:
  10043. NaggyMockImpl() { ::testing::Mock::WarnUninterestingCalls(this); }
  10044. ~NaggyMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
  10045. };
  10046. template <typename Base>
  10047. class StrictMockImpl {
  10048. public:
  10049. StrictMockImpl() { ::testing::Mock::FailUninterestingCalls(this); }
  10050. ~StrictMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
  10051. };
  10052. } // namespace internal
  10053. template <class MockClass>
  10054. class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
  10055. : private internal::NiceMockImpl<MockClass>,
  10056. public MockClass {
  10057. public:
  10058. static_assert(!internal::HasStrictnessModifier<MockClass>(),
  10059. "Can't apply NiceMock to a class hierarchy that already has a "
  10060. "strictness modifier. See "
  10061. "https://google.github.io/googletest/"
  10062. "gmock_cook_book.html#NiceStrictNaggy");
  10063. NiceMock() : MockClass() {
  10064. static_assert(sizeof(*this) == sizeof(MockClass),
  10065. "The impl subclass shouldn't introduce any padding");
  10066. }
  10067. // Ideally, we would inherit base class's constructors through a using
  10068. // declaration, which would preserve their visibility. However, many existing
  10069. // tests rely on the fact that current implementation reexports protected
  10070. // constructors as public. These tests would need to be cleaned up first.
  10071. // Single argument constructor is special-cased so that it can be
  10072. // made explicit.
  10073. template <typename A>
  10074. explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) {
  10075. static_assert(sizeof(*this) == sizeof(MockClass),
  10076. "The impl subclass shouldn't introduce any padding");
  10077. }
  10078. template <typename TArg1, typename TArg2, typename... An>
  10079. NiceMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
  10080. : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
  10081. std::forward<An>(args)...) {
  10082. static_assert(sizeof(*this) == sizeof(MockClass),
  10083. "The impl subclass shouldn't introduce any padding");
  10084. }
  10085. private:
  10086. GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock);
  10087. };
  10088. template <class MockClass>
  10089. class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
  10090. : private internal::NaggyMockImpl<MockClass>,
  10091. public MockClass {
  10092. static_assert(!internal::HasStrictnessModifier<MockClass>(),
  10093. "Can't apply NaggyMock to a class hierarchy that already has a "
  10094. "strictness modifier. See "
  10095. "https://google.github.io/googletest/"
  10096. "gmock_cook_book.html#NiceStrictNaggy");
  10097. public:
  10098. NaggyMock() : MockClass() {
  10099. static_assert(sizeof(*this) == sizeof(MockClass),
  10100. "The impl subclass shouldn't introduce any padding");
  10101. }
  10102. // Ideally, we would inherit base class's constructors through a using
  10103. // declaration, which would preserve their visibility. However, many existing
  10104. // tests rely on the fact that current implementation reexports protected
  10105. // constructors as public. These tests would need to be cleaned up first.
  10106. // Single argument constructor is special-cased so that it can be
  10107. // made explicit.
  10108. template <typename A>
  10109. explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) {
  10110. static_assert(sizeof(*this) == sizeof(MockClass),
  10111. "The impl subclass shouldn't introduce any padding");
  10112. }
  10113. template <typename TArg1, typename TArg2, typename... An>
  10114. NaggyMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
  10115. : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
  10116. std::forward<An>(args)...) {
  10117. static_assert(sizeof(*this) == sizeof(MockClass),
  10118. "The impl subclass shouldn't introduce any padding");
  10119. }
  10120. private:
  10121. GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock);
  10122. };
  10123. template <class MockClass>
  10124. class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock
  10125. : private internal::StrictMockImpl<MockClass>,
  10126. public MockClass {
  10127. public:
  10128. static_assert(
  10129. !internal::HasStrictnessModifier<MockClass>(),
  10130. "Can't apply StrictMock to a class hierarchy that already has a "
  10131. "strictness modifier. See "
  10132. "https://google.github.io/googletest/"
  10133. "gmock_cook_book.html#NiceStrictNaggy");
  10134. StrictMock() : MockClass() {
  10135. static_assert(sizeof(*this) == sizeof(MockClass),
  10136. "The impl subclass shouldn't introduce any padding");
  10137. }
  10138. // Ideally, we would inherit base class's constructors through a using
  10139. // declaration, which would preserve their visibility. However, many existing
  10140. // tests rely on the fact that current implementation reexports protected
  10141. // constructors as public. These tests would need to be cleaned up first.
  10142. // Single argument constructor is special-cased so that it can be
  10143. // made explicit.
  10144. template <typename A>
  10145. explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) {
  10146. static_assert(sizeof(*this) == sizeof(MockClass),
  10147. "The impl subclass shouldn't introduce any padding");
  10148. }
  10149. template <typename TArg1, typename TArg2, typename... An>
  10150. StrictMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
  10151. : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
  10152. std::forward<An>(args)...) {
  10153. static_assert(sizeof(*this) == sizeof(MockClass),
  10154. "The impl subclass shouldn't introduce any padding");
  10155. }
  10156. private:
  10157. GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock);
  10158. };
  10159. #undef GTEST_INTERNAL_EMPTY_BASE_CLASS
  10160. } // namespace testing
  10161. #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
  10162. namespace testing {
  10163. // Declares Google Mock flags that we want a user to use programmatically.
  10164. GMOCK_DECLARE_bool_(catch_leaked_mocks);
  10165. GMOCK_DECLARE_string_(verbose);
  10166. GMOCK_DECLARE_int32_(default_mock_behavior);
  10167. // Initializes Google Mock. This must be called before running the
  10168. // tests. In particular, it parses the command line for the flags
  10169. // that Google Mock recognizes. Whenever a Google Mock flag is seen,
  10170. // it is removed from argv, and *argc is decremented.
  10171. //
  10172. // No value is returned. Instead, the Google Mock flag variables are
  10173. // updated.
  10174. //
  10175. // Since Google Test is needed for Google Mock to work, this function
  10176. // also initializes Google Test and parses its flags, if that hasn't
  10177. // been done.
  10178. GTEST_API_ void InitGoogleMock(int* argc, char** argv);
  10179. // This overloaded version can be used in Windows programs compiled in
  10180. // UNICODE mode.
  10181. GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv);
  10182. // This overloaded version can be used on Arduino/embedded platforms where
  10183. // there is no argc/argv.
  10184. GTEST_API_ void InitGoogleMock();
  10185. } // namespace testing
  10186. #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_