gtest.h 463 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399
  1. // Copyright 2005, 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. //
  30. // The Google C++ Testing and Mocking Framework (Google Test)
  31. //
  32. // This header file defines the public API for Google Test. It should be
  33. // included by any test program that uses Google Test.
  34. //
  35. // IMPORTANT NOTE: Due to limitation of the C++ language, we have to
  36. // leave some internal implementation details in this header file.
  37. // They are clearly marked by comments like this:
  38. //
  39. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  40. //
  41. // Such code is NOT meant to be used by a user directly, and is subject
  42. // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
  43. // program!
  44. //
  45. // Acknowledgment: Google Test borrowed the idea of automatic test
  46. // registration from Barthelemy Dagenais' (barthelemy@prologique.com)
  47. // easyUnit framework.
  48. // GOOGLETEST_CM0001 DO NOT DELETE
  49. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_H_
  50. #define GOOGLETEST_INCLUDE_GTEST_GTEST_H_
  51. #include <cstddef>
  52. #include <limits>
  53. #include <memory>
  54. #include <ostream>
  55. #include <type_traits>
  56. #include <vector>
  57. // Copyright 2005, Google Inc.
  58. // All rights reserved.
  59. //
  60. // Redistribution and use in source and binary forms, with or without
  61. // modification, are permitted provided that the following conditions are
  62. // met:
  63. //
  64. // * Redistributions of source code must retain the above copyright
  65. // notice, this list of conditions and the following disclaimer.
  66. // * Redistributions in binary form must reproduce the above
  67. // copyright notice, this list of conditions and the following disclaimer
  68. // in the documentation and/or other materials provided with the
  69. // distribution.
  70. // * Neither the name of Google Inc. nor the names of its
  71. // contributors may be used to endorse or promote products derived from
  72. // this software without specific prior written permission.
  73. //
  74. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  75. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  76. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  77. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  78. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  79. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  80. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  81. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  82. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  83. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  84. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  85. //
  86. // The Google C++ Testing and Mocking Framework (Google Test)
  87. //
  88. // This header file declares functions and macros used internally by
  89. // Google Test. They are subject to change without notice.
  90. // GOOGLETEST_CM0001 DO NOT DELETE
  91. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
  92. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
  93. // Copyright 2005, Google Inc.
  94. // All rights reserved.
  95. //
  96. // Redistribution and use in source and binary forms, with or without
  97. // modification, are permitted provided that the following conditions are
  98. // met:
  99. //
  100. // * Redistributions of source code must retain the above copyright
  101. // notice, this list of conditions and the following disclaimer.
  102. // * Redistributions in binary form must reproduce the above
  103. // copyright notice, this list of conditions and the following disclaimer
  104. // in the documentation and/or other materials provided with the
  105. // distribution.
  106. // * Neither the name of Google Inc. nor the names of its
  107. // contributors may be used to endorse or promote products derived from
  108. // this software without specific prior written permission.
  109. //
  110. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  111. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  112. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  113. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  114. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  115. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  116. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  117. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  118. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  119. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  120. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  121. //
  122. // Low-level types and utilities for porting Google Test to various
  123. // platforms. All macros ending with _ and symbols defined in an
  124. // internal namespace are subject to change without notice. Code
  125. // outside Google Test MUST NOT USE THEM DIRECTLY. Macros that don't
  126. // end with _ are part of Google Test's public API and can be used by
  127. // code outside Google Test.
  128. //
  129. // This file is fundamental to Google Test. All other Google Test source
  130. // files are expected to #include this. Therefore, it cannot #include
  131. // any other Google Test header.
  132. // GOOGLETEST_CM0001 DO NOT DELETE
  133. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
  134. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
  135. // Environment-describing macros
  136. // -----------------------------
  137. //
  138. // Google Test can be used in many different environments. Macros in
  139. // this section tell Google Test what kind of environment it is being
  140. // used in, such that Google Test can provide environment-specific
  141. // features and implementations.
  142. //
  143. // Google Test tries to automatically detect the properties of its
  144. // environment, so users usually don't need to worry about these
  145. // macros. However, the automatic detection is not perfect.
  146. // Sometimes it's necessary for a user to define some of the following
  147. // macros in the build script to override Google Test's decisions.
  148. //
  149. // If the user doesn't define a macro in the list, Google Test will
  150. // provide a default definition. After this header is #included, all
  151. // macros in this list will be defined to either 1 or 0.
  152. //
  153. // Notes to maintainers:
  154. // - Each macro here is a user-tweakable knob; do not grow the list
  155. // lightly.
  156. // - Use #if to key off these macros. Don't use #ifdef or "#if
  157. // defined(...)", which will not work as these macros are ALWAYS
  158. // defined.
  159. //
  160. // GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2)
  161. // is/isn't available.
  162. // GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions
  163. // are enabled.
  164. // GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular
  165. // expressions are/aren't available.
  166. // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h>
  167. // is/isn't available.
  168. // GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't
  169. // enabled.
  170. // GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that
  171. // std::wstring does/doesn't work (Google Test can
  172. // be used where std::wstring is unavailable).
  173. // GTEST_HAS_SEH - Define it to 1/0 to indicate whether the
  174. // compiler supports Microsoft's "Structured
  175. // Exception Handling".
  176. // GTEST_HAS_STREAM_REDIRECTION
  177. // - Define it to 1/0 to indicate whether the
  178. // platform supports I/O stream redirection using
  179. // dup() and dup2().
  180. // GTEST_LINKED_AS_SHARED_LIBRARY
  181. // - Define to 1 when compiling tests that use
  182. // Google Test as a shared library (known as
  183. // DLL on Windows).
  184. // GTEST_CREATE_SHARED_LIBRARY
  185. // - Define to 1 when compiling Google Test itself
  186. // as a shared library.
  187. // GTEST_DEFAULT_DEATH_TEST_STYLE
  188. // - The default value of --gtest_death_test_style.
  189. // The legacy default has been "fast" in the open
  190. // source version since 2008. The recommended value
  191. // is "threadsafe", and can be set in
  192. // custom/gtest-port.h.
  193. // Platform-indicating macros
  194. // --------------------------
  195. //
  196. // Macros indicating the platform on which Google Test is being used
  197. // (a macro is defined to 1 if compiled on the given platform;
  198. // otherwise UNDEFINED -- it's never defined to 0.). Google Test
  199. // defines these macros automatically. Code outside Google Test MUST
  200. // NOT define them.
  201. //
  202. // GTEST_OS_AIX - IBM AIX
  203. // GTEST_OS_CYGWIN - Cygwin
  204. // GTEST_OS_DRAGONFLY - DragonFlyBSD
  205. // GTEST_OS_FREEBSD - FreeBSD
  206. // GTEST_OS_FUCHSIA - Fuchsia
  207. // GTEST_OS_GNU_KFREEBSD - GNU/kFreeBSD
  208. // GTEST_OS_HAIKU - Haiku
  209. // GTEST_OS_HPUX - HP-UX
  210. // GTEST_OS_LINUX - Linux
  211. // GTEST_OS_LINUX_ANDROID - Google Android
  212. // GTEST_OS_MAC - Mac OS X
  213. // GTEST_OS_IOS - iOS
  214. // GTEST_OS_NACL - Google Native Client (NaCl)
  215. // GTEST_OS_NETBSD - NetBSD
  216. // GTEST_OS_OPENBSD - OpenBSD
  217. // GTEST_OS_OS2 - OS/2
  218. // GTEST_OS_QNX - QNX
  219. // GTEST_OS_SOLARIS - Sun Solaris
  220. // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile)
  221. // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop
  222. // GTEST_OS_WINDOWS_MINGW - MinGW
  223. // GTEST_OS_WINDOWS_MOBILE - Windows Mobile
  224. // GTEST_OS_WINDOWS_PHONE - Windows Phone
  225. // GTEST_OS_WINDOWS_RT - Windows Store App/WinRT
  226. // GTEST_OS_ZOS - z/OS
  227. //
  228. // Among the platforms, Cygwin, Linux, Mac OS X, and Windows have the
  229. // most stable support. Since core members of the Google Test project
  230. // don't have access to other platforms, support for them may be less
  231. // stable. If you notice any problems on your platform, please notify
  232. // googletestframework@googlegroups.com (patches for fixing them are
  233. // even more welcome!).
  234. //
  235. // It is possible that none of the GTEST_OS_* macros are defined.
  236. // Feature-indicating macros
  237. // -------------------------
  238. //
  239. // Macros indicating which Google Test features are available (a macro
  240. // is defined to 1 if the corresponding feature is supported;
  241. // otherwise UNDEFINED -- it's never defined to 0.). Google Test
  242. // defines these macros automatically. Code outside Google Test MUST
  243. // NOT define them.
  244. //
  245. // These macros are public so that portable tests can be written.
  246. // Such tests typically surround code using a feature with an #if
  247. // which controls that code. For example:
  248. //
  249. // #if GTEST_HAS_DEATH_TEST
  250. // EXPECT_DEATH(DoSomethingDeadly());
  251. // #endif
  252. //
  253. // GTEST_HAS_DEATH_TEST - death tests
  254. // GTEST_HAS_TYPED_TEST - typed tests
  255. // GTEST_HAS_TYPED_TEST_P - type-parameterized tests
  256. // GTEST_IS_THREADSAFE - Google Test is thread-safe.
  257. // GOOGLETEST_CM0007 DO NOT DELETE
  258. // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with
  259. // GTEST_HAS_POSIX_RE (see above) which users can
  260. // define themselves.
  261. // GTEST_USES_SIMPLE_RE - our own simple regex is used;
  262. // the above RE\b(s) are mutually exclusive.
  263. // Misc public macros
  264. // ------------------
  265. //
  266. // GTEST_FLAG(flag_name) - references the variable corresponding to
  267. // the given Google Test flag.
  268. // Internal utilities
  269. // ------------------
  270. //
  271. // The following macros and utilities are for Google Test's INTERNAL
  272. // use only. Code outside Google Test MUST NOT USE THEM DIRECTLY.
  273. //
  274. // Macros for basic C++ coding:
  275. // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
  276. // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a
  277. // variable don't have to be used.
  278. // GTEST_DISALLOW_ASSIGN_ - disables copy operator=.
  279. // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
  280. // GTEST_DISALLOW_MOVE_ASSIGN_ - disables move operator=.
  281. // GTEST_DISALLOW_MOVE_AND_ASSIGN_ - disables move ctor and operator=.
  282. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used.
  283. // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is
  284. // suppressed (constant conditional).
  285. // GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127
  286. // is suppressed.
  287. // GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter<std::any> or
  288. // UniversalPrinter<absl::any> specializations.
  289. // GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional>
  290. // or
  291. // UniversalPrinter<absl::optional>
  292. // specializations.
  293. // GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or
  294. // Matcher<absl::string_view>
  295. // specializations.
  296. // GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter<std::variant> or
  297. // UniversalPrinter<absl::variant>
  298. // specializations.
  299. //
  300. // Synchronization:
  301. // Mutex, MutexLock, ThreadLocal, GetThreadCount()
  302. // - synchronization primitives.
  303. //
  304. // Regular expressions:
  305. // RE - a simple regular expression class using the POSIX
  306. // Extended Regular Expression syntax on UNIX-like platforms
  307. // GOOGLETEST_CM0008 DO NOT DELETE
  308. // or a reduced regular exception syntax on other
  309. // platforms, including Windows.
  310. // Logging:
  311. // GTEST_LOG_() - logs messages at the specified severity level.
  312. // LogToStderr() - directs all log messages to stderr.
  313. // FlushInfoLog() - flushes informational log messages.
  314. //
  315. // Stdout and stderr capturing:
  316. // CaptureStdout() - starts capturing stdout.
  317. // GetCapturedStdout() - stops capturing stdout and returns the captured
  318. // string.
  319. // CaptureStderr() - starts capturing stderr.
  320. // GetCapturedStderr() - stops capturing stderr and returns the captured
  321. // string.
  322. //
  323. // Integer types:
  324. // TypeWithSize - maps an integer to a int type.
  325. // TimeInMillis - integers of known sizes.
  326. // BiggestInt - the biggest signed integer type.
  327. //
  328. // Command-line utilities:
  329. // GTEST_DECLARE_*() - declares a flag.
  330. // GTEST_DEFINE_*() - defines a flag.
  331. // GetInjectableArgvs() - returns the command line as a vector of strings.
  332. //
  333. // Environment variable utilities:
  334. // GetEnv() - gets the value of an environment variable.
  335. // BoolFromGTestEnv() - parses a bool environment variable.
  336. // Int32FromGTestEnv() - parses an int32_t environment variable.
  337. // StringFromGTestEnv() - parses a string environment variable.
  338. //
  339. // Deprecation warnings:
  340. // GTEST_INTERNAL_DEPRECATED(message) - attribute marking a function as
  341. // deprecated; calling a marked function
  342. // should generate a compiler warning
  343. #include <ctype.h> // for isspace, etc
  344. #include <stddef.h> // for ptrdiff_t
  345. #include <stdio.h>
  346. #include <stdlib.h>
  347. #include <string.h>
  348. #include <cerrno>
  349. #include <cstdint>
  350. #include <limits>
  351. #include <type_traits>
  352. #ifndef _WIN32_WCE
  353. # include <sys/types.h>
  354. # include <sys/stat.h>
  355. #endif // !_WIN32_WCE
  356. #if defined __APPLE__
  357. # include <AvailabilityMacros.h>
  358. # include <TargetConditionals.h>
  359. #endif
  360. #include <iostream> // NOLINT
  361. #include <locale>
  362. #include <memory>
  363. #include <string> // NOLINT
  364. #include <tuple>
  365. #include <vector> // NOLINT
  366. // Copyright 2015, Google Inc.
  367. // All rights reserved.
  368. //
  369. // Redistribution and use in source and binary forms, with or without
  370. // modification, are permitted provided that the following conditions are
  371. // met:
  372. //
  373. // * Redistributions of source code must retain the above copyright
  374. // notice, this list of conditions and the following disclaimer.
  375. // * Redistributions in binary form must reproduce the above
  376. // copyright notice, this list of conditions and the following disclaimer
  377. // in the documentation and/or other materials provided with the
  378. // distribution.
  379. // * Neither the name of Google Inc. nor the names of its
  380. // contributors may be used to endorse or promote products derived from
  381. // this software without specific prior written permission.
  382. //
  383. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  384. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  385. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  386. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  387. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  388. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  389. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  390. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  391. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  392. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  393. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  394. //
  395. // Injection point for custom user configurations. See README for details
  396. //
  397. // ** Custom implementation starts here **
  398. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
  399. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
  400. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
  401. // Copyright 2015, Google Inc.
  402. // All rights reserved.
  403. //
  404. // Redistribution and use in source and binary forms, with or without
  405. // modification, are permitted provided that the following conditions are
  406. // met:
  407. //
  408. // * Redistributions of source code must retain the above copyright
  409. // notice, this list of conditions and the following disclaimer.
  410. // * Redistributions in binary form must reproduce the above
  411. // copyright notice, this list of conditions and the following disclaimer
  412. // in the documentation and/or other materials provided with the
  413. // distribution.
  414. // * Neither the name of Google Inc. nor the names of its
  415. // contributors may be used to endorse or promote products derived from
  416. // this software without specific prior written permission.
  417. //
  418. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  419. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  420. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  421. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  422. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  423. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  424. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  425. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  426. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  427. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  428. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  429. //
  430. // The Google C++ Testing and Mocking Framework (Google Test)
  431. //
  432. // This header file defines the GTEST_OS_* macro.
  433. // It is separate from gtest-port.h so that custom/gtest-port.h can include it.
  434. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
  435. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
  436. // Determines the platform on which Google Test is compiled.
  437. #ifdef __CYGWIN__
  438. # define GTEST_OS_CYGWIN 1
  439. # elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)
  440. # define GTEST_OS_WINDOWS_MINGW 1
  441. # define GTEST_OS_WINDOWS 1
  442. #elif defined _WIN32
  443. # define GTEST_OS_WINDOWS 1
  444. # ifdef _WIN32_WCE
  445. # define GTEST_OS_WINDOWS_MOBILE 1
  446. # elif defined(WINAPI_FAMILY)
  447. # include <winapifamily.h>
  448. # if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
  449. # define GTEST_OS_WINDOWS_DESKTOP 1
  450. # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
  451. # define GTEST_OS_WINDOWS_PHONE 1
  452. # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
  453. # define GTEST_OS_WINDOWS_RT 1
  454. # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
  455. # define GTEST_OS_WINDOWS_PHONE 1
  456. # define GTEST_OS_WINDOWS_TV_TITLE 1
  457. # else
  458. // WINAPI_FAMILY defined but no known partition matched.
  459. // Default to desktop.
  460. # define GTEST_OS_WINDOWS_DESKTOP 1
  461. # endif
  462. # else
  463. # define GTEST_OS_WINDOWS_DESKTOP 1
  464. # endif // _WIN32_WCE
  465. #elif defined __OS2__
  466. # define GTEST_OS_OS2 1
  467. #elif defined __APPLE__
  468. # define GTEST_OS_MAC 1
  469. # include <TargetConditionals.h>
  470. # if TARGET_OS_IPHONE
  471. # define GTEST_OS_IOS 1
  472. # endif
  473. #elif defined __DragonFly__
  474. # define GTEST_OS_DRAGONFLY 1
  475. #elif defined __FreeBSD__
  476. # define GTEST_OS_FREEBSD 1
  477. #elif defined __Fuchsia__
  478. # define GTEST_OS_FUCHSIA 1
  479. #elif defined(__GLIBC__) && defined(__FreeBSD_kernel__)
  480. # define GTEST_OS_GNU_KFREEBSD 1
  481. #elif defined __linux__
  482. # define GTEST_OS_LINUX 1
  483. # if defined __ANDROID__
  484. # define GTEST_OS_LINUX_ANDROID 1
  485. # endif
  486. #elif defined __MVS__
  487. # define GTEST_OS_ZOS 1
  488. #elif defined(__sun) && defined(__SVR4)
  489. # define GTEST_OS_SOLARIS 1
  490. #elif defined(_AIX)
  491. # define GTEST_OS_AIX 1
  492. #elif defined(__hpux)
  493. # define GTEST_OS_HPUX 1
  494. #elif defined __native_client__
  495. # define GTEST_OS_NACL 1
  496. #elif defined __NetBSD__
  497. # define GTEST_OS_NETBSD 1
  498. #elif defined __OpenBSD__
  499. # define GTEST_OS_OPENBSD 1
  500. #elif defined __QNX__
  501. # define GTEST_OS_QNX 1
  502. #elif defined(__HAIKU__)
  503. #define GTEST_OS_HAIKU 1
  504. #elif defined ESP8266
  505. #define GTEST_OS_ESP8266 1
  506. #elif defined ESP32
  507. #define GTEST_OS_ESP32 1
  508. #elif defined(__XTENSA__)
  509. #define GTEST_OS_XTENSA 1
  510. #endif // __CYGWIN__
  511. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
  512. #if !defined(GTEST_DEV_EMAIL_)
  513. # define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
  514. # define GTEST_FLAG_PREFIX_ "gtest_"
  515. # define GTEST_FLAG_PREFIX_DASH_ "gtest-"
  516. # define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
  517. # define GTEST_NAME_ "Google Test"
  518. # define GTEST_PROJECT_URL_ "https://github.com/google/googletest/"
  519. #endif // !defined(GTEST_DEV_EMAIL_)
  520. #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
  521. # define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest"
  522. #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
  523. // Determines the version of gcc that is used to compile this.
  524. #ifdef __GNUC__
  525. // 40302 means version 4.3.2.
  526. # define GTEST_GCC_VER_ \
  527. (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
  528. #endif // __GNUC__
  529. // Macros for disabling Microsoft Visual C++ warnings.
  530. //
  531. // GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385)
  532. // /* code that triggers warnings C4800 and C4385 */
  533. // GTEST_DISABLE_MSC_WARNINGS_POP_()
  534. #if defined(_MSC_VER)
  535. # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
  536. __pragma(warning(push)) \
  537. __pragma(warning(disable: warnings))
  538. # define GTEST_DISABLE_MSC_WARNINGS_POP_() \
  539. __pragma(warning(pop))
  540. #else
  541. // Not all compilers are MSVC
  542. # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
  543. # define GTEST_DISABLE_MSC_WARNINGS_POP_()
  544. #endif
  545. // Clang on Windows does not understand MSVC's pragma warning.
  546. // We need clang-specific way to disable function deprecation warning.
  547. #ifdef __clang__
  548. # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
  549. _Pragma("clang diagnostic push") \
  550. _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \
  551. _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"")
  552. #define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
  553. _Pragma("clang diagnostic pop")
  554. #else
  555. # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
  556. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
  557. # define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
  558. GTEST_DISABLE_MSC_WARNINGS_POP_()
  559. #endif
  560. // Brings in definitions for functions used in the testing::internal::posix
  561. // namespace (read, write, close, chdir, isatty, stat). We do not currently
  562. // use them on Windows Mobile.
  563. #if GTEST_OS_WINDOWS
  564. # if !GTEST_OS_WINDOWS_MOBILE
  565. # include <direct.h>
  566. # include <io.h>
  567. # endif
  568. // In order to avoid having to include <windows.h>, use forward declaration
  569. #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
  570. // MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two
  571. // separate (equivalent) structs, instead of using typedef
  572. typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION;
  573. #else
  574. // Assume CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION.
  575. // This assumption is verified by
  576. // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
  577. typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
  578. #endif
  579. #elif GTEST_OS_XTENSA
  580. #include <unistd.h>
  581. // Xtensa toolchains define strcasecmp in the string.h header instead of
  582. // strings.h. string.h is already included.
  583. #else
  584. // This assumes that non-Windows OSes provide unistd.h. For OSes where this
  585. // is not the case, we need to include headers that provide the functions
  586. // mentioned above.
  587. # include <unistd.h>
  588. # include <strings.h>
  589. #endif // GTEST_OS_WINDOWS
  590. #if GTEST_OS_LINUX_ANDROID
  591. // Used to define __ANDROID_API__ matching the target NDK API level.
  592. # include <android/api-level.h> // NOLINT
  593. #endif
  594. // Defines this to true if and only if Google Test can use POSIX regular
  595. // expressions.
  596. #ifndef GTEST_HAS_POSIX_RE
  597. # if GTEST_OS_LINUX_ANDROID
  598. // On Android, <regex.h> is only available starting with Gingerbread.
  599. # define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
  600. # else
  601. #define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS && !GTEST_OS_XTENSA)
  602. # endif
  603. #endif
  604. #if GTEST_USES_PCRE
  605. // The appropriate headers have already been included.
  606. #elif GTEST_HAS_POSIX_RE
  607. // On some platforms, <regex.h> needs someone to define size_t, and
  608. // won't compile otherwise. We can #include it here as we already
  609. // included <stdlib.h>, which is guaranteed to define size_t through
  610. // <stddef.h>.
  611. # include <regex.h> // NOLINT
  612. # define GTEST_USES_POSIX_RE 1
  613. #elif GTEST_OS_WINDOWS
  614. // <regex.h> is not available on Windows. Use our own simple regex
  615. // implementation instead.
  616. # define GTEST_USES_SIMPLE_RE 1
  617. #else
  618. // <regex.h> may not be available on this platform. Use our own
  619. // simple regex implementation instead.
  620. # define GTEST_USES_SIMPLE_RE 1
  621. #endif // GTEST_USES_PCRE
  622. #ifndef GTEST_HAS_EXCEPTIONS
  623. // The user didn't tell us whether exceptions are enabled, so we need
  624. // to figure it out.
  625. # if defined(_MSC_VER) && defined(_CPPUNWIND)
  626. // MSVC defines _CPPUNWIND to 1 if and only if exceptions are enabled.
  627. # define GTEST_HAS_EXCEPTIONS 1
  628. # elif defined(__BORLANDC__)
  629. // C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS
  630. // macro to enable exceptions, so we'll do the same.
  631. // Assumes that exceptions are enabled by default.
  632. # ifndef _HAS_EXCEPTIONS
  633. # define _HAS_EXCEPTIONS 1
  634. # endif // _HAS_EXCEPTIONS
  635. # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
  636. # elif defined(__clang__)
  637. // clang defines __EXCEPTIONS if and only if exceptions are enabled before clang
  638. // 220714, but if and only if cleanups are enabled after that. In Obj-C++ files,
  639. // there can be cleanups for ObjC exceptions which also need cleanups, even if
  640. // C++ exceptions are disabled. clang has __has_feature(cxx_exceptions) which
  641. // checks for C++ exceptions starting at clang r206352, but which checked for
  642. // cleanups prior to that. To reliably check for C++ exception availability with
  643. // clang, check for
  644. // __EXCEPTIONS && __has_feature(cxx_exceptions).
  645. # define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
  646. # elif defined(__GNUC__) && __EXCEPTIONS
  647. // gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
  648. # define GTEST_HAS_EXCEPTIONS 1
  649. # elif defined(__SUNPRO_CC)
  650. // Sun Pro CC supports exceptions. However, there is no compile-time way of
  651. // detecting whether they are enabled or not. Therefore, we assume that
  652. // they are enabled unless the user tells us otherwise.
  653. # define GTEST_HAS_EXCEPTIONS 1
  654. # elif defined(__IBMCPP__) && __EXCEPTIONS
  655. // xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
  656. # define GTEST_HAS_EXCEPTIONS 1
  657. # elif defined(__HP_aCC)
  658. // Exception handling is in effect by default in HP aCC compiler. It has to
  659. // be turned of by +noeh compiler option if desired.
  660. # define GTEST_HAS_EXCEPTIONS 1
  661. # else
  662. // For other compilers, we assume exceptions are disabled to be
  663. // conservative.
  664. # define GTEST_HAS_EXCEPTIONS 0
  665. # endif // defined(_MSC_VER) || defined(__BORLANDC__)
  666. #endif // GTEST_HAS_EXCEPTIONS
  667. #ifndef GTEST_HAS_STD_WSTRING
  668. // The user didn't tell us whether ::std::wstring is available, so we need
  669. // to figure it out.
  670. // Cygwin 1.7 and below doesn't support ::std::wstring.
  671. // Solaris' libc++ doesn't support it either. Android has
  672. // no support for it at least as recent as Froyo (2.2).
  673. #define GTEST_HAS_STD_WSTRING \
  674. (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
  675. GTEST_OS_HAIKU || GTEST_OS_ESP32 || GTEST_OS_ESP8266 || GTEST_OS_XTENSA))
  676. #endif // GTEST_HAS_STD_WSTRING
  677. // Determines whether RTTI is available.
  678. #ifndef GTEST_HAS_RTTI
  679. // The user didn't tell us whether RTTI is enabled, so we need to
  680. // figure it out.
  681. # ifdef _MSC_VER
  682. #ifdef _CPPRTTI // MSVC defines this macro if and only if RTTI is enabled.
  683. # define GTEST_HAS_RTTI 1
  684. # else
  685. # define GTEST_HAS_RTTI 0
  686. # endif
  687. // Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is
  688. // enabled.
  689. # elif defined(__GNUC__)
  690. # ifdef __GXX_RTTI
  691. // When building against STLport with the Android NDK and with
  692. // -frtti -fno-exceptions, the build fails at link time with undefined
  693. // references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
  694. // so disable RTTI when detected.
  695. # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
  696. !defined(__EXCEPTIONS)
  697. # define GTEST_HAS_RTTI 0
  698. # else
  699. # define GTEST_HAS_RTTI 1
  700. # endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
  701. # else
  702. # define GTEST_HAS_RTTI 0
  703. # endif // __GXX_RTTI
  704. // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends
  705. // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the
  706. // first version with C++ support.
  707. # elif defined(__clang__)
  708. # define GTEST_HAS_RTTI __has_feature(cxx_rtti)
  709. // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
  710. // both the typeid and dynamic_cast features are present.
  711. # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
  712. # ifdef __RTTI_ALL__
  713. # define GTEST_HAS_RTTI 1
  714. # else
  715. # define GTEST_HAS_RTTI 0
  716. # endif
  717. # else
  718. // For all other compilers, we assume RTTI is enabled.
  719. # define GTEST_HAS_RTTI 1
  720. # endif // _MSC_VER
  721. #endif // GTEST_HAS_RTTI
  722. // It's this header's responsibility to #include <typeinfo> when RTTI
  723. // is enabled.
  724. #if GTEST_HAS_RTTI
  725. # include <typeinfo>
  726. #endif
  727. // Determines whether Google Test can use the pthreads library.
  728. #ifndef GTEST_HAS_PTHREAD
  729. // The user didn't tell us explicitly, so we make reasonable assumptions about
  730. // which platforms have pthreads support.
  731. //
  732. // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
  733. // to your compiler flags.
  734. #define GTEST_HAS_PTHREAD \
  735. (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \
  736. GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
  737. GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD || \
  738. GTEST_OS_HAIKU)
  739. #endif // GTEST_HAS_PTHREAD
  740. #if GTEST_HAS_PTHREAD
  741. // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
  742. // true.
  743. # include <pthread.h> // NOLINT
  744. // For timespec and nanosleep, used below.
  745. # include <time.h> // NOLINT
  746. #endif
  747. // Determines whether clone(2) is supported.
  748. // Usually it will only be available on Linux, excluding
  749. // Linux on the Itanium architecture.
  750. // Also see http://linux.die.net/man/2/clone.
  751. #ifndef GTEST_HAS_CLONE
  752. // The user didn't tell us, so we need to figure it out.
  753. # if GTEST_OS_LINUX && !defined(__ia64__)
  754. # if GTEST_OS_LINUX_ANDROID
  755. // On Android, clone() became available at different API levels for each 32-bit
  756. // architecture.
  757. # if defined(__LP64__) || \
  758. (defined(__arm__) && __ANDROID_API__ >= 9) || \
  759. (defined(__mips__) && __ANDROID_API__ >= 12) || \
  760. (defined(__i386__) && __ANDROID_API__ >= 17)
  761. # define GTEST_HAS_CLONE 1
  762. # else
  763. # define GTEST_HAS_CLONE 0
  764. # endif
  765. # else
  766. # define GTEST_HAS_CLONE 1
  767. # endif
  768. # else
  769. # define GTEST_HAS_CLONE 0
  770. # endif // GTEST_OS_LINUX && !defined(__ia64__)
  771. #endif // GTEST_HAS_CLONE
  772. // Determines whether to support stream redirection. This is used to test
  773. // output correctness and to implement death tests.
  774. #ifndef GTEST_HAS_STREAM_REDIRECTION
  775. // By default, we assume that stream redirection is supported on all
  776. // platforms except known mobile ones.
  777. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
  778. GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
  779. # define GTEST_HAS_STREAM_REDIRECTION 0
  780. # else
  781. # define GTEST_HAS_STREAM_REDIRECTION 1
  782. # endif // !GTEST_OS_WINDOWS_MOBILE
  783. #endif // GTEST_HAS_STREAM_REDIRECTION
  784. // Determines whether to support death tests.
  785. // pops up a dialog window that cannot be suppressed programmatically.
  786. #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
  787. (GTEST_OS_MAC && !GTEST_OS_IOS) || \
  788. (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW || \
  789. GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \
  790. GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
  791. GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU)
  792. # define GTEST_HAS_DEATH_TEST 1
  793. #endif
  794. // Determines whether to support type-driven tests.
  795. // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
  796. // Sun Pro CC, IBM Visual Age, and HP aCC support.
  797. #if defined(__GNUC__) || defined(_MSC_VER) || defined(__SUNPRO_CC) || \
  798. defined(__IBMCPP__) || defined(__HP_aCC)
  799. # define GTEST_HAS_TYPED_TEST 1
  800. # define GTEST_HAS_TYPED_TEST_P 1
  801. #endif
  802. // Determines whether the system compiler uses UTF-16 for encoding wide strings.
  803. #define GTEST_WIDE_STRING_USES_UTF16_ \
  804. (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2)
  805. // Determines whether test results can be streamed to a socket.
  806. #if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \
  807. GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD
  808. # define GTEST_CAN_STREAM_RESULTS_ 1
  809. #endif
  810. // Defines some utility macros.
  811. // The GNU compiler emits a warning if nested "if" statements are followed by
  812. // an "else" statement and braces are not used to explicitly disambiguate the
  813. // "else" binding. This leads to problems with code like:
  814. //
  815. // if (gate)
  816. // ASSERT_*(condition) << "Some message";
  817. //
  818. // The "switch (0) case 0:" idiom is used to suppress this.
  819. #ifdef __INTEL_COMPILER
  820. # define GTEST_AMBIGUOUS_ELSE_BLOCKER_
  821. #else
  822. # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT
  823. #endif
  824. // Use this annotation at the end of a struct/class definition to
  825. // prevent the compiler from optimizing away instances that are never
  826. // used. This is useful when all interesting logic happens inside the
  827. // c'tor and / or d'tor. Example:
  828. //
  829. // struct Foo {
  830. // Foo() { ... }
  831. // } GTEST_ATTRIBUTE_UNUSED_;
  832. //
  833. // Also use it after a variable or parameter declaration to tell the
  834. // compiler the variable/parameter does not have to be used.
  835. #if defined(__GNUC__) && !defined(COMPILER_ICC)
  836. # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
  837. #elif defined(__clang__)
  838. # if __has_attribute(unused)
  839. # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
  840. # endif
  841. #endif
  842. #ifndef GTEST_ATTRIBUTE_UNUSED_
  843. # define GTEST_ATTRIBUTE_UNUSED_
  844. #endif
  845. // Use this annotation before a function that takes a printf format string.
  846. #if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC)
  847. # if defined(__MINGW_PRINTF_FORMAT)
  848. // MinGW has two different printf implementations. Ensure the format macro
  849. // matches the selected implementation. See
  850. // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/.
  851. # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
  852. __attribute__((__format__(__MINGW_PRINTF_FORMAT, string_index, \
  853. first_to_check)))
  854. # else
  855. # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
  856. __attribute__((__format__(__printf__, string_index, first_to_check)))
  857. # endif
  858. #else
  859. # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
  860. #endif
  861. // A macro to disallow copy operator=
  862. // This should be used in the private: declarations for a class.
  863. #define GTEST_DISALLOW_ASSIGN_(type) \
  864. type& operator=(type const &) = delete
  865. // A macro to disallow copy constructor and operator=
  866. // This should be used in the private: declarations for a class.
  867. #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \
  868. type(type const&) = delete; \
  869. type& operator=(type const&) = delete
  870. // A macro to disallow move operator=
  871. // This should be used in the private: declarations for a class.
  872. #define GTEST_DISALLOW_MOVE_ASSIGN_(type) \
  873. type& operator=(type &&) noexcept = delete
  874. // A macro to disallow move constructor and operator=
  875. // This should be used in the private: declarations for a class.
  876. #define GTEST_DISALLOW_MOVE_AND_ASSIGN_(type) \
  877. type(type&&) noexcept = delete; \
  878. type& operator=(type&&) noexcept = delete
  879. // Tell the compiler to warn about unused return values for functions declared
  880. // with this macro. The macro should be used on function declarations
  881. // following the argument list:
  882. //
  883. // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
  884. #if defined(__GNUC__) && !defined(COMPILER_ICC)
  885. # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
  886. #else
  887. # define GTEST_MUST_USE_RESULT_
  888. #endif // __GNUC__ && !COMPILER_ICC
  889. // MS C++ compiler emits warning when a conditional expression is compile time
  890. // constant. In some contexts this warning is false positive and needs to be
  891. // suppressed. Use the following two macros in such cases:
  892. //
  893. // GTEST_INTENTIONAL_CONST_COND_PUSH_()
  894. // while (true) {
  895. // GTEST_INTENTIONAL_CONST_COND_POP_()
  896. // }
  897. # define GTEST_INTENTIONAL_CONST_COND_PUSH_() \
  898. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)
  899. # define GTEST_INTENTIONAL_CONST_COND_POP_() \
  900. GTEST_DISABLE_MSC_WARNINGS_POP_()
  901. // Determine whether the compiler supports Microsoft's Structured Exception
  902. // Handling. This is supported by several Windows compilers but generally
  903. // does not exist on any other system.
  904. #ifndef GTEST_HAS_SEH
  905. // The user didn't tell us, so we need to figure it out.
  906. # if defined(_MSC_VER) || defined(__BORLANDC__)
  907. // These two compilers are known to support SEH.
  908. # define GTEST_HAS_SEH 1
  909. # else
  910. // Assume no SEH.
  911. # define GTEST_HAS_SEH 0
  912. # endif
  913. #endif // GTEST_HAS_SEH
  914. #ifndef GTEST_IS_THREADSAFE
  915. #define GTEST_IS_THREADSAFE \
  916. (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \
  917. (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) || \
  918. GTEST_HAS_PTHREAD)
  919. #endif // GTEST_IS_THREADSAFE
  920. // GTEST_API_ qualifies all symbols that must be exported. The definitions below
  921. // are guarded by #ifndef to give embedders a chance to define GTEST_API_ in
  922. // gtest/internal/custom/gtest-port.h
  923. #ifndef GTEST_API_
  924. #ifdef _MSC_VER
  925. # if GTEST_LINKED_AS_SHARED_LIBRARY
  926. # define GTEST_API_ __declspec(dllimport)
  927. # elif GTEST_CREATE_SHARED_LIBRARY
  928. # define GTEST_API_ __declspec(dllexport)
  929. # endif
  930. #elif __GNUC__ >= 4 || defined(__clang__)
  931. # define GTEST_API_ __attribute__((visibility ("default")))
  932. #endif // _MSC_VER
  933. #endif // GTEST_API_
  934. #ifndef GTEST_API_
  935. # define GTEST_API_
  936. #endif // GTEST_API_
  937. #ifndef GTEST_DEFAULT_DEATH_TEST_STYLE
  938. # define GTEST_DEFAULT_DEATH_TEST_STYLE "fast"
  939. #endif // GTEST_DEFAULT_DEATH_TEST_STYLE
  940. #ifdef __GNUC__
  941. // Ask the compiler to never inline a given function.
  942. # define GTEST_NO_INLINE_ __attribute__((noinline))
  943. #else
  944. # define GTEST_NO_INLINE_
  945. #endif
  946. // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
  947. #if !defined(GTEST_HAS_CXXABI_H_)
  948. # if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER))
  949. # define GTEST_HAS_CXXABI_H_ 1
  950. # else
  951. # define GTEST_HAS_CXXABI_H_ 0
  952. # endif
  953. #endif
  954. // A function level attribute to disable checking for use of uninitialized
  955. // memory when built with MemorySanitizer.
  956. #if defined(__clang__)
  957. # if __has_feature(memory_sanitizer)
  958. # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
  959. __attribute__((no_sanitize_memory))
  960. # else
  961. # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  962. # endif // __has_feature(memory_sanitizer)
  963. #else
  964. # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  965. #endif // __clang__
  966. // A function level attribute to disable AddressSanitizer instrumentation.
  967. #if defined(__clang__)
  968. # if __has_feature(address_sanitizer)
  969. # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
  970. __attribute__((no_sanitize_address))
  971. # else
  972. # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  973. # endif // __has_feature(address_sanitizer)
  974. #else
  975. # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  976. #endif // __clang__
  977. // A function level attribute to disable HWAddressSanitizer instrumentation.
  978. #if defined(__clang__)
  979. # if __has_feature(hwaddress_sanitizer)
  980. # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \
  981. __attribute__((no_sanitize("hwaddress")))
  982. # else
  983. # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  984. # endif // __has_feature(hwaddress_sanitizer)
  985. #else
  986. # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  987. #endif // __clang__
  988. // A function level attribute to disable ThreadSanitizer instrumentation.
  989. #if defined(__clang__)
  990. # if __has_feature(thread_sanitizer)
  991. # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
  992. __attribute__((no_sanitize_thread))
  993. # else
  994. # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  995. # endif // __has_feature(thread_sanitizer)
  996. #else
  997. # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  998. #endif // __clang__
  999. namespace testing {
  1000. class Message;
  1001. // Legacy imports for backwards compatibility.
  1002. // New code should use std:: names directly.
  1003. using std::get;
  1004. using std::make_tuple;
  1005. using std::tuple;
  1006. using std::tuple_element;
  1007. using std::tuple_size;
  1008. namespace internal {
  1009. // A secret type that Google Test users don't know about. It has no
  1010. // definition on purpose. Therefore it's impossible to create a
  1011. // Secret object, which is what we want.
  1012. class Secret;
  1013. // The GTEST_COMPILE_ASSERT_ is a legacy macro used to verify that a compile
  1014. // time expression is true (in new code, use static_assert instead). For
  1015. // example, you could use it to verify the size of a static array:
  1016. //
  1017. // GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
  1018. // names_incorrect_size);
  1019. //
  1020. // The second argument to the macro must be a valid C++ identifier. If the
  1021. // expression is false, compiler will issue an error containing this identifier.
  1022. #define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg)
  1023. // A helper for suppressing warnings on constant condition. It just
  1024. // returns 'condition'.
  1025. GTEST_API_ bool IsTrue(bool condition);
  1026. // Defines RE.
  1027. #if GTEST_USES_PCRE
  1028. // if used, PCRE is injected by custom/gtest-port.h
  1029. #elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE
  1030. // A simple C++ wrapper for <regex.h>. It uses the POSIX Extended
  1031. // Regular Expression syntax.
  1032. class GTEST_API_ RE {
  1033. public:
  1034. // A copy constructor is required by the Standard to initialize object
  1035. // references from r-values.
  1036. RE(const RE& other) { Init(other.pattern()); }
  1037. // Constructs an RE from a string.
  1038. RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT
  1039. RE(const char* regex) { Init(regex); } // NOLINT
  1040. ~RE();
  1041. // Returns the string representation of the regex.
  1042. const char* pattern() const { return pattern_; }
  1043. // FullMatch(str, re) returns true if and only if regular expression re
  1044. // matches the entire str.
  1045. // PartialMatch(str, re) returns true if and only if regular expression re
  1046. // matches a substring of str (including str itself).
  1047. static bool FullMatch(const ::std::string& str, const RE& re) {
  1048. return FullMatch(str.c_str(), re);
  1049. }
  1050. static bool PartialMatch(const ::std::string& str, const RE& re) {
  1051. return PartialMatch(str.c_str(), re);
  1052. }
  1053. static bool FullMatch(const char* str, const RE& re);
  1054. static bool PartialMatch(const char* str, const RE& re);
  1055. private:
  1056. void Init(const char* regex);
  1057. const char* pattern_;
  1058. bool is_valid_;
  1059. # if GTEST_USES_POSIX_RE
  1060. regex_t full_regex_; // For FullMatch().
  1061. regex_t partial_regex_; // For PartialMatch().
  1062. # else // GTEST_USES_SIMPLE_RE
  1063. const char* full_pattern_; // For FullMatch();
  1064. # endif
  1065. };
  1066. #endif // GTEST_USES_PCRE
  1067. // Formats a source file path and a line number as they would appear
  1068. // in an error message from the compiler used to compile this code.
  1069. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
  1070. // Formats a file location for compiler-independent XML output.
  1071. // Although this function is not platform dependent, we put it next to
  1072. // FormatFileLocation in order to contrast the two functions.
  1073. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
  1074. int line);
  1075. // Defines logging utilities:
  1076. // GTEST_LOG_(severity) - logs messages at the specified severity level. The
  1077. // message itself is streamed into the macro.
  1078. // LogToStderr() - directs all log messages to stderr.
  1079. // FlushInfoLog() - flushes informational log messages.
  1080. enum GTestLogSeverity {
  1081. GTEST_INFO,
  1082. GTEST_WARNING,
  1083. GTEST_ERROR,
  1084. GTEST_FATAL
  1085. };
  1086. // Formats log entry severity, provides a stream object for streaming the
  1087. // log message, and terminates the message with a newline when going out of
  1088. // scope.
  1089. class GTEST_API_ GTestLog {
  1090. public:
  1091. GTestLog(GTestLogSeverity severity, const char* file, int line);
  1092. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  1093. ~GTestLog();
  1094. ::std::ostream& GetStream() { return ::std::cerr; }
  1095. private:
  1096. const GTestLogSeverity severity_;
  1097. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
  1098. };
  1099. #if !defined(GTEST_LOG_)
  1100. # define GTEST_LOG_(severity) \
  1101. ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
  1102. __FILE__, __LINE__).GetStream()
  1103. inline void LogToStderr() {}
  1104. inline void FlushInfoLog() { fflush(nullptr); }
  1105. #endif // !defined(GTEST_LOG_)
  1106. #if !defined(GTEST_CHECK_)
  1107. // INTERNAL IMPLEMENTATION - DO NOT USE.
  1108. //
  1109. // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
  1110. // is not satisfied.
  1111. // Synopsys:
  1112. // GTEST_CHECK_(boolean_condition);
  1113. // or
  1114. // GTEST_CHECK_(boolean_condition) << "Additional message";
  1115. //
  1116. // This checks the condition and if the condition is not satisfied
  1117. // it prints message about the condition violation, including the
  1118. // condition itself, plus additional message streamed into it, if any,
  1119. // and then it aborts the program. It aborts the program irrespective of
  1120. // whether it is built in the debug mode or not.
  1121. # define GTEST_CHECK_(condition) \
  1122. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  1123. if (::testing::internal::IsTrue(condition)) \
  1124. ; \
  1125. else \
  1126. GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
  1127. #endif // !defined(GTEST_CHECK_)
  1128. // An all-mode assert to verify that the given POSIX-style function
  1129. // call returns 0 (indicating success). Known limitation: this
  1130. // doesn't expand to a balanced 'if' statement, so enclose the macro
  1131. // in {} if you need to use it as the only statement in an 'if'
  1132. // branch.
  1133. #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
  1134. if (const int gtest_error = (posix_call)) \
  1135. GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
  1136. << gtest_error
  1137. // Transforms "T" into "const T&" according to standard reference collapsing
  1138. // rules (this is only needed as a backport for C++98 compilers that do not
  1139. // support reference collapsing). Specifically, it transforms:
  1140. //
  1141. // char ==> const char&
  1142. // const char ==> const char&
  1143. // char& ==> char&
  1144. // const char& ==> const char&
  1145. //
  1146. // Note that the non-const reference will not have "const" added. This is
  1147. // standard, and necessary so that "T" can always bind to "const T&".
  1148. template <typename T>
  1149. struct ConstRef { typedef const T& type; };
  1150. template <typename T>
  1151. struct ConstRef<T&> { typedef T& type; };
  1152. // The argument T must depend on some template parameters.
  1153. #define GTEST_REFERENCE_TO_CONST_(T) \
  1154. typename ::testing::internal::ConstRef<T>::type
  1155. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  1156. //
  1157. // Use ImplicitCast_ as a safe version of static_cast for upcasting in
  1158. // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a
  1159. // const Foo*). When you use ImplicitCast_, the compiler checks that
  1160. // the cast is safe. Such explicit ImplicitCast_s are necessary in
  1161. // surprisingly many situations where C++ demands an exact type match
  1162. // instead of an argument type convertable to a target type.
  1163. //
  1164. // The syntax for using ImplicitCast_ is the same as for static_cast:
  1165. //
  1166. // ImplicitCast_<ToType>(expr)
  1167. //
  1168. // ImplicitCast_ would have been part of the C++ standard library,
  1169. // but the proposal was submitted too late. It will probably make
  1170. // its way into the language in the future.
  1171. //
  1172. // This relatively ugly name is intentional. It prevents clashes with
  1173. // similar functions users may have (e.g., implicit_cast). The internal
  1174. // namespace alone is not enough because the function can be found by ADL.
  1175. template<typename To>
  1176. inline To ImplicitCast_(To x) { return x; }
  1177. // When you upcast (that is, cast a pointer from type Foo to type
  1178. // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
  1179. // always succeed. When you downcast (that is, cast a pointer from
  1180. // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
  1181. // how do you know the pointer is really of type SubclassOfFoo? It
  1182. // could be a bare Foo, or of type DifferentSubclassOfFoo. Thus,
  1183. // when you downcast, you should use this macro. In debug mode, we
  1184. // use dynamic_cast<> to double-check the downcast is legal (we die
  1185. // if it's not). In normal mode, we do the efficient static_cast<>
  1186. // instead. Thus, it's important to test in debug mode to make sure
  1187. // the cast is legal!
  1188. // This is the only place in the code we should use dynamic_cast<>.
  1189. // In particular, you SHOULDN'T be using dynamic_cast<> in order to
  1190. // do RTTI (eg code like this:
  1191. // if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
  1192. // if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
  1193. // You should design the code some other way not to need this.
  1194. //
  1195. // This relatively ugly name is intentional. It prevents clashes with
  1196. // similar functions users may have (e.g., down_cast). The internal
  1197. // namespace alone is not enough because the function can be found by ADL.
  1198. template<typename To, typename From> // use like this: DownCast_<T*>(foo);
  1199. inline To DownCast_(From* f) { // so we only accept pointers
  1200. // Ensures that To is a sub-type of From *. This test is here only
  1201. // for compile-time type checking, and has no overhead in an
  1202. // optimized build at run-time, as it will be optimized away
  1203. // completely.
  1204. GTEST_INTENTIONAL_CONST_COND_PUSH_()
  1205. if (false) {
  1206. GTEST_INTENTIONAL_CONST_COND_POP_()
  1207. const To to = nullptr;
  1208. ::testing::internal::ImplicitCast_<From*>(to);
  1209. }
  1210. #if GTEST_HAS_RTTI
  1211. // RTTI: debug mode only!
  1212. GTEST_CHECK_(f == nullptr || dynamic_cast<To>(f) != nullptr);
  1213. #endif
  1214. return static_cast<To>(f);
  1215. }
  1216. // Downcasts the pointer of type Base to Derived.
  1217. // Derived must be a subclass of Base. The parameter MUST
  1218. // point to a class of type Derived, not any subclass of it.
  1219. // When RTTI is available, the function performs a runtime
  1220. // check to enforce this.
  1221. template <class Derived, class Base>
  1222. Derived* CheckedDowncastToActualType(Base* base) {
  1223. #if GTEST_HAS_RTTI
  1224. GTEST_CHECK_(typeid(*base) == typeid(Derived));
  1225. #endif
  1226. #if GTEST_HAS_DOWNCAST_
  1227. return ::down_cast<Derived*>(base);
  1228. #elif GTEST_HAS_RTTI
  1229. return dynamic_cast<Derived*>(base); // NOLINT
  1230. #else
  1231. return static_cast<Derived*>(base); // Poor man's downcast.
  1232. #endif
  1233. }
  1234. #if GTEST_HAS_STREAM_REDIRECTION
  1235. // Defines the stderr capturer:
  1236. // CaptureStdout - starts capturing stdout.
  1237. // GetCapturedStdout - stops capturing stdout and returns the captured string.
  1238. // CaptureStderr - starts capturing stderr.
  1239. // GetCapturedStderr - stops capturing stderr and returns the captured string.
  1240. //
  1241. GTEST_API_ void CaptureStdout();
  1242. GTEST_API_ std::string GetCapturedStdout();
  1243. GTEST_API_ void CaptureStderr();
  1244. GTEST_API_ std::string GetCapturedStderr();
  1245. #endif // GTEST_HAS_STREAM_REDIRECTION
  1246. // Returns the size (in bytes) of a file.
  1247. GTEST_API_ size_t GetFileSize(FILE* file);
  1248. // Reads the entire content of a file as a string.
  1249. GTEST_API_ std::string ReadEntireFile(FILE* file);
  1250. // All command line arguments.
  1251. GTEST_API_ std::vector<std::string> GetArgvs();
  1252. #if GTEST_HAS_DEATH_TEST
  1253. std::vector<std::string> GetInjectableArgvs();
  1254. // Deprecated: pass the args vector by value instead.
  1255. void SetInjectableArgvs(const std::vector<std::string>* new_argvs);
  1256. void SetInjectableArgvs(const std::vector<std::string>& new_argvs);
  1257. void ClearInjectableArgvs();
  1258. #endif // GTEST_HAS_DEATH_TEST
  1259. // Defines synchronization primitives.
  1260. #if GTEST_IS_THREADSAFE
  1261. # if GTEST_HAS_PTHREAD
  1262. // Sleeps for (roughly) n milliseconds. This function is only for testing
  1263. // Google Test's own constructs. Don't use it in user tests, either
  1264. // directly or indirectly.
  1265. inline void SleepMilliseconds(int n) {
  1266. const timespec time = {
  1267. 0, // 0 seconds.
  1268. n * 1000L * 1000L, // And n ms.
  1269. };
  1270. nanosleep(&time, nullptr);
  1271. }
  1272. # endif // GTEST_HAS_PTHREAD
  1273. # if GTEST_HAS_NOTIFICATION_
  1274. // Notification has already been imported into the namespace.
  1275. // Nothing to do here.
  1276. # elif GTEST_HAS_PTHREAD
  1277. // Allows a controller thread to pause execution of newly created
  1278. // threads until notified. Instances of this class must be created
  1279. // and destroyed in the controller thread.
  1280. //
  1281. // This class is only for testing Google Test's own constructs. Do not
  1282. // use it in user tests, either directly or indirectly.
  1283. class Notification {
  1284. public:
  1285. Notification() : notified_(false) {
  1286. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
  1287. }
  1288. ~Notification() {
  1289. pthread_mutex_destroy(&mutex_);
  1290. }
  1291. // Notifies all threads created with this notification to start. Must
  1292. // be called from the controller thread.
  1293. void Notify() {
  1294. pthread_mutex_lock(&mutex_);
  1295. notified_ = true;
  1296. pthread_mutex_unlock(&mutex_);
  1297. }
  1298. // Blocks until the controller thread notifies. Must be called from a test
  1299. // thread.
  1300. void WaitForNotification() {
  1301. for (;;) {
  1302. pthread_mutex_lock(&mutex_);
  1303. const bool notified = notified_;
  1304. pthread_mutex_unlock(&mutex_);
  1305. if (notified)
  1306. break;
  1307. SleepMilliseconds(10);
  1308. }
  1309. }
  1310. private:
  1311. pthread_mutex_t mutex_;
  1312. bool notified_;
  1313. GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
  1314. };
  1315. # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  1316. GTEST_API_ void SleepMilliseconds(int n);
  1317. // Provides leak-safe Windows kernel handle ownership.
  1318. // Used in death tests and in threading support.
  1319. class GTEST_API_ AutoHandle {
  1320. public:
  1321. // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to
  1322. // avoid including <windows.h> in this header file. Including <windows.h> is
  1323. // undesirable because it defines a lot of symbols and macros that tend to
  1324. // conflict with client code. This assumption is verified by
  1325. // WindowsTypesTest.HANDLEIsVoidStar.
  1326. typedef void* Handle;
  1327. AutoHandle();
  1328. explicit AutoHandle(Handle handle);
  1329. ~AutoHandle();
  1330. Handle Get() const;
  1331. void Reset();
  1332. void Reset(Handle handle);
  1333. private:
  1334. // Returns true if and only if the handle is a valid handle object that can be
  1335. // closed.
  1336. bool IsCloseable() const;
  1337. Handle handle_;
  1338. GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
  1339. };
  1340. // Allows a controller thread to pause execution of newly created
  1341. // threads until notified. Instances of this class must be created
  1342. // and destroyed in the controller thread.
  1343. //
  1344. // This class is only for testing Google Test's own constructs. Do not
  1345. // use it in user tests, either directly or indirectly.
  1346. class GTEST_API_ Notification {
  1347. public:
  1348. Notification();
  1349. void Notify();
  1350. void WaitForNotification();
  1351. private:
  1352. AutoHandle event_;
  1353. GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
  1354. };
  1355. # endif // GTEST_HAS_NOTIFICATION_
  1356. // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
  1357. // defined, but we don't want to use MinGW's pthreads implementation, which
  1358. // has conformance problems with some versions of the POSIX standard.
  1359. # if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
  1360. // As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
  1361. // Consequently, it cannot select a correct instantiation of ThreadWithParam
  1362. // in order to call its Run(). Introducing ThreadWithParamBase as a
  1363. // non-templated base class for ThreadWithParam allows us to bypass this
  1364. // problem.
  1365. class ThreadWithParamBase {
  1366. public:
  1367. virtual ~ThreadWithParamBase() {}
  1368. virtual void Run() = 0;
  1369. };
  1370. // pthread_create() accepts a pointer to a function type with the C linkage.
  1371. // According to the Standard (7.5/1), function types with different linkages
  1372. // are different even if they are otherwise identical. Some compilers (for
  1373. // example, SunStudio) treat them as different types. Since class methods
  1374. // cannot be defined with C-linkage we need to define a free C-function to
  1375. // pass into pthread_create().
  1376. extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
  1377. static_cast<ThreadWithParamBase*>(thread)->Run();
  1378. return nullptr;
  1379. }
  1380. // Helper class for testing Google Test's multi-threading constructs.
  1381. // To use it, write:
  1382. //
  1383. // void ThreadFunc(int param) { /* Do things with param */ }
  1384. // Notification thread_can_start;
  1385. // ...
  1386. // // The thread_can_start parameter is optional; you can supply NULL.
  1387. // ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
  1388. // thread_can_start.Notify();
  1389. //
  1390. // These classes are only for testing Google Test's own constructs. Do
  1391. // not use them in user tests, either directly or indirectly.
  1392. template <typename T>
  1393. class ThreadWithParam : public ThreadWithParamBase {
  1394. public:
  1395. typedef void UserThreadFunc(T);
  1396. ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
  1397. : func_(func),
  1398. param_(param),
  1399. thread_can_start_(thread_can_start),
  1400. finished_(false) {
  1401. ThreadWithParamBase* const base = this;
  1402. // The thread can be created only after all fields except thread_
  1403. // have been initialized.
  1404. GTEST_CHECK_POSIX_SUCCESS_(
  1405. pthread_create(&thread_, nullptr, &ThreadFuncWithCLinkage, base));
  1406. }
  1407. ~ThreadWithParam() override { Join(); }
  1408. void Join() {
  1409. if (!finished_) {
  1410. GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, nullptr));
  1411. finished_ = true;
  1412. }
  1413. }
  1414. void Run() override {
  1415. if (thread_can_start_ != nullptr) thread_can_start_->WaitForNotification();
  1416. func_(param_);
  1417. }
  1418. private:
  1419. UserThreadFunc* const func_; // User-supplied thread function.
  1420. const T param_; // User-supplied parameter to the thread function.
  1421. // When non-NULL, used to block execution until the controller thread
  1422. // notifies.
  1423. Notification* const thread_can_start_;
  1424. bool finished_; // true if and only if we know that the thread function has
  1425. // finished.
  1426. pthread_t thread_; // The native thread object.
  1427. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
  1428. };
  1429. # endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD ||
  1430. // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
  1431. # if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
  1432. // Mutex and ThreadLocal have already been imported into the namespace.
  1433. // Nothing to do here.
  1434. # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  1435. // Mutex implements mutex on Windows platforms. It is used in conjunction
  1436. // with class MutexLock:
  1437. //
  1438. // Mutex mutex;
  1439. // ...
  1440. // MutexLock lock(&mutex); // Acquires the mutex and releases it at the
  1441. // // end of the current scope.
  1442. //
  1443. // A static Mutex *must* be defined or declared using one of the following
  1444. // macros:
  1445. // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
  1446. // GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
  1447. //
  1448. // (A non-static Mutex is defined/declared in the usual way).
  1449. class GTEST_API_ Mutex {
  1450. public:
  1451. enum MutexType { kStatic = 0, kDynamic = 1 };
  1452. // We rely on kStaticMutex being 0 as it is to what the linker initializes
  1453. // type_ in static mutexes. critical_section_ will be initialized lazily
  1454. // in ThreadSafeLazyInit().
  1455. enum StaticConstructorSelector { kStaticMutex = 0 };
  1456. // This constructor intentionally does nothing. It relies on type_ being
  1457. // statically initialized to 0 (effectively setting it to kStatic) and on
  1458. // ThreadSafeLazyInit() to lazily initialize the rest of the members.
  1459. explicit Mutex(StaticConstructorSelector /*dummy*/) {}
  1460. Mutex();
  1461. ~Mutex();
  1462. void Lock();
  1463. void Unlock();
  1464. // Does nothing if the current thread holds the mutex. Otherwise, crashes
  1465. // with high probability.
  1466. void AssertHeld();
  1467. private:
  1468. // Initializes owner_thread_id_ and critical_section_ in static mutexes.
  1469. void ThreadSafeLazyInit();
  1470. // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503,
  1471. // we assume that 0 is an invalid value for thread IDs.
  1472. unsigned int owner_thread_id_;
  1473. // For static mutexes, we rely on these members being initialized to zeros
  1474. // by the linker.
  1475. MutexType type_;
  1476. long critical_section_init_phase_; // NOLINT
  1477. GTEST_CRITICAL_SECTION* critical_section_;
  1478. GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
  1479. };
  1480. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
  1481. extern ::testing::internal::Mutex mutex
  1482. # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
  1483. ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)
  1484. // We cannot name this class MutexLock because the ctor declaration would
  1485. // conflict with a macro named MutexLock, which is defined on some
  1486. // platforms. That macro is used as a defensive measure to prevent against
  1487. // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
  1488. // "MutexLock l(&mu)". Hence the typedef trick below.
  1489. class GTestMutexLock {
  1490. public:
  1491. explicit GTestMutexLock(Mutex* mutex)
  1492. : mutex_(mutex) { mutex_->Lock(); }
  1493. ~GTestMutexLock() { mutex_->Unlock(); }
  1494. private:
  1495. Mutex* const mutex_;
  1496. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
  1497. };
  1498. typedef GTestMutexLock MutexLock;
  1499. // Base class for ValueHolder<T>. Allows a caller to hold and delete a value
  1500. // without knowing its type.
  1501. class ThreadLocalValueHolderBase {
  1502. public:
  1503. virtual ~ThreadLocalValueHolderBase() {}
  1504. };
  1505. // Provides a way for a thread to send notifications to a ThreadLocal
  1506. // regardless of its parameter type.
  1507. class ThreadLocalBase {
  1508. public:
  1509. // Creates a new ValueHolder<T> object holding a default value passed to
  1510. // this ThreadLocal<T>'s constructor and returns it. It is the caller's
  1511. // responsibility not to call this when the ThreadLocal<T> instance already
  1512. // has a value on the current thread.
  1513. virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0;
  1514. protected:
  1515. ThreadLocalBase() {}
  1516. virtual ~ThreadLocalBase() {}
  1517. private:
  1518. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase);
  1519. };
  1520. // Maps a thread to a set of ThreadLocals that have values instantiated on that
  1521. // thread and notifies them when the thread exits. A ThreadLocal instance is
  1522. // expected to persist until all threads it has values on have terminated.
  1523. class GTEST_API_ ThreadLocalRegistry {
  1524. public:
  1525. // Registers thread_local_instance as having value on the current thread.
  1526. // Returns a value that can be used to identify the thread from other threads.
  1527. static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
  1528. const ThreadLocalBase* thread_local_instance);
  1529. // Invoked when a ThreadLocal instance is destroyed.
  1530. static void OnThreadLocalDestroyed(
  1531. const ThreadLocalBase* thread_local_instance);
  1532. };
  1533. class GTEST_API_ ThreadWithParamBase {
  1534. public:
  1535. void Join();
  1536. protected:
  1537. class Runnable {
  1538. public:
  1539. virtual ~Runnable() {}
  1540. virtual void Run() = 0;
  1541. };
  1542. ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start);
  1543. virtual ~ThreadWithParamBase();
  1544. private:
  1545. AutoHandle thread_;
  1546. };
  1547. // Helper class for testing Google Test's multi-threading constructs.
  1548. template <typename T>
  1549. class ThreadWithParam : public ThreadWithParamBase {
  1550. public:
  1551. typedef void UserThreadFunc(T);
  1552. ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
  1553. : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {
  1554. }
  1555. virtual ~ThreadWithParam() {}
  1556. private:
  1557. class RunnableImpl : public Runnable {
  1558. public:
  1559. RunnableImpl(UserThreadFunc* func, T param)
  1560. : func_(func),
  1561. param_(param) {
  1562. }
  1563. virtual ~RunnableImpl() {}
  1564. virtual void Run() {
  1565. func_(param_);
  1566. }
  1567. private:
  1568. UserThreadFunc* const func_;
  1569. const T param_;
  1570. GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl);
  1571. };
  1572. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
  1573. };
  1574. // Implements thread-local storage on Windows systems.
  1575. //
  1576. // // Thread 1
  1577. // ThreadLocal<int> tl(100); // 100 is the default value for each thread.
  1578. //
  1579. // // Thread 2
  1580. // tl.set(150); // Changes the value for thread 2 only.
  1581. // EXPECT_EQ(150, tl.get());
  1582. //
  1583. // // Thread 1
  1584. // EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value.
  1585. // tl.set(200);
  1586. // EXPECT_EQ(200, tl.get());
  1587. //
  1588. // The template type argument T must have a public copy constructor.
  1589. // In addition, the default ThreadLocal constructor requires T to have
  1590. // a public default constructor.
  1591. //
  1592. // The users of a TheadLocal instance have to make sure that all but one
  1593. // threads (including the main one) using that instance have exited before
  1594. // destroying it. Otherwise, the per-thread objects managed for them by the
  1595. // ThreadLocal instance are not guaranteed to be destroyed on all platforms.
  1596. //
  1597. // Google Test only uses global ThreadLocal objects. That means they
  1598. // will die after main() has returned. Therefore, no per-thread
  1599. // object managed by Google Test will be leaked as long as all threads
  1600. // using Google Test have exited when main() returns.
  1601. template <typename T>
  1602. class ThreadLocal : public ThreadLocalBase {
  1603. public:
  1604. ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {}
  1605. explicit ThreadLocal(const T& value)
  1606. : default_factory_(new InstanceValueHolderFactory(value)) {}
  1607. ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }
  1608. T* pointer() { return GetOrCreateValue(); }
  1609. const T* pointer() const { return GetOrCreateValue(); }
  1610. const T& get() const { return *pointer(); }
  1611. void set(const T& value) { *pointer() = value; }
  1612. private:
  1613. // Holds a value of T. Can be deleted via its base class without the caller
  1614. // knowing the type of T.
  1615. class ValueHolder : public ThreadLocalValueHolderBase {
  1616. public:
  1617. ValueHolder() : value_() {}
  1618. explicit ValueHolder(const T& value) : value_(value) {}
  1619. T* pointer() { return &value_; }
  1620. private:
  1621. T value_;
  1622. GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
  1623. };
  1624. T* GetOrCreateValue() const {
  1625. return static_cast<ValueHolder*>(
  1626. ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer();
  1627. }
  1628. virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const {
  1629. return default_factory_->MakeNewHolder();
  1630. }
  1631. class ValueHolderFactory {
  1632. public:
  1633. ValueHolderFactory() {}
  1634. virtual ~ValueHolderFactory() {}
  1635. virtual ValueHolder* MakeNewHolder() const = 0;
  1636. private:
  1637. GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
  1638. };
  1639. class DefaultValueHolderFactory : public ValueHolderFactory {
  1640. public:
  1641. DefaultValueHolderFactory() {}
  1642. ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
  1643. private:
  1644. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
  1645. };
  1646. class InstanceValueHolderFactory : public ValueHolderFactory {
  1647. public:
  1648. explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
  1649. ValueHolder* MakeNewHolder() const override {
  1650. return new ValueHolder(value_);
  1651. }
  1652. private:
  1653. const T value_; // The value for each thread.
  1654. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
  1655. };
  1656. std::unique_ptr<ValueHolderFactory> default_factory_;
  1657. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
  1658. };
  1659. # elif GTEST_HAS_PTHREAD
  1660. // MutexBase and Mutex implement mutex on pthreads-based platforms.
  1661. class MutexBase {
  1662. public:
  1663. // Acquires this mutex.
  1664. void Lock() {
  1665. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
  1666. owner_ = pthread_self();
  1667. has_owner_ = true;
  1668. }
  1669. // Releases this mutex.
  1670. void Unlock() {
  1671. // Since the lock is being released the owner_ field should no longer be
  1672. // considered valid. We don't protect writing to has_owner_ here, as it's
  1673. // the caller's responsibility to ensure that the current thread holds the
  1674. // mutex when this is called.
  1675. has_owner_ = false;
  1676. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
  1677. }
  1678. // Does nothing if the current thread holds the mutex. Otherwise, crashes
  1679. // with high probability.
  1680. void AssertHeld() const {
  1681. GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))
  1682. << "The current thread is not holding the mutex @" << this;
  1683. }
  1684. // A static mutex may be used before main() is entered. It may even
  1685. // be used before the dynamic initialization stage. Therefore we
  1686. // must be able to initialize a static mutex object at link time.
  1687. // This means MutexBase has to be a POD and its member variables
  1688. // have to be public.
  1689. public:
  1690. pthread_mutex_t mutex_; // The underlying pthread mutex.
  1691. // has_owner_ indicates whether the owner_ field below contains a valid thread
  1692. // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All
  1693. // accesses to the owner_ field should be protected by a check of this field.
  1694. // An alternative might be to memset() owner_ to all zeros, but there's no
  1695. // guarantee that a zero'd pthread_t is necessarily invalid or even different
  1696. // from pthread_self().
  1697. bool has_owner_;
  1698. pthread_t owner_; // The thread holding the mutex.
  1699. };
  1700. // Forward-declares a static mutex.
  1701. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
  1702. extern ::testing::internal::MutexBase mutex
  1703. // Defines and statically (i.e. at link time) initializes a static mutex.
  1704. // The initialization list here does not explicitly initialize each field,
  1705. // instead relying on default initialization for the unspecified fields. In
  1706. // particular, the owner_ field (a pthread_t) is not explicitly initialized.
  1707. // This allows initialization to work whether pthread_t is a scalar or struct.
  1708. // The flag -Wmissing-field-initializers must not be specified for this to work.
  1709. #define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
  1710. ::testing::internal::MutexBase mutex = {PTHREAD_MUTEX_INITIALIZER, false, 0}
  1711. // The Mutex class can only be used for mutexes created at runtime. It
  1712. // shares its API with MutexBase otherwise.
  1713. class Mutex : public MutexBase {
  1714. public:
  1715. Mutex() {
  1716. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
  1717. has_owner_ = false;
  1718. }
  1719. ~Mutex() {
  1720. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
  1721. }
  1722. private:
  1723. GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
  1724. };
  1725. // We cannot name this class MutexLock because the ctor declaration would
  1726. // conflict with a macro named MutexLock, which is defined on some
  1727. // platforms. That macro is used as a defensive measure to prevent against
  1728. // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
  1729. // "MutexLock l(&mu)". Hence the typedef trick below.
  1730. class GTestMutexLock {
  1731. public:
  1732. explicit GTestMutexLock(MutexBase* mutex)
  1733. : mutex_(mutex) { mutex_->Lock(); }
  1734. ~GTestMutexLock() { mutex_->Unlock(); }
  1735. private:
  1736. MutexBase* const mutex_;
  1737. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
  1738. };
  1739. typedef GTestMutexLock MutexLock;
  1740. // Helpers for ThreadLocal.
  1741. // pthread_key_create() requires DeleteThreadLocalValue() to have
  1742. // C-linkage. Therefore it cannot be templatized to access
  1743. // ThreadLocal<T>. Hence the need for class
  1744. // ThreadLocalValueHolderBase.
  1745. class ThreadLocalValueHolderBase {
  1746. public:
  1747. virtual ~ThreadLocalValueHolderBase() {}
  1748. };
  1749. // Called by pthread to delete thread-local data stored by
  1750. // pthread_setspecific().
  1751. extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
  1752. delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
  1753. }
  1754. // Implements thread-local storage on pthreads-based systems.
  1755. template <typename T>
  1756. class GTEST_API_ ThreadLocal {
  1757. public:
  1758. ThreadLocal()
  1759. : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {}
  1760. explicit ThreadLocal(const T& value)
  1761. : key_(CreateKey()),
  1762. default_factory_(new InstanceValueHolderFactory(value)) {}
  1763. ~ThreadLocal() {
  1764. // Destroys the managed object for the current thread, if any.
  1765. DeleteThreadLocalValue(pthread_getspecific(key_));
  1766. // Releases resources associated with the key. This will *not*
  1767. // delete managed objects for other threads.
  1768. GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
  1769. }
  1770. T* pointer() { return GetOrCreateValue(); }
  1771. const T* pointer() const { return GetOrCreateValue(); }
  1772. const T& get() const { return *pointer(); }
  1773. void set(const T& value) { *pointer() = value; }
  1774. private:
  1775. // Holds a value of type T.
  1776. class ValueHolder : public ThreadLocalValueHolderBase {
  1777. public:
  1778. ValueHolder() : value_() {}
  1779. explicit ValueHolder(const T& value) : value_(value) {}
  1780. T* pointer() { return &value_; }
  1781. private:
  1782. T value_;
  1783. GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
  1784. };
  1785. static pthread_key_t CreateKey() {
  1786. pthread_key_t key;
  1787. // When a thread exits, DeleteThreadLocalValue() will be called on
  1788. // the object managed for that thread.
  1789. GTEST_CHECK_POSIX_SUCCESS_(
  1790. pthread_key_create(&key, &DeleteThreadLocalValue));
  1791. return key;
  1792. }
  1793. T* GetOrCreateValue() const {
  1794. ThreadLocalValueHolderBase* const holder =
  1795. static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
  1796. if (holder != nullptr) {
  1797. return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
  1798. }
  1799. ValueHolder* const new_holder = default_factory_->MakeNewHolder();
  1800. ThreadLocalValueHolderBase* const holder_base = new_holder;
  1801. GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
  1802. return new_holder->pointer();
  1803. }
  1804. class ValueHolderFactory {
  1805. public:
  1806. ValueHolderFactory() {}
  1807. virtual ~ValueHolderFactory() {}
  1808. virtual ValueHolder* MakeNewHolder() const = 0;
  1809. private:
  1810. GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
  1811. };
  1812. class DefaultValueHolderFactory : public ValueHolderFactory {
  1813. public:
  1814. DefaultValueHolderFactory() {}
  1815. ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
  1816. private:
  1817. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
  1818. };
  1819. class InstanceValueHolderFactory : public ValueHolderFactory {
  1820. public:
  1821. explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
  1822. ValueHolder* MakeNewHolder() const override {
  1823. return new ValueHolder(value_);
  1824. }
  1825. private:
  1826. const T value_; // The value for each thread.
  1827. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
  1828. };
  1829. // A key pthreads uses for looking up per-thread values.
  1830. const pthread_key_t key_;
  1831. std::unique_ptr<ValueHolderFactory> default_factory_;
  1832. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
  1833. };
  1834. # endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
  1835. #else // GTEST_IS_THREADSAFE
  1836. // A dummy implementation of synchronization primitives (mutex, lock,
  1837. // and thread-local variable). Necessary for compiling Google Test where
  1838. // mutex is not supported - using Google Test in multiple threads is not
  1839. // supported on such platforms.
  1840. class Mutex {
  1841. public:
  1842. Mutex() {}
  1843. void Lock() {}
  1844. void Unlock() {}
  1845. void AssertHeld() const {}
  1846. };
  1847. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
  1848. extern ::testing::internal::Mutex mutex
  1849. # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
  1850. // We cannot name this class MutexLock because the ctor declaration would
  1851. // conflict with a macro named MutexLock, which is defined on some
  1852. // platforms. That macro is used as a defensive measure to prevent against
  1853. // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
  1854. // "MutexLock l(&mu)". Hence the typedef trick below.
  1855. class GTestMutexLock {
  1856. public:
  1857. explicit GTestMutexLock(Mutex*) {} // NOLINT
  1858. };
  1859. typedef GTestMutexLock MutexLock;
  1860. template <typename T>
  1861. class GTEST_API_ ThreadLocal {
  1862. public:
  1863. ThreadLocal() : value_() {}
  1864. explicit ThreadLocal(const T& value) : value_(value) {}
  1865. T* pointer() { return &value_; }
  1866. const T* pointer() const { return &value_; }
  1867. const T& get() const { return value_; }
  1868. void set(const T& value) { value_ = value; }
  1869. private:
  1870. T value_;
  1871. };
  1872. #endif // GTEST_IS_THREADSAFE
  1873. // Returns the number of threads running in the process, or 0 to indicate that
  1874. // we cannot detect it.
  1875. GTEST_API_ size_t GetThreadCount();
  1876. #if GTEST_OS_WINDOWS
  1877. # define GTEST_PATH_SEP_ "\\"
  1878. # define GTEST_HAS_ALT_PATH_SEP_ 1
  1879. #else
  1880. # define GTEST_PATH_SEP_ "/"
  1881. # define GTEST_HAS_ALT_PATH_SEP_ 0
  1882. #endif // GTEST_OS_WINDOWS
  1883. // Utilities for char.
  1884. // isspace(int ch) and friends accept an unsigned char or EOF. char
  1885. // may be signed, depending on the compiler (or compiler flags).
  1886. // Therefore we need to cast a char to unsigned char before calling
  1887. // isspace(), etc.
  1888. inline bool IsAlpha(char ch) {
  1889. return isalpha(static_cast<unsigned char>(ch)) != 0;
  1890. }
  1891. inline bool IsAlNum(char ch) {
  1892. return isalnum(static_cast<unsigned char>(ch)) != 0;
  1893. }
  1894. inline bool IsDigit(char ch) {
  1895. return isdigit(static_cast<unsigned char>(ch)) != 0;
  1896. }
  1897. inline bool IsLower(char ch) {
  1898. return islower(static_cast<unsigned char>(ch)) != 0;
  1899. }
  1900. inline bool IsSpace(char ch) {
  1901. return isspace(static_cast<unsigned char>(ch)) != 0;
  1902. }
  1903. inline bool IsUpper(char ch) {
  1904. return isupper(static_cast<unsigned char>(ch)) != 0;
  1905. }
  1906. inline bool IsXDigit(char ch) {
  1907. return isxdigit(static_cast<unsigned char>(ch)) != 0;
  1908. }
  1909. #ifdef __cpp_char8_t
  1910. inline bool IsXDigit(char8_t ch) {
  1911. return isxdigit(static_cast<unsigned char>(ch)) != 0;
  1912. }
  1913. #endif
  1914. inline bool IsXDigit(char16_t ch) {
  1915. const unsigned char low_byte = static_cast<unsigned char>(ch);
  1916. return ch == low_byte && isxdigit(low_byte) != 0;
  1917. }
  1918. inline bool IsXDigit(char32_t ch) {
  1919. const unsigned char low_byte = static_cast<unsigned char>(ch);
  1920. return ch == low_byte && isxdigit(low_byte) != 0;
  1921. }
  1922. inline bool IsXDigit(wchar_t ch) {
  1923. const unsigned char low_byte = static_cast<unsigned char>(ch);
  1924. return ch == low_byte && isxdigit(low_byte) != 0;
  1925. }
  1926. inline char ToLower(char ch) {
  1927. return static_cast<char>(tolower(static_cast<unsigned char>(ch)));
  1928. }
  1929. inline char ToUpper(char ch) {
  1930. return static_cast<char>(toupper(static_cast<unsigned char>(ch)));
  1931. }
  1932. inline std::string StripTrailingSpaces(std::string str) {
  1933. std::string::iterator it = str.end();
  1934. while (it != str.begin() && IsSpace(*--it))
  1935. it = str.erase(it);
  1936. return str;
  1937. }
  1938. // The testing::internal::posix namespace holds wrappers for common
  1939. // POSIX functions. These wrappers hide the differences between
  1940. // Windows/MSVC and POSIX systems. Since some compilers define these
  1941. // standard functions as macros, the wrapper cannot have the same name
  1942. // as the wrapped function.
  1943. namespace posix {
  1944. // Functions with a different name on Windows.
  1945. #if GTEST_OS_WINDOWS
  1946. typedef struct _stat StatStruct;
  1947. # ifdef __BORLANDC__
  1948. inline int DoIsATTY(int fd) { return isatty(fd); }
  1949. inline int StrCaseCmp(const char* s1, const char* s2) {
  1950. return stricmp(s1, s2);
  1951. }
  1952. inline char* StrDup(const char* src) { return strdup(src); }
  1953. # else // !__BORLANDC__
  1954. # if GTEST_OS_WINDOWS_MOBILE
  1955. inline int DoIsATTY(int /* fd */) { return 0; }
  1956. # else
  1957. inline int DoIsATTY(int fd) { return _isatty(fd); }
  1958. # endif // GTEST_OS_WINDOWS_MOBILE
  1959. inline int StrCaseCmp(const char* s1, const char* s2) {
  1960. return _stricmp(s1, s2);
  1961. }
  1962. inline char* StrDup(const char* src) { return _strdup(src); }
  1963. # endif // __BORLANDC__
  1964. # if GTEST_OS_WINDOWS_MOBILE
  1965. inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
  1966. // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
  1967. // time and thus not defined there.
  1968. # else
  1969. inline int FileNo(FILE* file) { return _fileno(file); }
  1970. inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
  1971. inline int RmDir(const char* dir) { return _rmdir(dir); }
  1972. inline bool IsDir(const StatStruct& st) {
  1973. return (_S_IFDIR & st.st_mode) != 0;
  1974. }
  1975. # endif // GTEST_OS_WINDOWS_MOBILE
  1976. #elif GTEST_OS_ESP8266
  1977. typedef struct stat StatStruct;
  1978. inline int FileNo(FILE* file) { return fileno(file); }
  1979. inline int DoIsATTY(int fd) { return isatty(fd); }
  1980. inline int Stat(const char* path, StatStruct* buf) {
  1981. // stat function not implemented on ESP8266
  1982. return 0;
  1983. }
  1984. inline int StrCaseCmp(const char* s1, const char* s2) {
  1985. return strcasecmp(s1, s2);
  1986. }
  1987. inline char* StrDup(const char* src) { return strdup(src); }
  1988. inline int RmDir(const char* dir) { return rmdir(dir); }
  1989. inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
  1990. #else
  1991. typedef struct stat StatStruct;
  1992. inline int FileNo(FILE* file) { return fileno(file); }
  1993. inline int DoIsATTY(int fd) { return isatty(fd); }
  1994. inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
  1995. inline int StrCaseCmp(const char* s1, const char* s2) {
  1996. return strcasecmp(s1, s2);
  1997. }
  1998. inline char* StrDup(const char* src) { return strdup(src); }
  1999. inline int RmDir(const char* dir) { return rmdir(dir); }
  2000. inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
  2001. #endif // GTEST_OS_WINDOWS
  2002. inline int IsATTY(int fd) {
  2003. // DoIsATTY might change errno (for example ENOTTY in case you redirect stdout
  2004. // to a file on Linux), which is unexpected, so save the previous value, and
  2005. // restore it after the call.
  2006. int savedErrno = errno;
  2007. int isAttyValue = DoIsATTY(fd);
  2008. errno = savedErrno;
  2009. return isAttyValue;
  2010. }
  2011. // Functions deprecated by MSVC 8.0.
  2012. GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
  2013. // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
  2014. // StrError() aren't needed on Windows CE at this time and thus not
  2015. // defined there.
  2016. #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
  2017. !GTEST_OS_WINDOWS_RT && !GTEST_OS_ESP8266 && !GTEST_OS_XTENSA
  2018. inline int ChDir(const char* dir) { return chdir(dir); }
  2019. #endif
  2020. inline FILE* FOpen(const char* path, const char* mode) {
  2021. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
  2022. struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {};
  2023. std::wstring_convert<wchar_codecvt> converter;
  2024. std::wstring wide_path = converter.from_bytes(path);
  2025. std::wstring wide_mode = converter.from_bytes(mode);
  2026. return _wfopen(wide_path.c_str(), wide_mode.c_str());
  2027. #else // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
  2028. return fopen(path, mode);
  2029. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
  2030. }
  2031. #if !GTEST_OS_WINDOWS_MOBILE
  2032. inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
  2033. return freopen(path, mode, stream);
  2034. }
  2035. inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
  2036. #endif
  2037. inline int FClose(FILE* fp) { return fclose(fp); }
  2038. #if !GTEST_OS_WINDOWS_MOBILE
  2039. inline int Read(int fd, void* buf, unsigned int count) {
  2040. return static_cast<int>(read(fd, buf, count));
  2041. }
  2042. inline int Write(int fd, const void* buf, unsigned int count) {
  2043. return static_cast<int>(write(fd, buf, count));
  2044. }
  2045. inline int Close(int fd) { return close(fd); }
  2046. inline const char* StrError(int errnum) { return strerror(errnum); }
  2047. #endif
  2048. inline const char* GetEnv(const char* name) {
  2049. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
  2050. GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
  2051. // We are on an embedded platform, which has no environment variables.
  2052. static_cast<void>(name); // To prevent 'unused argument' warning.
  2053. return nullptr;
  2054. #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
  2055. // Environment variables which we programmatically clear will be set to the
  2056. // empty string rather than unset (NULL). Handle that case.
  2057. const char* const env = getenv(name);
  2058. return (env != nullptr && env[0] != '\0') ? env : nullptr;
  2059. #else
  2060. return getenv(name);
  2061. #endif
  2062. }
  2063. GTEST_DISABLE_MSC_DEPRECATED_POP_()
  2064. #if GTEST_OS_WINDOWS_MOBILE
  2065. // Windows CE has no C library. The abort() function is used in
  2066. // several places in Google Test. This implementation provides a reasonable
  2067. // imitation of standard behaviour.
  2068. [[noreturn]] void Abort();
  2069. #else
  2070. [[noreturn]] inline void Abort() { abort(); }
  2071. #endif // GTEST_OS_WINDOWS_MOBILE
  2072. } // namespace posix
  2073. // MSVC "deprecates" snprintf and issues warnings wherever it is used. In
  2074. // order to avoid these warnings, we need to use _snprintf or _snprintf_s on
  2075. // MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate
  2076. // function in order to achieve that. We use macro definition here because
  2077. // snprintf is a variadic function.
  2078. #if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE
  2079. // MSVC 2005 and above support variadic macros.
  2080. # define GTEST_SNPRINTF_(buffer, size, format, ...) \
  2081. _snprintf_s(buffer, size, size, format, __VA_ARGS__)
  2082. #elif defined(_MSC_VER)
  2083. // Windows CE does not define _snprintf_s
  2084. # define GTEST_SNPRINTF_ _snprintf
  2085. #else
  2086. # define GTEST_SNPRINTF_ snprintf
  2087. #endif
  2088. // The biggest signed integer type the compiler supports.
  2089. //
  2090. // long long is guaranteed to be at least 64-bits in C++11.
  2091. using BiggestInt = long long; // NOLINT
  2092. // The maximum number a BiggestInt can represent.
  2093. constexpr BiggestInt kMaxBiggestInt = (std::numeric_limits<BiggestInt>::max)();
  2094. // This template class serves as a compile-time function from size to
  2095. // type. It maps a size in bytes to a primitive type with that
  2096. // size. e.g.
  2097. //
  2098. // TypeWithSize<4>::UInt
  2099. //
  2100. // is typedef-ed to be unsigned int (unsigned integer made up of 4
  2101. // bytes).
  2102. //
  2103. // Such functionality should belong to STL, but I cannot find it
  2104. // there.
  2105. //
  2106. // Google Test uses this class in the implementation of floating-point
  2107. // comparison.
  2108. //
  2109. // For now it only handles UInt (unsigned int) as that's all Google Test
  2110. // needs. Other types can be easily added in the future if need
  2111. // arises.
  2112. template <size_t size>
  2113. class TypeWithSize {
  2114. public:
  2115. // This prevents the user from using TypeWithSize<N> with incorrect
  2116. // values of N.
  2117. using UInt = void;
  2118. };
  2119. // The specialization for size 4.
  2120. template <>
  2121. class TypeWithSize<4> {
  2122. public:
  2123. using Int = std::int32_t;
  2124. using UInt = std::uint32_t;
  2125. };
  2126. // The specialization for size 8.
  2127. template <>
  2128. class TypeWithSize<8> {
  2129. public:
  2130. using Int = std::int64_t;
  2131. using UInt = std::uint64_t;
  2132. };
  2133. // Integer types of known sizes.
  2134. using TimeInMillis = int64_t; // Represents time in milliseconds.
  2135. // Utilities for command line flags and environment variables.
  2136. // Macro for referencing flags.
  2137. #if !defined(GTEST_FLAG)
  2138. # define GTEST_FLAG(name) FLAGS_gtest_##name
  2139. #endif // !defined(GTEST_FLAG)
  2140. #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
  2141. # define GTEST_USE_OWN_FLAGFILE_FLAG_ 1
  2142. #endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
  2143. #if !defined(GTEST_DECLARE_bool_)
  2144. # define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver
  2145. // Macros for declaring flags.
  2146. # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
  2147. # define GTEST_DECLARE_int32_(name) \
  2148. GTEST_API_ extern std::int32_t GTEST_FLAG(name)
  2149. # define GTEST_DECLARE_string_(name) \
  2150. GTEST_API_ extern ::std::string GTEST_FLAG(name)
  2151. // Macros for defining flags.
  2152. # define GTEST_DEFINE_bool_(name, default_val, doc) \
  2153. GTEST_API_ bool GTEST_FLAG(name) = (default_val)
  2154. # define GTEST_DEFINE_int32_(name, default_val, doc) \
  2155. GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val)
  2156. # define GTEST_DEFINE_string_(name, default_val, doc) \
  2157. GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
  2158. #endif // !defined(GTEST_DECLARE_bool_)
  2159. // Thread annotations
  2160. #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
  2161. # define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
  2162. # define GTEST_LOCK_EXCLUDED_(locks)
  2163. #endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
  2164. // Parses 'str' for a 32-bit signed integer. If successful, writes the result
  2165. // to *value and returns true; otherwise leaves *value unchanged and returns
  2166. // false.
  2167. GTEST_API_ bool ParseInt32(const Message& src_text, const char* str,
  2168. int32_t* value);
  2169. // Parses a bool/int32_t/string from the environment variable
  2170. // corresponding to the given Google Test flag.
  2171. bool BoolFromGTestEnv(const char* flag, bool default_val);
  2172. GTEST_API_ int32_t Int32FromGTestEnv(const char* flag, int32_t default_val);
  2173. std::string OutputFlagAlsoCheckEnvVar();
  2174. const char* StringFromGTestEnv(const char* flag, const char* default_val);
  2175. } // namespace internal
  2176. } // namespace testing
  2177. #if !defined(GTEST_INTERNAL_DEPRECATED)
  2178. // Internal Macro to mark an API deprecated, for googletest usage only
  2179. // Usage: class GTEST_INTERNAL_DEPRECATED(message) MyClass or
  2180. // GTEST_INTERNAL_DEPRECATED(message) <return_type> myFunction(); Every usage of
  2181. // a deprecated entity will trigger a warning when compiled with
  2182. // `-Wdeprecated-declarations` option (clang, gcc, any __GNUC__ compiler).
  2183. // For msvc /W3 option will need to be used
  2184. // Note that for 'other' compilers this macro evaluates to nothing to prevent
  2185. // compilations errors.
  2186. #if defined(_MSC_VER)
  2187. #define GTEST_INTERNAL_DEPRECATED(message) __declspec(deprecated(message))
  2188. #elif defined(__GNUC__)
  2189. #define GTEST_INTERNAL_DEPRECATED(message) __attribute__((deprecated(message)))
  2190. #else
  2191. #define GTEST_INTERNAL_DEPRECATED(message)
  2192. #endif
  2193. #endif // !defined(GTEST_INTERNAL_DEPRECATED)
  2194. #if GTEST_HAS_ABSL
  2195. // Always use absl::any for UniversalPrinter<> specializations if googletest
  2196. // is built with absl support.
  2197. #define GTEST_INTERNAL_HAS_ANY 1
  2198. #include "absl/types/any.h"
  2199. namespace testing {
  2200. namespace internal {
  2201. using Any = ::absl::any;
  2202. } // namespace internal
  2203. } // namespace testing
  2204. #else
  2205. #ifdef __has_include
  2206. #if __has_include(<any>) && __cplusplus >= 201703L
  2207. // Otherwise for C++17 and higher use std::any for UniversalPrinter<>
  2208. // specializations.
  2209. #define GTEST_INTERNAL_HAS_ANY 1
  2210. #include <any>
  2211. namespace testing {
  2212. namespace internal {
  2213. using Any = ::std::any;
  2214. } // namespace internal
  2215. } // namespace testing
  2216. // The case where absl is configured NOT to alias std::any is not
  2217. // supported.
  2218. #endif // __has_include(<any>) && __cplusplus >= 201703L
  2219. #endif // __has_include
  2220. #endif // GTEST_HAS_ABSL
  2221. #if GTEST_HAS_ABSL
  2222. // Always use absl::optional for UniversalPrinter<> specializations if
  2223. // googletest is built with absl support.
  2224. #define GTEST_INTERNAL_HAS_OPTIONAL 1
  2225. #include "absl/types/optional.h"
  2226. namespace testing {
  2227. namespace internal {
  2228. template <typename T>
  2229. using Optional = ::absl::optional<T>;
  2230. } // namespace internal
  2231. } // namespace testing
  2232. #else
  2233. #ifdef __has_include
  2234. #if __has_include(<optional>) && __cplusplus >= 201703L
  2235. // Otherwise for C++17 and higher use std::optional for UniversalPrinter<>
  2236. // specializations.
  2237. #define GTEST_INTERNAL_HAS_OPTIONAL 1
  2238. #include <optional>
  2239. namespace testing {
  2240. namespace internal {
  2241. template <typename T>
  2242. using Optional = ::std::optional<T>;
  2243. } // namespace internal
  2244. } // namespace testing
  2245. // The case where absl is configured NOT to alias std::optional is not
  2246. // supported.
  2247. #endif // __has_include(<optional>) && __cplusplus >= 201703L
  2248. #endif // __has_include
  2249. #endif // GTEST_HAS_ABSL
  2250. #if GTEST_HAS_ABSL
  2251. // Always use absl::string_view for Matcher<> specializations if googletest
  2252. // is built with absl support.
  2253. # define GTEST_INTERNAL_HAS_STRING_VIEW 1
  2254. #include "absl/strings/string_view.h"
  2255. namespace testing {
  2256. namespace internal {
  2257. using StringView = ::absl::string_view;
  2258. } // namespace internal
  2259. } // namespace testing
  2260. #else
  2261. # ifdef __has_include
  2262. # if __has_include(<string_view>) && __cplusplus >= 201703L
  2263. // Otherwise for C++17 and higher use std::string_view for Matcher<>
  2264. // specializations.
  2265. # define GTEST_INTERNAL_HAS_STRING_VIEW 1
  2266. #include <string_view>
  2267. namespace testing {
  2268. namespace internal {
  2269. using StringView = ::std::string_view;
  2270. } // namespace internal
  2271. } // namespace testing
  2272. // The case where absl is configured NOT to alias std::string_view is not
  2273. // supported.
  2274. # endif // __has_include(<string_view>) && __cplusplus >= 201703L
  2275. # endif // __has_include
  2276. #endif // GTEST_HAS_ABSL
  2277. #if GTEST_HAS_ABSL
  2278. // Always use absl::variant for UniversalPrinter<> specializations if googletest
  2279. // is built with absl support.
  2280. #define GTEST_INTERNAL_HAS_VARIANT 1
  2281. #include "absl/types/variant.h"
  2282. namespace testing {
  2283. namespace internal {
  2284. template <typename... T>
  2285. using Variant = ::absl::variant<T...>;
  2286. } // namespace internal
  2287. } // namespace testing
  2288. #else
  2289. #ifdef __has_include
  2290. #if __has_include(<variant>) && __cplusplus >= 201703L
  2291. // Otherwise for C++17 and higher use std::variant for UniversalPrinter<>
  2292. // specializations.
  2293. #define GTEST_INTERNAL_HAS_VARIANT 1
  2294. #include <variant>
  2295. namespace testing {
  2296. namespace internal {
  2297. template <typename... T>
  2298. using Variant = ::std::variant<T...>;
  2299. } // namespace internal
  2300. } // namespace testing
  2301. // The case where absl is configured NOT to alias std::variant is not supported.
  2302. #endif // __has_include(<variant>) && __cplusplus >= 201703L
  2303. #endif // __has_include
  2304. #endif // GTEST_HAS_ABSL
  2305. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
  2306. #if GTEST_OS_LINUX
  2307. # include <stdlib.h>
  2308. # include <sys/types.h>
  2309. # include <sys/wait.h>
  2310. # include <unistd.h>
  2311. #endif // GTEST_OS_LINUX
  2312. #if GTEST_HAS_EXCEPTIONS
  2313. # include <stdexcept>
  2314. #endif
  2315. #include <ctype.h>
  2316. #include <float.h>
  2317. #include <string.h>
  2318. #include <cstdint>
  2319. #include <iomanip>
  2320. #include <limits>
  2321. #include <map>
  2322. #include <set>
  2323. #include <string>
  2324. #include <type_traits>
  2325. #include <vector>
  2326. // Copyright 2005, Google Inc.
  2327. // All rights reserved.
  2328. //
  2329. // Redistribution and use in source and binary forms, with or without
  2330. // modification, are permitted provided that the following conditions are
  2331. // met:
  2332. //
  2333. // * Redistributions of source code must retain the above copyright
  2334. // notice, this list of conditions and the following disclaimer.
  2335. // * Redistributions in binary form must reproduce the above
  2336. // copyright notice, this list of conditions and the following disclaimer
  2337. // in the documentation and/or other materials provided with the
  2338. // distribution.
  2339. // * Neither the name of Google Inc. nor the names of its
  2340. // contributors may be used to endorse or promote products derived from
  2341. // this software without specific prior written permission.
  2342. //
  2343. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2344. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2345. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2346. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2347. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2348. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2349. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2350. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2351. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2352. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2353. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2354. //
  2355. // The Google C++ Testing and Mocking Framework (Google Test)
  2356. //
  2357. // This header file defines the Message class.
  2358. //
  2359. // IMPORTANT NOTE: Due to limitation of the C++ language, we have to
  2360. // leave some internal implementation details in this header file.
  2361. // They are clearly marked by comments like this:
  2362. //
  2363. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  2364. //
  2365. // Such code is NOT meant to be used by a user directly, and is subject
  2366. // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
  2367. // program!
  2368. // GOOGLETEST_CM0001 DO NOT DELETE
  2369. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
  2370. #define GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
  2371. #include <limits>
  2372. #include <memory>
  2373. #include <sstream>
  2374. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  2375. /* class A needs to have dll-interface to be used by clients of class B */)
  2376. // Ensures that there is at least one operator<< in the global namespace.
  2377. // See Message& operator<<(...) below for why.
  2378. void operator<<(const testing::internal::Secret&, int);
  2379. namespace testing {
  2380. // The Message class works like an ostream repeater.
  2381. //
  2382. // Typical usage:
  2383. //
  2384. // 1. You stream a bunch of values to a Message object.
  2385. // It will remember the text in a stringstream.
  2386. // 2. Then you stream the Message object to an ostream.
  2387. // This causes the text in the Message to be streamed
  2388. // to the ostream.
  2389. //
  2390. // For example;
  2391. //
  2392. // testing::Message foo;
  2393. // foo << 1 << " != " << 2;
  2394. // std::cout << foo;
  2395. //
  2396. // will print "1 != 2".
  2397. //
  2398. // Message is not intended to be inherited from. In particular, its
  2399. // destructor is not virtual.
  2400. //
  2401. // Note that stringstream behaves differently in gcc and in MSVC. You
  2402. // can stream a NULL char pointer to it in the former, but not in the
  2403. // latter (it causes an access violation if you do). The Message
  2404. // class hides this difference by treating a NULL char pointer as
  2405. // "(null)".
  2406. class GTEST_API_ Message {
  2407. private:
  2408. // The type of basic IO manipulators (endl, ends, and flush) for
  2409. // narrow streams.
  2410. typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&);
  2411. public:
  2412. // Constructs an empty Message.
  2413. Message();
  2414. // Copy constructor.
  2415. Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT
  2416. *ss_ << msg.GetString();
  2417. }
  2418. // Constructs a Message from a C-string.
  2419. explicit Message(const char* str) : ss_(new ::std::stringstream) {
  2420. *ss_ << str;
  2421. }
  2422. // Streams a non-pointer value to this object.
  2423. template <typename T>
  2424. inline Message& operator <<(const T& val) {
  2425. // Some libraries overload << for STL containers. These
  2426. // overloads are defined in the global namespace instead of ::std.
  2427. //
  2428. // C++'s symbol lookup rule (i.e. Koenig lookup) says that these
  2429. // overloads are visible in either the std namespace or the global
  2430. // namespace, but not other namespaces, including the testing
  2431. // namespace which Google Test's Message class is in.
  2432. //
  2433. // To allow STL containers (and other types that has a << operator
  2434. // defined in the global namespace) to be used in Google Test
  2435. // assertions, testing::Message must access the custom << operator
  2436. // from the global namespace. With this using declaration,
  2437. // overloads of << defined in the global namespace and those
  2438. // visible via Koenig lookup are both exposed in this function.
  2439. using ::operator <<;
  2440. *ss_ << val;
  2441. return *this;
  2442. }
  2443. // Streams a pointer value to this object.
  2444. //
  2445. // This function is an overload of the previous one. When you
  2446. // stream a pointer to a Message, this definition will be used as it
  2447. // is more specialized. (The C++ Standard, section
  2448. // [temp.func.order].) If you stream a non-pointer, then the
  2449. // previous definition will be used.
  2450. //
  2451. // The reason for this overload is that streaming a NULL pointer to
  2452. // ostream is undefined behavior. Depending on the compiler, you
  2453. // may get "0", "(nil)", "(null)", or an access violation. To
  2454. // ensure consistent result across compilers, we always treat NULL
  2455. // as "(null)".
  2456. template <typename T>
  2457. inline Message& operator <<(T* const& pointer) { // NOLINT
  2458. if (pointer == nullptr) {
  2459. *ss_ << "(null)";
  2460. } else {
  2461. *ss_ << pointer;
  2462. }
  2463. return *this;
  2464. }
  2465. // Since the basic IO manipulators are overloaded for both narrow
  2466. // and wide streams, we have to provide this specialized definition
  2467. // of operator <<, even though its body is the same as the
  2468. // templatized version above. Without this definition, streaming
  2469. // endl or other basic IO manipulators to Message will confuse the
  2470. // compiler.
  2471. Message& operator <<(BasicNarrowIoManip val) {
  2472. *ss_ << val;
  2473. return *this;
  2474. }
  2475. // Instead of 1/0, we want to see true/false for bool values.
  2476. Message& operator <<(bool b) {
  2477. return *this << (b ? "true" : "false");
  2478. }
  2479. // These two overloads allow streaming a wide C string to a Message
  2480. // using the UTF-8 encoding.
  2481. Message& operator <<(const wchar_t* wide_c_str);
  2482. Message& operator <<(wchar_t* wide_c_str);
  2483. #if GTEST_HAS_STD_WSTRING
  2484. // Converts the given wide string to a narrow string using the UTF-8
  2485. // encoding, and streams the result to this Message object.
  2486. Message& operator <<(const ::std::wstring& wstr);
  2487. #endif // GTEST_HAS_STD_WSTRING
  2488. // Gets the text streamed to this object so far as an std::string.
  2489. // Each '\0' character in the buffer is replaced with "\\0".
  2490. //
  2491. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  2492. std::string GetString() const;
  2493. private:
  2494. // We'll hold the text streamed to this object here.
  2495. const std::unique_ptr< ::std::stringstream> ss_;
  2496. // We declare (but don't implement) this to prevent the compiler
  2497. // from implementing the assignment operator.
  2498. void operator=(const Message&);
  2499. };
  2500. // Streams a Message to an ostream.
  2501. inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
  2502. return os << sb.GetString();
  2503. }
  2504. namespace internal {
  2505. // Converts a streamable value to an std::string. A NULL pointer is
  2506. // converted to "(null)". When the input value is a ::string,
  2507. // ::std::string, ::wstring, or ::std::wstring object, each NUL
  2508. // character in it is replaced with "\\0".
  2509. template <typename T>
  2510. std::string StreamableToString(const T& streamable) {
  2511. return (Message() << streamable).GetString();
  2512. }
  2513. } // namespace internal
  2514. } // namespace testing
  2515. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  2516. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
  2517. // Copyright 2008, Google Inc.
  2518. // All rights reserved.
  2519. //
  2520. // Redistribution and use in source and binary forms, with or without
  2521. // modification, are permitted provided that the following conditions are
  2522. // met:
  2523. //
  2524. // * Redistributions of source code must retain the above copyright
  2525. // notice, this list of conditions and the following disclaimer.
  2526. // * Redistributions in binary form must reproduce the above
  2527. // copyright notice, this list of conditions and the following disclaimer
  2528. // in the documentation and/or other materials provided with the
  2529. // distribution.
  2530. // * Neither the name of Google Inc. nor the names of its
  2531. // contributors may be used to endorse or promote products derived from
  2532. // this software without specific prior written permission.
  2533. //
  2534. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2535. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2536. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2537. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2538. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2539. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2540. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2541. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2542. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2543. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2544. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2545. //
  2546. // Google Test filepath utilities
  2547. //
  2548. // This header file declares classes and functions used internally by
  2549. // Google Test. They are subject to change without notice.
  2550. //
  2551. // This file is #included in gtest/internal/gtest-internal.h.
  2552. // Do not include this header file separately!
  2553. // GOOGLETEST_CM0001 DO NOT DELETE
  2554. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
  2555. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
  2556. // Copyright 2005, Google Inc.
  2557. // All rights reserved.
  2558. //
  2559. // Redistribution and use in source and binary forms, with or without
  2560. // modification, are permitted provided that the following conditions are
  2561. // met:
  2562. //
  2563. // * Redistributions of source code must retain the above copyright
  2564. // notice, this list of conditions and the following disclaimer.
  2565. // * Redistributions in binary form must reproduce the above
  2566. // copyright notice, this list of conditions and the following disclaimer
  2567. // in the documentation and/or other materials provided with the
  2568. // distribution.
  2569. // * Neither the name of Google Inc. nor the names of its
  2570. // contributors may be used to endorse or promote products derived from
  2571. // this software without specific prior written permission.
  2572. //
  2573. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2574. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2575. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2576. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2577. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2578. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2579. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2580. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2581. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2582. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2583. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2584. //
  2585. // The Google C++ Testing and Mocking Framework (Google Test)
  2586. //
  2587. // This header file declares the String class and functions used internally by
  2588. // Google Test. They are subject to change without notice. They should not used
  2589. // by code external to Google Test.
  2590. //
  2591. // This header file is #included by gtest-internal.h.
  2592. // It should not be #included by other files.
  2593. // GOOGLETEST_CM0001 DO NOT DELETE
  2594. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
  2595. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
  2596. #ifdef __BORLANDC__
  2597. // string.h is not guaranteed to provide strcpy on C++ Builder.
  2598. # include <mem.h>
  2599. #endif
  2600. #include <string.h>
  2601. #include <cstdint>
  2602. #include <string>
  2603. namespace testing {
  2604. namespace internal {
  2605. // String - an abstract class holding static string utilities.
  2606. class GTEST_API_ String {
  2607. public:
  2608. // Static utility methods
  2609. // Clones a 0-terminated C string, allocating memory using new. The
  2610. // caller is responsible for deleting the return value using
  2611. // delete[]. Returns the cloned string, or NULL if the input is
  2612. // NULL.
  2613. //
  2614. // This is different from strdup() in string.h, which allocates
  2615. // memory using malloc().
  2616. static const char* CloneCString(const char* c_str);
  2617. #if GTEST_OS_WINDOWS_MOBILE
  2618. // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
  2619. // able to pass strings to Win32 APIs on CE we need to convert them
  2620. // to 'Unicode', UTF-16.
  2621. // Creates a UTF-16 wide string from the given ANSI string, allocating
  2622. // memory using new. The caller is responsible for deleting the return
  2623. // value using delete[]. Returns the wide string, or NULL if the
  2624. // input is NULL.
  2625. //
  2626. // The wide string is created using the ANSI codepage (CP_ACP) to
  2627. // match the behaviour of the ANSI versions of Win32 calls and the
  2628. // C runtime.
  2629. static LPCWSTR AnsiToUtf16(const char* c_str);
  2630. // Creates an ANSI string from the given wide string, allocating
  2631. // memory using new. The caller is responsible for deleting the return
  2632. // value using delete[]. Returns the ANSI string, or NULL if the
  2633. // input is NULL.
  2634. //
  2635. // The returned string is created using the ANSI codepage (CP_ACP) to
  2636. // match the behaviour of the ANSI versions of Win32 calls and the
  2637. // C runtime.
  2638. static const char* Utf16ToAnsi(LPCWSTR utf16_str);
  2639. #endif
  2640. // Compares two C strings. Returns true if and only if they have the same
  2641. // content.
  2642. //
  2643. // Unlike strcmp(), this function can handle NULL argument(s). A
  2644. // NULL C string is considered different to any non-NULL C string,
  2645. // including the empty string.
  2646. static bool CStringEquals(const char* lhs, const char* rhs);
  2647. // Converts a wide C string to a String using the UTF-8 encoding.
  2648. // NULL will be converted to "(null)". If an error occurred during
  2649. // the conversion, "(failed to convert from wide string)" is
  2650. // returned.
  2651. static std::string ShowWideCString(const wchar_t* wide_c_str);
  2652. // Compares two wide C strings. Returns true if and only if they have the
  2653. // same content.
  2654. //
  2655. // Unlike wcscmp(), this function can handle NULL argument(s). A
  2656. // NULL C string is considered different to any non-NULL C string,
  2657. // including the empty string.
  2658. static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
  2659. // Compares two C strings, ignoring case. Returns true if and only if
  2660. // they have the same content.
  2661. //
  2662. // Unlike strcasecmp(), this function can handle NULL argument(s).
  2663. // A NULL C string is considered different to any non-NULL C string,
  2664. // including the empty string.
  2665. static bool CaseInsensitiveCStringEquals(const char* lhs,
  2666. const char* rhs);
  2667. // Compares two wide C strings, ignoring case. Returns true if and only if
  2668. // they have the same content.
  2669. //
  2670. // Unlike wcscasecmp(), this function can handle NULL argument(s).
  2671. // A NULL C string is considered different to any non-NULL wide C string,
  2672. // including the empty string.
  2673. // NB: The implementations on different platforms slightly differ.
  2674. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  2675. // environment variable. On GNU platform this method uses wcscasecmp
  2676. // which compares according to LC_CTYPE category of the current locale.
  2677. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  2678. // current locale.
  2679. static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  2680. const wchar_t* rhs);
  2681. // Returns true if and only if the given string ends with the given suffix,
  2682. // ignoring case. Any string is considered to end with an empty suffix.
  2683. static bool EndsWithCaseInsensitive(
  2684. const std::string& str, const std::string& suffix);
  2685. // Formats an int value as "%02d".
  2686. static std::string FormatIntWidth2(int value); // "%02d" for width == 2
  2687. // Formats an int value to given width with leading zeros.
  2688. static std::string FormatIntWidthN(int value, int width);
  2689. // Formats an int value as "%X".
  2690. static std::string FormatHexInt(int value);
  2691. // Formats an int value as "%X".
  2692. static std::string FormatHexUInt32(uint32_t value);
  2693. // Formats a byte as "%02X".
  2694. static std::string FormatByte(unsigned char value);
  2695. private:
  2696. String(); // Not meant to be instantiated.
  2697. }; // class String
  2698. // Gets the content of the stringstream's buffer as an std::string. Each '\0'
  2699. // character in the buffer is replaced with "\\0".
  2700. GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
  2701. } // namespace internal
  2702. } // namespace testing
  2703. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
  2704. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  2705. /* class A needs to have dll-interface to be used by clients of class B */)
  2706. namespace testing {
  2707. namespace internal {
  2708. // FilePath - a class for file and directory pathname manipulation which
  2709. // handles platform-specific conventions (like the pathname separator).
  2710. // Used for helper functions for naming files in a directory for xml output.
  2711. // Except for Set methods, all methods are const or static, which provides an
  2712. // "immutable value object" -- useful for peace of mind.
  2713. // A FilePath with a value ending in a path separator ("like/this/") represents
  2714. // a directory, otherwise it is assumed to represent a file. In either case,
  2715. // it may or may not represent an actual file or directory in the file system.
  2716. // Names are NOT checked for syntax correctness -- no checking for illegal
  2717. // characters, malformed paths, etc.
  2718. class GTEST_API_ FilePath {
  2719. public:
  2720. FilePath() : pathname_("") { }
  2721. FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
  2722. explicit FilePath(const std::string& pathname) : pathname_(pathname) {
  2723. Normalize();
  2724. }
  2725. FilePath& operator=(const FilePath& rhs) {
  2726. Set(rhs);
  2727. return *this;
  2728. }
  2729. void Set(const FilePath& rhs) {
  2730. pathname_ = rhs.pathname_;
  2731. }
  2732. const std::string& string() const { return pathname_; }
  2733. const char* c_str() const { return pathname_.c_str(); }
  2734. // Returns the current working directory, or "" if unsuccessful.
  2735. static FilePath GetCurrentDir();
  2736. // Given directory = "dir", base_name = "test", number = 0,
  2737. // extension = "xml", returns "dir/test.xml". If number is greater
  2738. // than zero (e.g., 12), returns "dir/test_12.xml".
  2739. // On Windows platform, uses \ as the separator rather than /.
  2740. static FilePath MakeFileName(const FilePath& directory,
  2741. const FilePath& base_name,
  2742. int number,
  2743. const char* extension);
  2744. // Given directory = "dir", relative_path = "test.xml",
  2745. // returns "dir/test.xml".
  2746. // On Windows, uses \ as the separator rather than /.
  2747. static FilePath ConcatPaths(const FilePath& directory,
  2748. const FilePath& relative_path);
  2749. // Returns a pathname for a file that does not currently exist. The pathname
  2750. // will be directory/base_name.extension or
  2751. // directory/base_name_<number>.extension if directory/base_name.extension
  2752. // already exists. The number will be incremented until a pathname is found
  2753. // that does not already exist.
  2754. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
  2755. // There could be a race condition if two or more processes are calling this
  2756. // function at the same time -- they could both pick the same filename.
  2757. static FilePath GenerateUniqueFileName(const FilePath& directory,
  2758. const FilePath& base_name,
  2759. const char* extension);
  2760. // Returns true if and only if the path is "".
  2761. bool IsEmpty() const { return pathname_.empty(); }
  2762. // If input name has a trailing separator character, removes it and returns
  2763. // the name, otherwise return the name string unmodified.
  2764. // On Windows platform, uses \ as the separator, other platforms use /.
  2765. FilePath RemoveTrailingPathSeparator() const;
  2766. // Returns a copy of the FilePath with the directory part removed.
  2767. // Example: FilePath("path/to/file").RemoveDirectoryName() returns
  2768. // FilePath("file"). If there is no directory part ("just_a_file"), it returns
  2769. // the FilePath unmodified. If there is no file part ("just_a_dir/") it
  2770. // returns an empty FilePath ("").
  2771. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  2772. FilePath RemoveDirectoryName() const;
  2773. // RemoveFileName returns the directory path with the filename removed.
  2774. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
  2775. // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
  2776. // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
  2777. // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
  2778. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  2779. FilePath RemoveFileName() const;
  2780. // Returns a copy of the FilePath with the case-insensitive extension removed.
  2781. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
  2782. // FilePath("dir/file"). If a case-insensitive extension is not
  2783. // found, returns a copy of the original FilePath.
  2784. FilePath RemoveExtension(const char* extension) const;
  2785. // Creates directories so that path exists. Returns true if successful or if
  2786. // the directories already exist; returns false if unable to create
  2787. // directories for any reason. Will also return false if the FilePath does
  2788. // not represent a directory (that is, it doesn't end with a path separator).
  2789. bool CreateDirectoriesRecursively() const;
  2790. // Create the directory so that path exists. Returns true if successful or
  2791. // if the directory already exists; returns false if unable to create the
  2792. // directory for any reason, including if the parent directory does not
  2793. // exist. Not named "CreateDirectory" because that's a macro on Windows.
  2794. bool CreateFolder() const;
  2795. // Returns true if FilePath describes something in the file-system,
  2796. // either a file, directory, or whatever, and that something exists.
  2797. bool FileOrDirectoryExists() const;
  2798. // Returns true if pathname describes a directory in the file-system
  2799. // that exists.
  2800. bool DirectoryExists() const;
  2801. // Returns true if FilePath ends with a path separator, which indicates that
  2802. // it is intended to represent a directory. Returns false otherwise.
  2803. // This does NOT check that a directory (or file) actually exists.
  2804. bool IsDirectory() const;
  2805. // Returns true if pathname describes a root directory. (Windows has one
  2806. // root directory per disk drive.)
  2807. bool IsRootDirectory() const;
  2808. // Returns true if pathname describes an absolute path.
  2809. bool IsAbsolutePath() const;
  2810. private:
  2811. // Replaces multiple consecutive separators with a single separator.
  2812. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
  2813. // redundancies that might be in a pathname involving "." or "..".
  2814. //
  2815. // A pathname with multiple consecutive separators may occur either through
  2816. // user error or as a result of some scripts or APIs that generate a pathname
  2817. // with a trailing separator. On other platforms the same API or script
  2818. // may NOT generate a pathname with a trailing "/". Then elsewhere that
  2819. // pathname may have another "/" and pathname components added to it,
  2820. // without checking for the separator already being there.
  2821. // The script language and operating system may allow paths like "foo//bar"
  2822. // but some of the functions in FilePath will not handle that correctly. In
  2823. // particular, RemoveTrailingPathSeparator() only removes one separator, and
  2824. // it is called in CreateDirectoriesRecursively() assuming that it will change
  2825. // a pathname from directory syntax (trailing separator) to filename syntax.
  2826. //
  2827. // On Windows this method also replaces the alternate path separator '/' with
  2828. // the primary path separator '\\', so that for example "bar\\/\\foo" becomes
  2829. // "bar\\foo".
  2830. void Normalize();
  2831. // Returns a pointer to the last occurrence of a valid path separator in
  2832. // the FilePath. On Windows, for example, both '/' and '\' are valid path
  2833. // separators. Returns NULL if no path separator was found.
  2834. const char* FindLastPathSeparator() const;
  2835. std::string pathname_;
  2836. }; // class FilePath
  2837. } // namespace internal
  2838. } // namespace testing
  2839. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  2840. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
  2841. // Copyright 2008 Google Inc.
  2842. // All Rights Reserved.
  2843. //
  2844. // Redistribution and use in source and binary forms, with or without
  2845. // modification, are permitted provided that the following conditions are
  2846. // met:
  2847. //
  2848. // * Redistributions of source code must retain the above copyright
  2849. // notice, this list of conditions and the following disclaimer.
  2850. // * Redistributions in binary form must reproduce the above
  2851. // copyright notice, this list of conditions and the following disclaimer
  2852. // in the documentation and/or other materials provided with the
  2853. // distribution.
  2854. // * Neither the name of Google Inc. nor the names of its
  2855. // contributors may be used to endorse or promote products derived from
  2856. // this software without specific prior written permission.
  2857. //
  2858. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2859. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2860. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2861. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2862. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2863. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2864. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2865. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2866. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2867. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2868. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2869. // Type utilities needed for implementing typed and type-parameterized
  2870. // tests.
  2871. // GOOGLETEST_CM0001 DO NOT DELETE
  2872. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
  2873. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
  2874. // #ifdef __GNUC__ is too general here. It is possible to use gcc without using
  2875. // libstdc++ (which is where cxxabi.h comes from).
  2876. # if GTEST_HAS_CXXABI_H_
  2877. # include <cxxabi.h>
  2878. # elif defined(__HP_aCC)
  2879. # include <acxx_demangle.h>
  2880. # endif // GTEST_HASH_CXXABI_H_
  2881. namespace testing {
  2882. namespace internal {
  2883. // Canonicalizes a given name with respect to the Standard C++ Library.
  2884. // This handles removing the inline namespace within `std` that is
  2885. // used by various standard libraries (e.g., `std::__1`). Names outside
  2886. // of namespace std are returned unmodified.
  2887. inline std::string CanonicalizeForStdLibVersioning(std::string s) {
  2888. static const char prefix[] = "std::__";
  2889. if (s.compare(0, strlen(prefix), prefix) == 0) {
  2890. std::string::size_type end = s.find("::", strlen(prefix));
  2891. if (end != s.npos) {
  2892. // Erase everything between the initial `std` and the second `::`.
  2893. s.erase(strlen("std"), end - strlen("std"));
  2894. }
  2895. }
  2896. return s;
  2897. }
  2898. #if GTEST_HAS_RTTI
  2899. // GetTypeName(const std::type_info&) returns a human-readable name of type T.
  2900. inline std::string GetTypeName(const std::type_info& type) {
  2901. const char* const name = type.name();
  2902. #if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
  2903. int status = 0;
  2904. // gcc's implementation of typeid(T).name() mangles the type name,
  2905. // so we have to demangle it.
  2906. #if GTEST_HAS_CXXABI_H_
  2907. using abi::__cxa_demangle;
  2908. #endif // GTEST_HAS_CXXABI_H_
  2909. char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status);
  2910. const std::string name_str(status == 0 ? readable_name : name);
  2911. free(readable_name);
  2912. return CanonicalizeForStdLibVersioning(name_str);
  2913. #else
  2914. return name;
  2915. #endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
  2916. }
  2917. #endif // GTEST_HAS_RTTI
  2918. // GetTypeName<T>() returns a human-readable name of type T if and only if
  2919. // RTTI is enabled, otherwise it returns a dummy type name.
  2920. // NB: This function is also used in Google Mock, so don't move it inside of
  2921. // the typed-test-only section below.
  2922. template <typename T>
  2923. std::string GetTypeName() {
  2924. #if GTEST_HAS_RTTI
  2925. return GetTypeName(typeid(T));
  2926. #else
  2927. return "<type>";
  2928. #endif // GTEST_HAS_RTTI
  2929. }
  2930. // A unique type indicating an empty node
  2931. struct None {};
  2932. # define GTEST_TEMPLATE_ template <typename T> class
  2933. // The template "selector" struct TemplateSel<Tmpl> is used to
  2934. // represent Tmpl, which must be a class template with one type
  2935. // parameter, as a type. TemplateSel<Tmpl>::Bind<T>::type is defined
  2936. // as the type Tmpl<T>. This allows us to actually instantiate the
  2937. // template "selected" by TemplateSel<Tmpl>.
  2938. //
  2939. // This trick is necessary for simulating typedef for class templates,
  2940. // which C++ doesn't support directly.
  2941. template <GTEST_TEMPLATE_ Tmpl>
  2942. struct TemplateSel {
  2943. template <typename T>
  2944. struct Bind {
  2945. typedef Tmpl<T> type;
  2946. };
  2947. };
  2948. # define GTEST_BIND_(TmplSel, T) \
  2949. TmplSel::template Bind<T>::type
  2950. template <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_>
  2951. struct Templates {
  2952. using Head = TemplateSel<Head_>;
  2953. using Tail = Templates<Tail_...>;
  2954. };
  2955. template <GTEST_TEMPLATE_ Head_>
  2956. struct Templates<Head_> {
  2957. using Head = TemplateSel<Head_>;
  2958. using Tail = None;
  2959. };
  2960. // Tuple-like type lists
  2961. template <typename Head_, typename... Tail_>
  2962. struct Types {
  2963. using Head = Head_;
  2964. using Tail = Types<Tail_...>;
  2965. };
  2966. template <typename Head_>
  2967. struct Types<Head_> {
  2968. using Head = Head_;
  2969. using Tail = None;
  2970. };
  2971. // Helper metafunctions to tell apart a single type from types
  2972. // generated by ::testing::Types
  2973. template <typename... Ts>
  2974. struct ProxyTypeList {
  2975. using type = Types<Ts...>;
  2976. };
  2977. template <typename>
  2978. struct is_proxy_type_list : std::false_type {};
  2979. template <typename... Ts>
  2980. struct is_proxy_type_list<ProxyTypeList<Ts...>> : std::true_type {};
  2981. // Generator which conditionally creates type lists.
  2982. // It recognizes if a requested type list should be created
  2983. // and prevents creating a new type list nested within another one.
  2984. template <typename T>
  2985. struct GenerateTypeList {
  2986. private:
  2987. using proxy = typename std::conditional<is_proxy_type_list<T>::value, T,
  2988. ProxyTypeList<T>>::type;
  2989. public:
  2990. using type = typename proxy::type;
  2991. };
  2992. } // namespace internal
  2993. template <typename... Ts>
  2994. using Types = internal::ProxyTypeList<Ts...>;
  2995. } // namespace testing
  2996. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
  2997. // Due to C++ preprocessor weirdness, we need double indirection to
  2998. // concatenate two tokens when one of them is __LINE__. Writing
  2999. //
  3000. // foo ## __LINE__
  3001. //
  3002. // will result in the token foo__LINE__, instead of foo followed by
  3003. // the current line number. For more details, see
  3004. // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
  3005. #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
  3006. #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
  3007. // Stringifies its argument.
  3008. // Work around a bug in visual studio which doesn't accept code like this:
  3009. //
  3010. // #define GTEST_STRINGIFY_(name) #name
  3011. // #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...
  3012. // MACRO(, x, y)
  3013. //
  3014. // Complaining about the argument to GTEST_STRINGIFY_ being empty.
  3015. // This is allowed by the spec.
  3016. #define GTEST_STRINGIFY_HELPER_(name, ...) #name
  3017. #define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
  3018. namespace proto2 {
  3019. class MessageLite;
  3020. }
  3021. namespace testing {
  3022. // Forward declarations.
  3023. class AssertionResult; // Result of an assertion.
  3024. class Message; // Represents a failure message.
  3025. class Test; // Represents a test.
  3026. class TestInfo; // Information about a test.
  3027. class TestPartResult; // Result of a test part.
  3028. class UnitTest; // A collection of test suites.
  3029. template <typename T>
  3030. ::std::string PrintToString(const T& value);
  3031. namespace internal {
  3032. struct TraceInfo; // Information about a trace point.
  3033. class TestInfoImpl; // Opaque implementation of TestInfo
  3034. class UnitTestImpl; // Opaque implementation of UnitTest
  3035. // The text used in failure messages to indicate the start of the
  3036. // stack trace.
  3037. GTEST_API_ extern const char kStackTraceMarker[];
  3038. // An IgnoredValue object can be implicitly constructed from ANY value.
  3039. class IgnoredValue {
  3040. struct Sink {};
  3041. public:
  3042. // This constructor template allows any value to be implicitly
  3043. // converted to IgnoredValue. The object has no data member and
  3044. // doesn't try to remember anything about the argument. We
  3045. // deliberately omit the 'explicit' keyword in order to allow the
  3046. // conversion to be implicit.
  3047. // Disable the conversion if T already has a magical conversion operator.
  3048. // Otherwise we get ambiguity.
  3049. template <typename T,
  3050. typename std::enable_if<!std::is_convertible<T, Sink>::value,
  3051. int>::type = 0>
  3052. IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)
  3053. };
  3054. // Appends the user-supplied message to the Google-Test-generated message.
  3055. GTEST_API_ std::string AppendUserMessage(
  3056. const std::string& gtest_msg, const Message& user_msg);
  3057. #if GTEST_HAS_EXCEPTIONS
  3058. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
  3059. /* an exported class was derived from a class that was not exported */)
  3060. // This exception is thrown by (and only by) a failed Google Test
  3061. // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
  3062. // are enabled). We derive it from std::runtime_error, which is for
  3063. // errors presumably detectable only at run time. Since
  3064. // std::runtime_error inherits from std::exception, many testing
  3065. // frameworks know how to extract and print the message inside it.
  3066. class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
  3067. public:
  3068. explicit GoogleTestFailureException(const TestPartResult& failure);
  3069. };
  3070. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275
  3071. #endif // GTEST_HAS_EXCEPTIONS
  3072. namespace edit_distance {
  3073. // Returns the optimal edits to go from 'left' to 'right'.
  3074. // All edits cost the same, with replace having lower priority than
  3075. // add/remove.
  3076. // Simple implementation of the Wagner-Fischer algorithm.
  3077. // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
  3078. enum EditType { kMatch, kAdd, kRemove, kReplace };
  3079. GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
  3080. const std::vector<size_t>& left, const std::vector<size_t>& right);
  3081. // Same as above, but the input is represented as strings.
  3082. GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
  3083. const std::vector<std::string>& left,
  3084. const std::vector<std::string>& right);
  3085. // Create a diff of the input strings in Unified diff format.
  3086. GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
  3087. const std::vector<std::string>& right,
  3088. size_t context = 2);
  3089. } // namespace edit_distance
  3090. // Calculate the diff between 'left' and 'right' and return it in unified diff
  3091. // format.
  3092. // If not null, stores in 'total_line_count' the total number of lines found
  3093. // in left + right.
  3094. GTEST_API_ std::string DiffStrings(const std::string& left,
  3095. const std::string& right,
  3096. size_t* total_line_count);
  3097. // Constructs and returns the message for an equality assertion
  3098. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  3099. //
  3100. // The first four parameters are the expressions used in the assertion
  3101. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  3102. // where foo is 5 and bar is 6, we have:
  3103. //
  3104. // expected_expression: "foo"
  3105. // actual_expression: "bar"
  3106. // expected_value: "5"
  3107. // actual_value: "6"
  3108. //
  3109. // The ignoring_case parameter is true if and only if the assertion is a
  3110. // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
  3111. // be inserted into the message.
  3112. GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
  3113. const char* actual_expression,
  3114. const std::string& expected_value,
  3115. const std::string& actual_value,
  3116. bool ignoring_case);
  3117. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  3118. GTEST_API_ std::string GetBoolAssertionFailureMessage(
  3119. const AssertionResult& assertion_result,
  3120. const char* expression_text,
  3121. const char* actual_predicate_value,
  3122. const char* expected_predicate_value);
  3123. // This template class represents an IEEE floating-point number
  3124. // (either single-precision or double-precision, depending on the
  3125. // template parameters).
  3126. //
  3127. // The purpose of this class is to do more sophisticated number
  3128. // comparison. (Due to round-off error, etc, it's very unlikely that
  3129. // two floating-points will be equal exactly. Hence a naive
  3130. // comparison by the == operation often doesn't work.)
  3131. //
  3132. // Format of IEEE floating-point:
  3133. //
  3134. // The most-significant bit being the leftmost, an IEEE
  3135. // floating-point looks like
  3136. //
  3137. // sign_bit exponent_bits fraction_bits
  3138. //
  3139. // Here, sign_bit is a single bit that designates the sign of the
  3140. // number.
  3141. //
  3142. // For float, there are 8 exponent bits and 23 fraction bits.
  3143. //
  3144. // For double, there are 11 exponent bits and 52 fraction bits.
  3145. //
  3146. // More details can be found at
  3147. // http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
  3148. //
  3149. // Template parameter:
  3150. //
  3151. // RawType: the raw floating-point type (either float or double)
  3152. template <typename RawType>
  3153. class FloatingPoint {
  3154. public:
  3155. // Defines the unsigned integer type that has the same size as the
  3156. // floating point number.
  3157. typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
  3158. // Constants.
  3159. // # of bits in a number.
  3160. static const size_t kBitCount = 8*sizeof(RawType);
  3161. // # of fraction bits in a number.
  3162. static const size_t kFractionBitCount =
  3163. std::numeric_limits<RawType>::digits - 1;
  3164. // # of exponent bits in a number.
  3165. static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
  3166. // The mask for the sign bit.
  3167. static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
  3168. // The mask for the fraction bits.
  3169. static const Bits kFractionBitMask =
  3170. ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
  3171. // The mask for the exponent bits.
  3172. static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
  3173. // How many ULP's (Units in the Last Place) we want to tolerate when
  3174. // comparing two numbers. The larger the value, the more error we
  3175. // allow. A 0 value means that two numbers must be exactly the same
  3176. // to be considered equal.
  3177. //
  3178. // The maximum error of a single floating-point operation is 0.5
  3179. // units in the last place. On Intel CPU's, all floating-point
  3180. // calculations are done with 80-bit precision, while double has 64
  3181. // bits. Therefore, 4 should be enough for ordinary use.
  3182. //
  3183. // See the following article for more details on ULP:
  3184. // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
  3185. static const uint32_t kMaxUlps = 4;
  3186. // Constructs a FloatingPoint from a raw floating-point number.
  3187. //
  3188. // On an Intel CPU, passing a non-normalized NAN (Not a Number)
  3189. // around may change its bits, although the new value is guaranteed
  3190. // to be also a NAN. Therefore, don't expect this constructor to
  3191. // preserve the bits in x when x is a NAN.
  3192. explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
  3193. // Static methods
  3194. // Reinterprets a bit pattern as a floating-point number.
  3195. //
  3196. // This function is needed to test the AlmostEquals() method.
  3197. static RawType ReinterpretBits(const Bits bits) {
  3198. FloatingPoint fp(0);
  3199. fp.u_.bits_ = bits;
  3200. return fp.u_.value_;
  3201. }
  3202. // Returns the floating-point number that represent positive infinity.
  3203. static RawType Infinity() {
  3204. return ReinterpretBits(kExponentBitMask);
  3205. }
  3206. // Returns the maximum representable finite floating-point number.
  3207. static RawType Max();
  3208. // Non-static methods
  3209. // Returns the bits that represents this number.
  3210. const Bits &bits() const { return u_.bits_; }
  3211. // Returns the exponent bits of this number.
  3212. Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
  3213. // Returns the fraction bits of this number.
  3214. Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
  3215. // Returns the sign bit of this number.
  3216. Bits sign_bit() const { return kSignBitMask & u_.bits_; }
  3217. // Returns true if and only if this is NAN (not a number).
  3218. bool is_nan() const {
  3219. // It's a NAN if the exponent bits are all ones and the fraction
  3220. // bits are not entirely zeros.
  3221. return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
  3222. }
  3223. // Returns true if and only if this number is at most kMaxUlps ULP's away
  3224. // from rhs. In particular, this function:
  3225. //
  3226. // - returns false if either number is (or both are) NAN.
  3227. // - treats really large numbers as almost equal to infinity.
  3228. // - thinks +0.0 and -0.0 are 0 DLP's apart.
  3229. bool AlmostEquals(const FloatingPoint& rhs) const {
  3230. // The IEEE standard says that any comparison operation involving
  3231. // a NAN must return false.
  3232. if (is_nan() || rhs.is_nan()) return false;
  3233. return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
  3234. <= kMaxUlps;
  3235. }
  3236. private:
  3237. // The data type used to store the actual floating-point number.
  3238. union FloatingPointUnion {
  3239. RawType value_; // The raw floating-point number.
  3240. Bits bits_; // The bits that represent the number.
  3241. };
  3242. // Converts an integer from the sign-and-magnitude representation to
  3243. // the biased representation. More precisely, let N be 2 to the
  3244. // power of (kBitCount - 1), an integer x is represented by the
  3245. // unsigned number x + N.
  3246. //
  3247. // For instance,
  3248. //
  3249. // -N + 1 (the most negative number representable using
  3250. // sign-and-magnitude) is represented by 1;
  3251. // 0 is represented by N; and
  3252. // N - 1 (the biggest number representable using
  3253. // sign-and-magnitude) is represented by 2N - 1.
  3254. //
  3255. // Read http://en.wikipedia.org/wiki/Signed_number_representations
  3256. // for more details on signed number representations.
  3257. static Bits SignAndMagnitudeToBiased(const Bits &sam) {
  3258. if (kSignBitMask & sam) {
  3259. // sam represents a negative number.
  3260. return ~sam + 1;
  3261. } else {
  3262. // sam represents a positive number.
  3263. return kSignBitMask | sam;
  3264. }
  3265. }
  3266. // Given two numbers in the sign-and-magnitude representation,
  3267. // returns the distance between them as an unsigned number.
  3268. static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
  3269. const Bits &sam2) {
  3270. const Bits biased1 = SignAndMagnitudeToBiased(sam1);
  3271. const Bits biased2 = SignAndMagnitudeToBiased(sam2);
  3272. return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
  3273. }
  3274. FloatingPointUnion u_;
  3275. };
  3276. // We cannot use std::numeric_limits<T>::max() as it clashes with the max()
  3277. // macro defined by <windows.h>.
  3278. template <>
  3279. inline float FloatingPoint<float>::Max() { return FLT_MAX; }
  3280. template <>
  3281. inline double FloatingPoint<double>::Max() { return DBL_MAX; }
  3282. // Typedefs the instances of the FloatingPoint template class that we
  3283. // care to use.
  3284. typedef FloatingPoint<float> Float;
  3285. typedef FloatingPoint<double> Double;
  3286. // In order to catch the mistake of putting tests that use different
  3287. // test fixture classes in the same test suite, we need to assign
  3288. // unique IDs to fixture classes and compare them. The TypeId type is
  3289. // used to hold such IDs. The user should treat TypeId as an opaque
  3290. // type: the only operation allowed on TypeId values is to compare
  3291. // them for equality using the == operator.
  3292. typedef const void* TypeId;
  3293. template <typename T>
  3294. class TypeIdHelper {
  3295. public:
  3296. // dummy_ must not have a const type. Otherwise an overly eager
  3297. // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
  3298. // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
  3299. static bool dummy_;
  3300. };
  3301. template <typename T>
  3302. bool TypeIdHelper<T>::dummy_ = false;
  3303. // GetTypeId<T>() returns the ID of type T. Different values will be
  3304. // returned for different types. Calling the function twice with the
  3305. // same type argument is guaranteed to return the same ID.
  3306. template <typename T>
  3307. TypeId GetTypeId() {
  3308. // The compiler is required to allocate a different
  3309. // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
  3310. // the template. Therefore, the address of dummy_ is guaranteed to
  3311. // be unique.
  3312. return &(TypeIdHelper<T>::dummy_);
  3313. }
  3314. // Returns the type ID of ::testing::Test. Always call this instead
  3315. // of GetTypeId< ::testing::Test>() to get the type ID of
  3316. // ::testing::Test, as the latter may give the wrong result due to a
  3317. // suspected linker bug when compiling Google Test as a Mac OS X
  3318. // framework.
  3319. GTEST_API_ TypeId GetTestTypeId();
  3320. // Defines the abstract factory interface that creates instances
  3321. // of a Test object.
  3322. class TestFactoryBase {
  3323. public:
  3324. virtual ~TestFactoryBase() {}
  3325. // Creates a test instance to run. The instance is both created and destroyed
  3326. // within TestInfoImpl::Run()
  3327. virtual Test* CreateTest() = 0;
  3328. protected:
  3329. TestFactoryBase() {}
  3330. private:
  3331. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
  3332. };
  3333. // This class provides implementation of TeastFactoryBase interface.
  3334. // It is used in TEST and TEST_F macros.
  3335. template <class TestClass>
  3336. class TestFactoryImpl : public TestFactoryBase {
  3337. public:
  3338. Test* CreateTest() override { return new TestClass; }
  3339. };
  3340. #if GTEST_OS_WINDOWS
  3341. // Predicate-formatters for implementing the HRESULT checking macros
  3342. // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
  3343. // We pass a long instead of HRESULT to avoid causing an
  3344. // include dependency for the HRESULT type.
  3345. GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
  3346. long hr); // NOLINT
  3347. GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
  3348. long hr); // NOLINT
  3349. #endif // GTEST_OS_WINDOWS
  3350. // Types of SetUpTestSuite() and TearDownTestSuite() functions.
  3351. using SetUpTestSuiteFunc = void (*)();
  3352. using TearDownTestSuiteFunc = void (*)();
  3353. struct CodeLocation {
  3354. CodeLocation(const std::string& a_file, int a_line)
  3355. : file(a_file), line(a_line) {}
  3356. std::string file;
  3357. int line;
  3358. };
  3359. // Helper to identify which setup function for TestCase / TestSuite to call.
  3360. // Only one function is allowed, either TestCase or TestSute but not both.
  3361. // Utility functions to help SuiteApiResolver
  3362. using SetUpTearDownSuiteFuncType = void (*)();
  3363. inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(
  3364. SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) {
  3365. return a == def ? nullptr : a;
  3366. }
  3367. template <typename T>
  3368. // Note that SuiteApiResolver inherits from T because
  3369. // SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way
  3370. // SuiteApiResolver can access them.
  3371. struct SuiteApiResolver : T {
  3372. // testing::Test is only forward declared at this point. So we make it a
  3373. // dependend class for the compiler to be SUCCESS with it.
  3374. using Test =
  3375. typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;
  3376. static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,
  3377. int line_num) {
  3378. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3379. SetUpTearDownSuiteFuncType test_case_fp =
  3380. GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);
  3381. SetUpTearDownSuiteFuncType test_suite_fp =
  3382. GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite);
  3383. GTEST_CHECK_(!test_case_fp || !test_suite_fp)
  3384. << "Test can not provide both SetUpTestSuite and SetUpTestCase, please "
  3385. "make sure there is only one present at "
  3386. << filename << ":" << line_num;
  3387. return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
  3388. #else
  3389. (void)(filename);
  3390. (void)(line_num);
  3391. return &T::SetUpTestSuite;
  3392. #endif
  3393. }
  3394. static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,
  3395. int line_num) {
  3396. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3397. SetUpTearDownSuiteFuncType test_case_fp =
  3398. GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);
  3399. SetUpTearDownSuiteFuncType test_suite_fp =
  3400. GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite);
  3401. GTEST_CHECK_(!test_case_fp || !test_suite_fp)
  3402. << "Test can not provide both TearDownTestSuite and TearDownTestCase,"
  3403. " please make sure there is only one present at"
  3404. << filename << ":" << line_num;
  3405. return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
  3406. #else
  3407. (void)(filename);
  3408. (void)(line_num);
  3409. return &T::TearDownTestSuite;
  3410. #endif
  3411. }
  3412. };
  3413. // Creates a new TestInfo object and registers it with Google Test;
  3414. // returns the created object.
  3415. //
  3416. // Arguments:
  3417. //
  3418. // test_suite_name: name of the test suite
  3419. // name: name of the test
  3420. // type_param: the name of the test's type parameter, or NULL if
  3421. // this is not a typed or a type-parameterized test.
  3422. // value_param: text representation of the test's value parameter,
  3423. // or NULL if this is not a type-parameterized test.
  3424. // code_location: code location where the test is defined
  3425. // fixture_class_id: ID of the test fixture class
  3426. // set_up_tc: pointer to the function that sets up the test suite
  3427. // tear_down_tc: pointer to the function that tears down the test suite
  3428. // factory: pointer to the factory that creates a test object.
  3429. // The newly created TestInfo instance will assume
  3430. // ownership of the factory object.
  3431. GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
  3432. const char* test_suite_name, const char* name, const char* type_param,
  3433. const char* value_param, CodeLocation code_location,
  3434. TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
  3435. TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);
  3436. // If *pstr starts with the given prefix, modifies *pstr to be right
  3437. // past the prefix and returns true; otherwise leaves *pstr unchanged
  3438. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  3439. GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
  3440. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  3441. /* class A needs to have dll-interface to be used by clients of class B */)
  3442. // State of the definition of a type-parameterized test suite.
  3443. class GTEST_API_ TypedTestSuitePState {
  3444. public:
  3445. TypedTestSuitePState() : registered_(false) {}
  3446. // Adds the given test name to defined_test_names_ and return true
  3447. // if the test suite hasn't been registered; otherwise aborts the
  3448. // program.
  3449. bool AddTestName(const char* file, int line, const char* case_name,
  3450. const char* test_name) {
  3451. if (registered_) {
  3452. fprintf(stderr,
  3453. "%s Test %s must be defined before "
  3454. "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",
  3455. FormatFileLocation(file, line).c_str(), test_name, case_name);
  3456. fflush(stderr);
  3457. posix::Abort();
  3458. }
  3459. registered_tests_.insert(
  3460. ::std::make_pair(test_name, CodeLocation(file, line)));
  3461. return true;
  3462. }
  3463. bool TestExists(const std::string& test_name) const {
  3464. return registered_tests_.count(test_name) > 0;
  3465. }
  3466. const CodeLocation& GetCodeLocation(const std::string& test_name) const {
  3467. RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);
  3468. GTEST_CHECK_(it != registered_tests_.end());
  3469. return it->second;
  3470. }
  3471. // Verifies that registered_tests match the test names in
  3472. // defined_test_names_; returns registered_tests if successful, or
  3473. // aborts the program otherwise.
  3474. const char* VerifyRegisteredTestNames(const char* test_suite_name,
  3475. const char* file, int line,
  3476. const char* registered_tests);
  3477. private:
  3478. typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;
  3479. bool registered_;
  3480. RegisteredTestsMap registered_tests_;
  3481. };
  3482. // Legacy API is deprecated but still available
  3483. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3484. using TypedTestCasePState = TypedTestSuitePState;
  3485. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3486. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  3487. // Skips to the first non-space char after the first comma in 'str';
  3488. // returns NULL if no comma is found in 'str'.
  3489. inline const char* SkipComma(const char* str) {
  3490. const char* comma = strchr(str, ',');
  3491. if (comma == nullptr) {
  3492. return nullptr;
  3493. }
  3494. while (IsSpace(*(++comma))) {}
  3495. return comma;
  3496. }
  3497. // Returns the prefix of 'str' before the first comma in it; returns
  3498. // the entire string if it contains no comma.
  3499. inline std::string GetPrefixUntilComma(const char* str) {
  3500. const char* comma = strchr(str, ',');
  3501. return comma == nullptr ? str : std::string(str, comma);
  3502. }
  3503. // Splits a given string on a given delimiter, populating a given
  3504. // vector with the fields.
  3505. void SplitString(const ::std::string& str, char delimiter,
  3506. ::std::vector< ::std::string>* dest);
  3507. // The default argument to the template below for the case when the user does
  3508. // not provide a name generator.
  3509. struct DefaultNameGenerator {
  3510. template <typename T>
  3511. static std::string GetName(int i) {
  3512. return StreamableToString(i);
  3513. }
  3514. };
  3515. template <typename Provided = DefaultNameGenerator>
  3516. struct NameGeneratorSelector {
  3517. typedef Provided type;
  3518. };
  3519. template <typename NameGenerator>
  3520. void GenerateNamesRecursively(internal::None, std::vector<std::string>*, int) {}
  3521. template <typename NameGenerator, typename Types>
  3522. void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {
  3523. result->push_back(NameGenerator::template GetName<typename Types::Head>(i));
  3524. GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,
  3525. i + 1);
  3526. }
  3527. template <typename NameGenerator, typename Types>
  3528. std::vector<std::string> GenerateNames() {
  3529. std::vector<std::string> result;
  3530. GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);
  3531. return result;
  3532. }
  3533. // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
  3534. // registers a list of type-parameterized tests with Google Test. The
  3535. // return value is insignificant - we just need to return something
  3536. // such that we can call this function in a namespace scope.
  3537. //
  3538. // Implementation note: The GTEST_TEMPLATE_ macro declares a template
  3539. // template parameter. It's defined in gtest-type-util.h.
  3540. template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
  3541. class TypeParameterizedTest {
  3542. public:
  3543. // 'index' is the index of the test in the type list 'Types'
  3544. // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
  3545. // Types). Valid values for 'index' are [0, N - 1] where N is the
  3546. // length of Types.
  3547. static bool Register(const char* prefix, const CodeLocation& code_location,
  3548. const char* case_name, const char* test_names, int index,
  3549. const std::vector<std::string>& type_names =
  3550. GenerateNames<DefaultNameGenerator, Types>()) {
  3551. typedef typename Types::Head Type;
  3552. typedef Fixture<Type> FixtureClass;
  3553. typedef typename GTEST_BIND_(TestSel, Type) TestClass;
  3554. // First, registers the first type-parameterized test in the type
  3555. // list.
  3556. MakeAndRegisterTestInfo(
  3557. (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +
  3558. "/" + type_names[static_cast<size_t>(index)])
  3559. .c_str(),
  3560. StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
  3561. GetTypeName<Type>().c_str(),
  3562. nullptr, // No value parameter.
  3563. code_location, GetTypeId<FixtureClass>(),
  3564. SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite(
  3565. code_location.file.c_str(), code_location.line),
  3566. SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite(
  3567. code_location.file.c_str(), code_location.line),
  3568. new TestFactoryImpl<TestClass>);
  3569. // Next, recurses (at compile time) with the tail of the type list.
  3570. return TypeParameterizedTest<Fixture, TestSel,
  3571. typename Types::Tail>::Register(prefix,
  3572. code_location,
  3573. case_name,
  3574. test_names,
  3575. index + 1,
  3576. type_names);
  3577. }
  3578. };
  3579. // The base case for the compile time recursion.
  3580. template <GTEST_TEMPLATE_ Fixture, class TestSel>
  3581. class TypeParameterizedTest<Fixture, TestSel, internal::None> {
  3582. public:
  3583. static bool Register(const char* /*prefix*/, const CodeLocation&,
  3584. const char* /*case_name*/, const char* /*test_names*/,
  3585. int /*index*/,
  3586. const std::vector<std::string>& =
  3587. std::vector<std::string>() /*type_names*/) {
  3588. return true;
  3589. }
  3590. };
  3591. GTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
  3592. CodeLocation code_location);
  3593. GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(
  3594. const char* case_name);
  3595. // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
  3596. // registers *all combinations* of 'Tests' and 'Types' with Google
  3597. // Test. The return value is insignificant - we just need to return
  3598. // something such that we can call this function in a namespace scope.
  3599. template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
  3600. class TypeParameterizedTestSuite {
  3601. public:
  3602. static bool Register(const char* prefix, CodeLocation code_location,
  3603. const TypedTestSuitePState* state, const char* case_name,
  3604. const char* test_names,
  3605. const std::vector<std::string>& type_names =
  3606. GenerateNames<DefaultNameGenerator, Types>()) {
  3607. RegisterTypeParameterizedTestSuiteInstantiation(case_name);
  3608. std::string test_name = StripTrailingSpaces(
  3609. GetPrefixUntilComma(test_names));
  3610. if (!state->TestExists(test_name)) {
  3611. fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
  3612. case_name, test_name.c_str(),
  3613. FormatFileLocation(code_location.file.c_str(),
  3614. code_location.line).c_str());
  3615. fflush(stderr);
  3616. posix::Abort();
  3617. }
  3618. const CodeLocation& test_location = state->GetCodeLocation(test_name);
  3619. typedef typename Tests::Head Head;
  3620. // First, register the first test in 'Test' for each type in 'Types'.
  3621. TypeParameterizedTest<Fixture, Head, Types>::Register(
  3622. prefix, test_location, case_name, test_names, 0, type_names);
  3623. // Next, recurses (at compile time) with the tail of the test list.
  3624. return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,
  3625. Types>::Register(prefix, code_location,
  3626. state, case_name,
  3627. SkipComma(test_names),
  3628. type_names);
  3629. }
  3630. };
  3631. // The base case for the compile time recursion.
  3632. template <GTEST_TEMPLATE_ Fixture, typename Types>
  3633. class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
  3634. public:
  3635. static bool Register(const char* /*prefix*/, const CodeLocation&,
  3636. const TypedTestSuitePState* /*state*/,
  3637. const char* /*case_name*/, const char* /*test_names*/,
  3638. const std::vector<std::string>& =
  3639. std::vector<std::string>() /*type_names*/) {
  3640. return true;
  3641. }
  3642. };
  3643. // Returns the current OS stack trace as an std::string.
  3644. //
  3645. // The maximum number of stack frames to be included is specified by
  3646. // the gtest_stack_trace_depth flag. The skip_count parameter
  3647. // specifies the number of top frames to be skipped, which doesn't
  3648. // count against the number of frames to be included.
  3649. //
  3650. // For example, if Foo() calls Bar(), which in turn calls
  3651. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  3652. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  3653. GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
  3654. UnitTest* unit_test, int skip_count);
  3655. // Helpers for suppressing warnings on unreachable code or constant
  3656. // condition.
  3657. // Always returns true.
  3658. GTEST_API_ bool AlwaysTrue();
  3659. // Always returns false.
  3660. inline bool AlwaysFalse() { return !AlwaysTrue(); }
  3661. // Helper for suppressing false warning from Clang on a const char*
  3662. // variable declared in a conditional expression always being NULL in
  3663. // the else branch.
  3664. struct GTEST_API_ ConstCharPtr {
  3665. ConstCharPtr(const char* str) : value(str) {}
  3666. operator bool() const { return true; }
  3667. const char* value;
  3668. };
  3669. // Helper for declaring std::string within 'if' statement
  3670. // in pre C++17 build environment.
  3671. struct TrueWithString {
  3672. TrueWithString() = default;
  3673. explicit TrueWithString(const char* str) : value(str) {}
  3674. explicit TrueWithString(const std::string& str) : value(str) {}
  3675. explicit operator bool() const { return true; }
  3676. std::string value;
  3677. };
  3678. // A simple Linear Congruential Generator for generating random
  3679. // numbers with a uniform distribution. Unlike rand() and srand(), it
  3680. // doesn't use global state (and therefore can't interfere with user
  3681. // code). Unlike rand_r(), it's portable. An LCG isn't very random,
  3682. // but it's good enough for our purposes.
  3683. class GTEST_API_ Random {
  3684. public:
  3685. static const uint32_t kMaxRange = 1u << 31;
  3686. explicit Random(uint32_t seed) : state_(seed) {}
  3687. void Reseed(uint32_t seed) { state_ = seed; }
  3688. // Generates a random number from [0, range). Crashes if 'range' is
  3689. // 0 or greater than kMaxRange.
  3690. uint32_t Generate(uint32_t range);
  3691. private:
  3692. uint32_t state_;
  3693. GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
  3694. };
  3695. // Turns const U&, U&, const U, and U all into U.
  3696. #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
  3697. typename std::remove_const<typename std::remove_reference<T>::type>::type
  3698. // HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant
  3699. // that's true if and only if T has methods DebugString() and ShortDebugString()
  3700. // that return std::string.
  3701. template <typename T>
  3702. class HasDebugStringAndShortDebugString {
  3703. private:
  3704. template <typename C>
  3705. static auto CheckDebugString(C*) -> typename std::is_same<
  3706. std::string, decltype(std::declval<const C>().DebugString())>::type;
  3707. template <typename>
  3708. static std::false_type CheckDebugString(...);
  3709. template <typename C>
  3710. static auto CheckShortDebugString(C*) -> typename std::is_same<
  3711. std::string, decltype(std::declval<const C>().ShortDebugString())>::type;
  3712. template <typename>
  3713. static std::false_type CheckShortDebugString(...);
  3714. using HasDebugStringType = decltype(CheckDebugString<T>(nullptr));
  3715. using HasShortDebugStringType = decltype(CheckShortDebugString<T>(nullptr));
  3716. public:
  3717. static constexpr bool value =
  3718. HasDebugStringType::value && HasShortDebugStringType::value;
  3719. };
  3720. template <typename T>
  3721. constexpr bool HasDebugStringAndShortDebugString<T>::value;
  3722. // When the compiler sees expression IsContainerTest<C>(0), if C is an
  3723. // STL-style container class, the first overload of IsContainerTest
  3724. // will be viable (since both C::iterator* and C::const_iterator* are
  3725. // valid types and NULL can be implicitly converted to them). It will
  3726. // be picked over the second overload as 'int' is a perfect match for
  3727. // the type of argument 0. If C::iterator or C::const_iterator is not
  3728. // a valid type, the first overload is not viable, and the second
  3729. // overload will be picked. Therefore, we can determine whether C is
  3730. // a container class by checking the type of IsContainerTest<C>(0).
  3731. // The value of the expression is insignificant.
  3732. //
  3733. // In C++11 mode we check the existence of a const_iterator and that an
  3734. // iterator is properly implemented for the container.
  3735. //
  3736. // For pre-C++11 that we look for both C::iterator and C::const_iterator.
  3737. // The reason is that C++ injects the name of a class as a member of the
  3738. // class itself (e.g. you can refer to class iterator as either
  3739. // 'iterator' or 'iterator::iterator'). If we look for C::iterator
  3740. // only, for example, we would mistakenly think that a class named
  3741. // iterator is an STL container.
  3742. //
  3743. // Also note that the simpler approach of overloading
  3744. // IsContainerTest(typename C::const_iterator*) and
  3745. // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
  3746. typedef int IsContainer;
  3747. template <class C,
  3748. class Iterator = decltype(::std::declval<const C&>().begin()),
  3749. class = decltype(::std::declval<const C&>().end()),
  3750. class = decltype(++::std::declval<Iterator&>()),
  3751. class = decltype(*::std::declval<Iterator>()),
  3752. class = typename C::const_iterator>
  3753. IsContainer IsContainerTest(int /* dummy */) {
  3754. return 0;
  3755. }
  3756. typedef char IsNotContainer;
  3757. template <class C>
  3758. IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
  3759. // Trait to detect whether a type T is a hash table.
  3760. // The heuristic used is that the type contains an inner type `hasher` and does
  3761. // not contain an inner type `reverse_iterator`.
  3762. // If the container is iterable in reverse, then order might actually matter.
  3763. template <typename T>
  3764. struct IsHashTable {
  3765. private:
  3766. template <typename U>
  3767. static char test(typename U::hasher*, typename U::reverse_iterator*);
  3768. template <typename U>
  3769. static int test(typename U::hasher*, ...);
  3770. template <typename U>
  3771. static char test(...);
  3772. public:
  3773. static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int);
  3774. };
  3775. template <typename T>
  3776. const bool IsHashTable<T>::value;
  3777. template <typename C,
  3778. bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)>
  3779. struct IsRecursiveContainerImpl;
  3780. template <typename C>
  3781. struct IsRecursiveContainerImpl<C, false> : public std::false_type {};
  3782. // Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to
  3783. // obey the same inconsistencies as the IsContainerTest, namely check if
  3784. // something is a container is relying on only const_iterator in C++11 and
  3785. // is relying on both const_iterator and iterator otherwise
  3786. template <typename C>
  3787. struct IsRecursiveContainerImpl<C, true> {
  3788. using value_type = decltype(*std::declval<typename C::const_iterator>());
  3789. using type =
  3790. std::is_same<typename std::remove_const<
  3791. typename std::remove_reference<value_type>::type>::type,
  3792. C>;
  3793. };
  3794. // IsRecursiveContainer<Type> is a unary compile-time predicate that
  3795. // evaluates whether C is a recursive container type. A recursive container
  3796. // type is a container type whose value_type is equal to the container type
  3797. // itself. An example for a recursive container type is
  3798. // boost::filesystem::path, whose iterator has a value_type that is equal to
  3799. // boost::filesystem::path.
  3800. template <typename C>
  3801. struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};
  3802. // Utilities for native arrays.
  3803. // ArrayEq() compares two k-dimensional native arrays using the
  3804. // elements' operator==, where k can be any integer >= 0. When k is
  3805. // 0, ArrayEq() degenerates into comparing a single pair of values.
  3806. template <typename T, typename U>
  3807. bool ArrayEq(const T* lhs, size_t size, const U* rhs);
  3808. // This generic version is used when k is 0.
  3809. template <typename T, typename U>
  3810. inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
  3811. // This overload is used when k >= 1.
  3812. template <typename T, typename U, size_t N>
  3813. inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
  3814. return internal::ArrayEq(lhs, N, rhs);
  3815. }
  3816. // This helper reduces code bloat. If we instead put its logic inside
  3817. // the previous ArrayEq() function, arrays with different sizes would
  3818. // lead to different copies of the template code.
  3819. template <typename T, typename U>
  3820. bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
  3821. for (size_t i = 0; i != size; i++) {
  3822. if (!internal::ArrayEq(lhs[i], rhs[i]))
  3823. return false;
  3824. }
  3825. return true;
  3826. }
  3827. // Finds the first element in the iterator range [begin, end) that
  3828. // equals elem. Element may be a native array type itself.
  3829. template <typename Iter, typename Element>
  3830. Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
  3831. for (Iter it = begin; it != end; ++it) {
  3832. if (internal::ArrayEq(*it, elem))
  3833. return it;
  3834. }
  3835. return end;
  3836. }
  3837. // CopyArray() copies a k-dimensional native array using the elements'
  3838. // operator=, where k can be any integer >= 0. When k is 0,
  3839. // CopyArray() degenerates into copying a single value.
  3840. template <typename T, typename U>
  3841. void CopyArray(const T* from, size_t size, U* to);
  3842. // This generic version is used when k is 0.
  3843. template <typename T, typename U>
  3844. inline void CopyArray(const T& from, U* to) { *to = from; }
  3845. // This overload is used when k >= 1.
  3846. template <typename T, typename U, size_t N>
  3847. inline void CopyArray(const T(&from)[N], U(*to)[N]) {
  3848. internal::CopyArray(from, N, *to);
  3849. }
  3850. // This helper reduces code bloat. If we instead put its logic inside
  3851. // the previous CopyArray() function, arrays with different sizes
  3852. // would lead to different copies of the template code.
  3853. template <typename T, typename U>
  3854. void CopyArray(const T* from, size_t size, U* to) {
  3855. for (size_t i = 0; i != size; i++) {
  3856. internal::CopyArray(from[i], to + i);
  3857. }
  3858. }
  3859. // The relation between an NativeArray object (see below) and the
  3860. // native array it represents.
  3861. // We use 2 different structs to allow non-copyable types to be used, as long
  3862. // as RelationToSourceReference() is passed.
  3863. struct RelationToSourceReference {};
  3864. struct RelationToSourceCopy {};
  3865. // Adapts a native array to a read-only STL-style container. Instead
  3866. // of the complete STL container concept, this adaptor only implements
  3867. // members useful for Google Mock's container matchers. New members
  3868. // should be added as needed. To simplify the implementation, we only
  3869. // support Element being a raw type (i.e. having no top-level const or
  3870. // reference modifier). It's the client's responsibility to satisfy
  3871. // this requirement. Element can be an array type itself (hence
  3872. // multi-dimensional arrays are supported).
  3873. template <typename Element>
  3874. class NativeArray {
  3875. public:
  3876. // STL-style container typedefs.
  3877. typedef Element value_type;
  3878. typedef Element* iterator;
  3879. typedef const Element* const_iterator;
  3880. // Constructs from a native array. References the source.
  3881. NativeArray(const Element* array, size_t count, RelationToSourceReference) {
  3882. InitRef(array, count);
  3883. }
  3884. // Constructs from a native array. Copies the source.
  3885. NativeArray(const Element* array, size_t count, RelationToSourceCopy) {
  3886. InitCopy(array, count);
  3887. }
  3888. // Copy constructor.
  3889. NativeArray(const NativeArray& rhs) {
  3890. (this->*rhs.clone_)(rhs.array_, rhs.size_);
  3891. }
  3892. ~NativeArray() {
  3893. if (clone_ != &NativeArray::InitRef)
  3894. delete[] array_;
  3895. }
  3896. // STL-style container methods.
  3897. size_t size() const { return size_; }
  3898. const_iterator begin() const { return array_; }
  3899. const_iterator end() const { return array_ + size_; }
  3900. bool operator==(const NativeArray& rhs) const {
  3901. return size() == rhs.size() &&
  3902. ArrayEq(begin(), size(), rhs.begin());
  3903. }
  3904. private:
  3905. static_assert(!std::is_const<Element>::value, "Type must not be const");
  3906. static_assert(!std::is_reference<Element>::value,
  3907. "Type must not be a reference");
  3908. // Initializes this object with a copy of the input.
  3909. void InitCopy(const Element* array, size_t a_size) {
  3910. Element* const copy = new Element[a_size];
  3911. CopyArray(array, a_size, copy);
  3912. array_ = copy;
  3913. size_ = a_size;
  3914. clone_ = &NativeArray::InitCopy;
  3915. }
  3916. // Initializes this object with a reference of the input.
  3917. void InitRef(const Element* array, size_t a_size) {
  3918. array_ = array;
  3919. size_ = a_size;
  3920. clone_ = &NativeArray::InitRef;
  3921. }
  3922. const Element* array_;
  3923. size_t size_;
  3924. void (NativeArray::*clone_)(const Element*, size_t);
  3925. };
  3926. // Backport of std::index_sequence.
  3927. template <size_t... Is>
  3928. struct IndexSequence {
  3929. using type = IndexSequence;
  3930. };
  3931. // Double the IndexSequence, and one if plus_one is true.
  3932. template <bool plus_one, typename T, size_t sizeofT>
  3933. struct DoubleSequence;
  3934. template <size_t... I, size_t sizeofT>
  3935. struct DoubleSequence<true, IndexSequence<I...>, sizeofT> {
  3936. using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>;
  3937. };
  3938. template <size_t... I, size_t sizeofT>
  3939. struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
  3940. using type = IndexSequence<I..., (sizeofT + I)...>;
  3941. };
  3942. // Backport of std::make_index_sequence.
  3943. // It uses O(ln(N)) instantiation depth.
  3944. template <size_t N>
  3945. struct MakeIndexSequenceImpl
  3946. : DoubleSequence<N % 2 == 1, typename MakeIndexSequenceImpl<N / 2>::type,
  3947. N / 2>::type {};
  3948. template <>
  3949. struct MakeIndexSequenceImpl<0> : IndexSequence<> {};
  3950. template <size_t N>
  3951. using MakeIndexSequence = typename MakeIndexSequenceImpl<N>::type;
  3952. template <typename... T>
  3953. using IndexSequenceFor = typename MakeIndexSequence<sizeof...(T)>::type;
  3954. template <size_t>
  3955. struct Ignore {
  3956. Ignore(...); // NOLINT
  3957. };
  3958. template <typename>
  3959. struct ElemFromListImpl;
  3960. template <size_t... I>
  3961. struct ElemFromListImpl<IndexSequence<I...>> {
  3962. // We make Ignore a template to solve a problem with MSVC.
  3963. // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but
  3964. // MSVC doesn't understand how to deal with that pack expansion.
  3965. // Use `0 * I` to have a single instantiation of Ignore.
  3966. template <typename R>
  3967. static R Apply(Ignore<0 * I>..., R (*)(), ...);
  3968. };
  3969. template <size_t N, typename... T>
  3970. struct ElemFromList {
  3971. using type =
  3972. decltype(ElemFromListImpl<typename MakeIndexSequence<N>::type>::Apply(
  3973. static_cast<T (*)()>(nullptr)...));
  3974. };
  3975. struct FlatTupleConstructTag {};
  3976. template <typename... T>
  3977. class FlatTuple;
  3978. template <typename Derived, size_t I>
  3979. struct FlatTupleElemBase;
  3980. template <typename... T, size_t I>
  3981. struct FlatTupleElemBase<FlatTuple<T...>, I> {
  3982. using value_type = typename ElemFromList<I, T...>::type;
  3983. FlatTupleElemBase() = default;
  3984. template <typename Arg>
  3985. explicit FlatTupleElemBase(FlatTupleConstructTag, Arg&& t)
  3986. : value(std::forward<Arg>(t)) {}
  3987. value_type value;
  3988. };
  3989. template <typename Derived, typename Idx>
  3990. struct FlatTupleBase;
  3991. template <size_t... Idx, typename... T>
  3992. struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
  3993. : FlatTupleElemBase<FlatTuple<T...>, Idx>... {
  3994. using Indices = IndexSequence<Idx...>;
  3995. FlatTupleBase() = default;
  3996. template <typename... Args>
  3997. explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args)
  3998. : FlatTupleElemBase<FlatTuple<T...>, Idx>(FlatTupleConstructTag{},
  3999. std::forward<Args>(args))... {}
  4000. template <size_t I>
  4001. const typename ElemFromList<I, T...>::type& Get() const {
  4002. return FlatTupleElemBase<FlatTuple<T...>, I>::value;
  4003. }
  4004. template <size_t I>
  4005. typename ElemFromList<I, T...>::type& Get() {
  4006. return FlatTupleElemBase<FlatTuple<T...>, I>::value;
  4007. }
  4008. template <typename F>
  4009. auto Apply(F&& f) -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
  4010. return std::forward<F>(f)(Get<Idx>()...);
  4011. }
  4012. template <typename F>
  4013. auto Apply(F&& f) const -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
  4014. return std::forward<F>(f)(Get<Idx>()...);
  4015. }
  4016. };
  4017. // Analog to std::tuple but with different tradeoffs.
  4018. // This class minimizes the template instantiation depth, thus allowing more
  4019. // elements than std::tuple would. std::tuple has been seen to require an
  4020. // instantiation depth of more than 10x the number of elements in some
  4021. // implementations.
  4022. // FlatTuple and ElemFromList are not recursive and have a fixed depth
  4023. // regardless of T...
  4024. // MakeIndexSequence, on the other hand, it is recursive but with an
  4025. // instantiation depth of O(ln(N)).
  4026. template <typename... T>
  4027. class FlatTuple
  4028. : private FlatTupleBase<FlatTuple<T...>,
  4029. typename MakeIndexSequence<sizeof...(T)>::type> {
  4030. using Indices = typename FlatTupleBase<
  4031. FlatTuple<T...>, typename MakeIndexSequence<sizeof...(T)>::type>::Indices;
  4032. public:
  4033. FlatTuple() = default;
  4034. template <typename... Args>
  4035. explicit FlatTuple(FlatTupleConstructTag tag, Args&&... args)
  4036. : FlatTuple::FlatTupleBase(tag, std::forward<Args>(args)...) {}
  4037. using FlatTuple::FlatTupleBase::Apply;
  4038. using FlatTuple::FlatTupleBase::Get;
  4039. };
  4040. // Utility functions to be called with static_assert to induce deprecation
  4041. // warnings.
  4042. GTEST_INTERNAL_DEPRECATED(
  4043. "INSTANTIATE_TEST_CASE_P is deprecated, please use "
  4044. "INSTANTIATE_TEST_SUITE_P")
  4045. constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
  4046. GTEST_INTERNAL_DEPRECATED(
  4047. "TYPED_TEST_CASE_P is deprecated, please use "
  4048. "TYPED_TEST_SUITE_P")
  4049. constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
  4050. GTEST_INTERNAL_DEPRECATED(
  4051. "TYPED_TEST_CASE is deprecated, please use "
  4052. "TYPED_TEST_SUITE")
  4053. constexpr bool TypedTestCaseIsDeprecated() { return true; }
  4054. GTEST_INTERNAL_DEPRECATED(
  4055. "REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
  4056. "REGISTER_TYPED_TEST_SUITE_P")
  4057. constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
  4058. GTEST_INTERNAL_DEPRECATED(
  4059. "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
  4060. "INSTANTIATE_TYPED_TEST_SUITE_P")
  4061. constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
  4062. } // namespace internal
  4063. } // namespace testing
  4064. namespace std {
  4065. // Some standard library implementations use `struct tuple_size` and some use
  4066. // `class tuple_size`. Clang warns about the mismatch.
  4067. // https://reviews.llvm.org/D55466
  4068. #ifdef __clang__
  4069. #pragma clang diagnostic push
  4070. #pragma clang diagnostic ignored "-Wmismatched-tags"
  4071. #endif
  4072. template <typename... Ts>
  4073. struct tuple_size<testing::internal::FlatTuple<Ts...>>
  4074. : std::integral_constant<size_t, sizeof...(Ts)> {};
  4075. #ifdef __clang__
  4076. #pragma clang diagnostic pop
  4077. #endif
  4078. } // namespace std
  4079. #define GTEST_MESSAGE_AT_(file, line, message, result_type) \
  4080. ::testing::internal::AssertHelper(result_type, file, line, message) \
  4081. = ::testing::Message()
  4082. #define GTEST_MESSAGE_(message, result_type) \
  4083. GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
  4084. #define GTEST_FATAL_FAILURE_(message) \
  4085. return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
  4086. #define GTEST_NONFATAL_FAILURE_(message) \
  4087. GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
  4088. #define GTEST_SUCCESS_(message) \
  4089. GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
  4090. #define GTEST_SKIP_(message) \
  4091. return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)
  4092. // Suppress MSVC warning 4072 (unreachable code) for the code following
  4093. // statement if it returns or throws (or doesn't return or throw in some
  4094. // situations).
  4095. // NOTE: The "else" is important to keep this expansion to prevent a top-level
  4096. // "else" from attaching to our "if".
  4097. #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
  4098. if (::testing::internal::AlwaysTrue()) { \
  4099. statement; \
  4100. } else /* NOLINT */ \
  4101. static_assert(true, "") // User must have a semicolon after expansion.
  4102. #if GTEST_HAS_EXCEPTIONS
  4103. namespace testing {
  4104. namespace internal {
  4105. class NeverThrown {
  4106. public:
  4107. const char* what() const noexcept {
  4108. return "this exception should never be thrown";
  4109. }
  4110. };
  4111. } // namespace internal
  4112. } // namespace testing
  4113. #if GTEST_HAS_RTTI
  4114. #define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))
  4115. #else // GTEST_HAS_RTTI
  4116. #define GTEST_EXCEPTION_TYPE_(e) \
  4117. std::string { "an std::exception-derived error" }
  4118. #endif // GTEST_HAS_RTTI
  4119. #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
  4120. catch (typename std::conditional< \
  4121. std::is_same<typename std::remove_cv<typename std::remove_reference< \
  4122. expected_exception>::type>::type, \
  4123. std::exception>::value, \
  4124. const ::testing::internal::NeverThrown&, const std::exception&>::type \
  4125. e) { \
  4126. gtest_msg.value = "Expected: " #statement \
  4127. " throws an exception of type " #expected_exception \
  4128. ".\n Actual: it throws "; \
  4129. gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
  4130. gtest_msg.value += " with description \""; \
  4131. gtest_msg.value += e.what(); \
  4132. gtest_msg.value += "\"."; \
  4133. goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
  4134. }
  4135. #else // GTEST_HAS_EXCEPTIONS
  4136. #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)
  4137. #endif // GTEST_HAS_EXCEPTIONS
  4138. #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
  4139. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  4140. if (::testing::internal::TrueWithString gtest_msg{}) { \
  4141. bool gtest_caught_expected = false; \
  4142. try { \
  4143. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  4144. } catch (expected_exception const&) { \
  4145. gtest_caught_expected = true; \
  4146. } \
  4147. GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
  4148. catch (...) { \
  4149. gtest_msg.value = "Expected: " #statement \
  4150. " throws an exception of type " #expected_exception \
  4151. ".\n Actual: it throws a different type."; \
  4152. goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
  4153. } \
  4154. if (!gtest_caught_expected) { \
  4155. gtest_msg.value = "Expected: " #statement \
  4156. " throws an exception of type " #expected_exception \
  4157. ".\n Actual: it throws nothing."; \
  4158. goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
  4159. } \
  4160. } else /*NOLINT*/ \
  4161. GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
  4162. : fail(gtest_msg.value.c_str())
  4163. #if GTEST_HAS_EXCEPTIONS
  4164. #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
  4165. catch (std::exception const& e) { \
  4166. gtest_msg.value = "it throws "; \
  4167. gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
  4168. gtest_msg.value += " with description \""; \
  4169. gtest_msg.value += e.what(); \
  4170. gtest_msg.value += "\"."; \
  4171. goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
  4172. }
  4173. #else // GTEST_HAS_EXCEPTIONS
  4174. #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()
  4175. #endif // GTEST_HAS_EXCEPTIONS
  4176. #define GTEST_TEST_NO_THROW_(statement, fail) \
  4177. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  4178. if (::testing::internal::TrueWithString gtest_msg{}) { \
  4179. try { \
  4180. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  4181. } \
  4182. GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
  4183. catch (...) { \
  4184. gtest_msg.value = "it throws."; \
  4185. goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
  4186. } \
  4187. } else \
  4188. GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
  4189. fail(("Expected: " #statement " doesn't throw an exception.\n" \
  4190. " Actual: " + gtest_msg.value).c_str())
  4191. #define GTEST_TEST_ANY_THROW_(statement, fail) \
  4192. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  4193. if (::testing::internal::AlwaysTrue()) { \
  4194. bool gtest_caught_any = false; \
  4195. try { \
  4196. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  4197. } \
  4198. catch (...) { \
  4199. gtest_caught_any = true; \
  4200. } \
  4201. if (!gtest_caught_any) { \
  4202. goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
  4203. } \
  4204. } else \
  4205. GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
  4206. fail("Expected: " #statement " throws an exception.\n" \
  4207. " Actual: it doesn't.")
  4208. // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
  4209. // either a boolean expression or an AssertionResult. text is a textual
  4210. // representation of expression as it was passed into the EXPECT_TRUE.
  4211. #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
  4212. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  4213. if (const ::testing::AssertionResult gtest_ar_ = \
  4214. ::testing::AssertionResult(expression)) \
  4215. ; \
  4216. else \
  4217. fail(::testing::internal::GetBoolAssertionFailureMessage(\
  4218. gtest_ar_, text, #actual, #expected).c_str())
  4219. #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
  4220. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  4221. if (::testing::internal::AlwaysTrue()) { \
  4222. ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
  4223. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  4224. if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
  4225. goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
  4226. } \
  4227. } else \
  4228. GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
  4229. fail("Expected: " #statement " doesn't generate new fatal " \
  4230. "failures in the current thread.\n" \
  4231. " Actual: it does.")
  4232. // Expands to the name of the class that implements the given test.
  4233. #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
  4234. test_suite_name##_##test_name##_Test
  4235. // Helper macro for defining tests.
  4236. #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \
  4237. static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \
  4238. "test_suite_name must not be empty"); \
  4239. static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \
  4240. "test_name must not be empty"); \
  4241. class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
  4242. : public parent_class { \
  4243. public: \
  4244. GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \
  4245. ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \
  4246. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
  4247. test_name)); \
  4248. GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
  4249. test_name)); \
  4250. \
  4251. private: \
  4252. void TestBody() override; \
  4253. static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
  4254. }; \
  4255. \
  4256. ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \
  4257. test_name)::test_info_ = \
  4258. ::testing::internal::MakeAndRegisterTestInfo( \
  4259. #test_suite_name, #test_name, nullptr, nullptr, \
  4260. ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
  4261. ::testing::internal::SuiteApiResolver< \
  4262. parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \
  4263. ::testing::internal::SuiteApiResolver< \
  4264. parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \
  4265. new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \
  4266. test_suite_name, test_name)>); \
  4267. void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
  4268. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
  4269. // Copyright 2005, Google Inc.
  4270. // All rights reserved.
  4271. //
  4272. // Redistribution and use in source and binary forms, with or without
  4273. // modification, are permitted provided that the following conditions are
  4274. // met:
  4275. //
  4276. // * Redistributions of source code must retain the above copyright
  4277. // notice, this list of conditions and the following disclaimer.
  4278. // * Redistributions in binary form must reproduce the above
  4279. // copyright notice, this list of conditions and the following disclaimer
  4280. // in the documentation and/or other materials provided with the
  4281. // distribution.
  4282. // * Neither the name of Google Inc. nor the names of its
  4283. // contributors may be used to endorse or promote products derived from
  4284. // this software without specific prior written permission.
  4285. //
  4286. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4287. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  4288. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  4289. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  4290. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  4291. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4292. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  4293. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  4294. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  4295. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  4296. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4297. //
  4298. // The Google C++ Testing and Mocking Framework (Google Test)
  4299. //
  4300. // This header file defines the public API for death tests. It is
  4301. // #included by gtest.h so a user doesn't need to include this
  4302. // directly.
  4303. // GOOGLETEST_CM0001 DO NOT DELETE
  4304. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
  4305. #define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
  4306. // Copyright 2005, Google Inc.
  4307. // All rights reserved.
  4308. //
  4309. // Redistribution and use in source and binary forms, with or without
  4310. // modification, are permitted provided that the following conditions are
  4311. // met:
  4312. //
  4313. // * Redistributions of source code must retain the above copyright
  4314. // notice, this list of conditions and the following disclaimer.
  4315. // * Redistributions in binary form must reproduce the above
  4316. // copyright notice, this list of conditions and the following disclaimer
  4317. // in the documentation and/or other materials provided with the
  4318. // distribution.
  4319. // * Neither the name of Google Inc. nor the names of its
  4320. // contributors may be used to endorse or promote products derived from
  4321. // this software without specific prior written permission.
  4322. //
  4323. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4324. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  4325. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  4326. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  4327. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  4328. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4329. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  4330. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  4331. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  4332. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  4333. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4334. //
  4335. // The Google C++ Testing and Mocking Framework (Google Test)
  4336. //
  4337. // This header file defines internal utilities needed for implementing
  4338. // death tests. They are subject to change without notice.
  4339. // GOOGLETEST_CM0001 DO NOT DELETE
  4340. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
  4341. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
  4342. // Copyright 2007, Google Inc.
  4343. // All rights reserved.
  4344. //
  4345. // Redistribution and use in source and binary forms, with or without
  4346. // modification, are permitted provided that the following conditions are
  4347. // met:
  4348. //
  4349. // * Redistributions of source code must retain the above copyright
  4350. // notice, this list of conditions and the following disclaimer.
  4351. // * Redistributions in binary form must reproduce the above
  4352. // copyright notice, this list of conditions and the following disclaimer
  4353. // in the documentation and/or other materials provided with the
  4354. // distribution.
  4355. // * Neither the name of Google Inc. nor the names of its
  4356. // contributors may be used to endorse or promote products derived from
  4357. // this software without specific prior written permission.
  4358. //
  4359. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4360. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  4361. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  4362. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  4363. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  4364. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4365. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  4366. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  4367. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  4368. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  4369. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4370. // The Google C++ Testing and Mocking Framework (Google Test)
  4371. //
  4372. // This file implements just enough of the matcher interface to allow
  4373. // EXPECT_DEATH and friends to accept a matcher argument.
  4374. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
  4375. #define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
  4376. #include <atomic>
  4377. #include <memory>
  4378. #include <ostream>
  4379. #include <string>
  4380. #include <type_traits>
  4381. // Copyright 2007, Google Inc.
  4382. // All rights reserved.
  4383. //
  4384. // Redistribution and use in source and binary forms, with or without
  4385. // modification, are permitted provided that the following conditions are
  4386. // met:
  4387. //
  4388. // * Redistributions of source code must retain the above copyright
  4389. // notice, this list of conditions and the following disclaimer.
  4390. // * Redistributions in binary form must reproduce the above
  4391. // copyright notice, this list of conditions and the following disclaimer
  4392. // in the documentation and/or other materials provided with the
  4393. // distribution.
  4394. // * Neither the name of Google Inc. nor the names of its
  4395. // contributors may be used to endorse or promote products derived from
  4396. // this software without specific prior written permission.
  4397. //
  4398. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4399. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  4400. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  4401. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  4402. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  4403. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4404. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  4405. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  4406. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  4407. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  4408. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4409. // Google Test - The Google C++ Testing and Mocking Framework
  4410. //
  4411. // This file implements a universal value printer that can print a
  4412. // value of any type T:
  4413. //
  4414. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  4415. //
  4416. // A user can teach this function how to print a class type T by
  4417. // defining either operator<<() or PrintTo() in the namespace that
  4418. // defines T. More specifically, the FIRST defined function in the
  4419. // following list will be used (assuming T is defined in namespace
  4420. // foo):
  4421. //
  4422. // 1. foo::PrintTo(const T&, ostream*)
  4423. // 2. operator<<(ostream&, const T&) defined in either foo or the
  4424. // global namespace.
  4425. //
  4426. // However if T is an STL-style container then it is printed element-wise
  4427. // unless foo::PrintTo(const T&, ostream*) is defined. Note that
  4428. // operator<<() is ignored for container types.
  4429. //
  4430. // If none of the above is defined, it will print the debug string of
  4431. // the value if it is a protocol buffer, or print the raw bytes in the
  4432. // value otherwise.
  4433. //
  4434. // To aid debugging: when T is a reference type, the address of the
  4435. // value is also printed; when T is a (const) char pointer, both the
  4436. // pointer value and the NUL-terminated string it points to are
  4437. // printed.
  4438. //
  4439. // We also provide some convenient wrappers:
  4440. //
  4441. // // Prints a value to a string. For a (const or not) char
  4442. // // pointer, the NUL-terminated string (but not the pointer) is
  4443. // // printed.
  4444. // std::string ::testing::PrintToString(const T& value);
  4445. //
  4446. // // Prints a value tersely: for a reference type, the referenced
  4447. // // value (but not the address) is printed; for a (const or not) char
  4448. // // pointer, the NUL-terminated string (but not the pointer) is
  4449. // // printed.
  4450. // void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
  4451. //
  4452. // // Prints value using the type inferred by the compiler. The difference
  4453. // // from UniversalTersePrint() is that this function prints both the
  4454. // // pointer and the NUL-terminated string for a (const or not) char pointer.
  4455. // void ::testing::internal::UniversalPrint(const T& value, ostream*);
  4456. //
  4457. // // Prints the fields of a tuple tersely to a string vector, one
  4458. // // element for each field. Tuple support must be enabled in
  4459. // // gtest-port.h.
  4460. // std::vector<string> UniversalTersePrintTupleFieldsToStrings(
  4461. // const Tuple& value);
  4462. //
  4463. // Known limitation:
  4464. //
  4465. // The print primitives print the elements of an STL-style container
  4466. // using the compiler-inferred type of *iter where iter is a
  4467. // const_iterator of the container. When const_iterator is an input
  4468. // iterator but not a forward iterator, this inferred type may not
  4469. // match value_type, and the print output may be incorrect. In
  4470. // practice, this is rarely a problem as for most containers
  4471. // const_iterator is a forward iterator. We'll fix this if there's an
  4472. // actual need for it. Note that this fix cannot rely on value_type
  4473. // being defined as many user-defined container types don't have
  4474. // value_type.
  4475. // GOOGLETEST_CM0001 DO NOT DELETE
  4476. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
  4477. #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
  4478. #include <functional>
  4479. #include <memory>
  4480. #include <ostream> // NOLINT
  4481. #include <sstream>
  4482. #include <string>
  4483. #include <tuple>
  4484. #include <type_traits>
  4485. #include <utility>
  4486. #include <vector>
  4487. #if GTEST_HAS_RTTI
  4488. #include <typeindex>
  4489. #include <typeinfo>
  4490. #endif // GTEST_HAS_RTTI
  4491. namespace testing {
  4492. // Definitions in the internal* namespaces are subject to change without notice.
  4493. // DO NOT USE THEM IN USER CODE!
  4494. namespace internal {
  4495. template <typename T>
  4496. void UniversalPrint(const T& value, ::std::ostream* os);
  4497. // Used to print an STL-style container when the user doesn't define
  4498. // a PrintTo() for it.
  4499. struct ContainerPrinter {
  4500. template <typename T,
  4501. typename = typename std::enable_if<
  4502. (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
  4503. !IsRecursiveContainer<T>::value>::type>
  4504. static void PrintValue(const T& container, std::ostream* os) {
  4505. const size_t kMaxCount = 32; // The maximum number of elements to print.
  4506. *os << '{';
  4507. size_t count = 0;
  4508. for (auto&& elem : container) {
  4509. if (count > 0) {
  4510. *os << ',';
  4511. if (count == kMaxCount) { // Enough has been printed.
  4512. *os << " ...";
  4513. break;
  4514. }
  4515. }
  4516. *os << ' ';
  4517. // We cannot call PrintTo(elem, os) here as PrintTo() doesn't
  4518. // handle `elem` being a native array.
  4519. internal::UniversalPrint(elem, os);
  4520. ++count;
  4521. }
  4522. if (count > 0) {
  4523. *os << ' ';
  4524. }
  4525. *os << '}';
  4526. }
  4527. };
  4528. // Used to print a pointer that is neither a char pointer nor a member
  4529. // pointer, when the user doesn't define PrintTo() for it. (A member
  4530. // variable pointer or member function pointer doesn't really point to
  4531. // a location in the address space. Their representation is
  4532. // implementation-defined. Therefore they will be printed as raw
  4533. // bytes.)
  4534. struct FunctionPointerPrinter {
  4535. template <typename T, typename = typename std::enable_if<
  4536. std::is_function<T>::value>::type>
  4537. static void PrintValue(T* p, ::std::ostream* os) {
  4538. if (p == nullptr) {
  4539. *os << "NULL";
  4540. } else {
  4541. // T is a function type, so '*os << p' doesn't do what we want
  4542. // (it just prints p as bool). We want to print p as a const
  4543. // void*.
  4544. *os << reinterpret_cast<const void*>(p);
  4545. }
  4546. }
  4547. };
  4548. struct PointerPrinter {
  4549. template <typename T>
  4550. static void PrintValue(T* p, ::std::ostream* os) {
  4551. if (p == nullptr) {
  4552. *os << "NULL";
  4553. } else {
  4554. // T is not a function type. We just call << to print p,
  4555. // relying on ADL to pick up user-defined << for their pointer
  4556. // types, if any.
  4557. *os << p;
  4558. }
  4559. }
  4560. };
  4561. namespace internal_stream_operator_without_lexical_name_lookup {
  4562. // The presence of an operator<< here will terminate lexical scope lookup
  4563. // straight away (even though it cannot be a match because of its argument
  4564. // types). Thus, the two operator<< calls in StreamPrinter will find only ADL
  4565. // candidates.
  4566. struct LookupBlocker {};
  4567. void operator<<(LookupBlocker, LookupBlocker);
  4568. struct StreamPrinter {
  4569. template <typename T,
  4570. // Don't accept member pointers here. We'd print them via implicit
  4571. // conversion to bool, which isn't useful.
  4572. typename = typename std::enable_if<
  4573. !std::is_member_pointer<T>::value>::type,
  4574. // Only accept types for which we can find a streaming operator via
  4575. // ADL (possibly involving implicit conversions).
  4576. typename = decltype(std::declval<std::ostream&>()
  4577. << std::declval<const T&>())>
  4578. static void PrintValue(const T& value, ::std::ostream* os) {
  4579. // Call streaming operator found by ADL, possibly with implicit conversions
  4580. // of the arguments.
  4581. *os << value;
  4582. }
  4583. };
  4584. } // namespace internal_stream_operator_without_lexical_name_lookup
  4585. struct ProtobufPrinter {
  4586. // We print a protobuf using its ShortDebugString() when the string
  4587. // doesn't exceed this many characters; otherwise we print it using
  4588. // DebugString() for better readability.
  4589. static const size_t kProtobufOneLinerMaxLength = 50;
  4590. template <typename T,
  4591. typename = typename std::enable_if<
  4592. internal::HasDebugStringAndShortDebugString<T>::value>::type>
  4593. static void PrintValue(const T& value, ::std::ostream* os) {
  4594. std::string pretty_str = value.ShortDebugString();
  4595. if (pretty_str.length() > kProtobufOneLinerMaxLength) {
  4596. pretty_str = "\n" + value.DebugString();
  4597. }
  4598. *os << ("<" + pretty_str + ">");
  4599. }
  4600. };
  4601. struct ConvertibleToIntegerPrinter {
  4602. // Since T has no << operator or PrintTo() but can be implicitly
  4603. // converted to BiggestInt, we print it as a BiggestInt.
  4604. //
  4605. // Most likely T is an enum type (either named or unnamed), in which
  4606. // case printing it as an integer is the desired behavior. In case
  4607. // T is not an enum, printing it as an integer is the best we can do
  4608. // given that it has no user-defined printer.
  4609. static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {
  4610. *os << value;
  4611. }
  4612. };
  4613. struct ConvertibleToStringViewPrinter {
  4614. #if GTEST_INTERNAL_HAS_STRING_VIEW
  4615. static void PrintValue(internal::StringView value, ::std::ostream* os) {
  4616. internal::UniversalPrint(value, os);
  4617. }
  4618. #endif
  4619. };
  4620. // Prints the given number of bytes in the given object to the given
  4621. // ostream.
  4622. GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
  4623. size_t count,
  4624. ::std::ostream* os);
  4625. struct RawBytesPrinter {
  4626. // SFINAE on `sizeof` to make sure we have a complete type.
  4627. template <typename T, size_t = sizeof(T)>
  4628. static void PrintValue(const T& value, ::std::ostream* os) {
  4629. PrintBytesInObjectTo(
  4630. static_cast<const unsigned char*>(
  4631. // Load bearing cast to void* to support iOS
  4632. reinterpret_cast<const void*>(std::addressof(value))),
  4633. sizeof(value), os);
  4634. }
  4635. };
  4636. struct FallbackPrinter {
  4637. template <typename T>
  4638. static void PrintValue(const T&, ::std::ostream* os) {
  4639. *os << "(incomplete type)";
  4640. }
  4641. };
  4642. // Try every printer in order and return the first one that works.
  4643. template <typename T, typename E, typename Printer, typename... Printers>
  4644. struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
  4645. template <typename T, typename Printer, typename... Printers>
  4646. struct FindFirstPrinter<
  4647. T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),
  4648. Printer, Printers...> {
  4649. using type = Printer;
  4650. };
  4651. // Select the best printer in the following order:
  4652. // - Print containers (they have begin/end/etc).
  4653. // - Print function pointers.
  4654. // - Print object pointers.
  4655. // - Use the stream operator, if available.
  4656. // - Print protocol buffers.
  4657. // - Print types convertible to BiggestInt.
  4658. // - Print types convertible to StringView, if available.
  4659. // - Fallback to printing the raw bytes of the object.
  4660. template <typename T>
  4661. void PrintWithFallback(const T& value, ::std::ostream* os) {
  4662. using Printer = typename FindFirstPrinter<
  4663. T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
  4664. internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
  4665. ProtobufPrinter, ConvertibleToIntegerPrinter,
  4666. ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type;
  4667. Printer::PrintValue(value, os);
  4668. }
  4669. // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
  4670. // value of type ToPrint that is an operand of a comparison assertion
  4671. // (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
  4672. // the comparison, and is used to help determine the best way to
  4673. // format the value. In particular, when the value is a C string
  4674. // (char pointer) and the other operand is an STL string object, we
  4675. // want to format the C string as a string, since we know it is
  4676. // compared by value with the string object. If the value is a char
  4677. // pointer but the other operand is not an STL string object, we don't
  4678. // know whether the pointer is supposed to point to a NUL-terminated
  4679. // string, and thus want to print it as a pointer to be safe.
  4680. //
  4681. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  4682. // The default case.
  4683. template <typename ToPrint, typename OtherOperand>
  4684. class FormatForComparison {
  4685. public:
  4686. static ::std::string Format(const ToPrint& value) {
  4687. return ::testing::PrintToString(value);
  4688. }
  4689. };
  4690. // Array.
  4691. template <typename ToPrint, size_t N, typename OtherOperand>
  4692. class FormatForComparison<ToPrint[N], OtherOperand> {
  4693. public:
  4694. static ::std::string Format(const ToPrint* value) {
  4695. return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
  4696. }
  4697. };
  4698. // By default, print C string as pointers to be safe, as we don't know
  4699. // whether they actually point to a NUL-terminated string.
  4700. #define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \
  4701. template <typename OtherOperand> \
  4702. class FormatForComparison<CharType*, OtherOperand> { \
  4703. public: \
  4704. static ::std::string Format(CharType* value) { \
  4705. return ::testing::PrintToString(static_cast<const void*>(value)); \
  4706. } \
  4707. }
  4708. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
  4709. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
  4710. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
  4711. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
  4712. #ifdef __cpp_char8_t
  4713. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
  4714. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
  4715. #endif
  4716. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
  4717. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
  4718. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
  4719. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
  4720. #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
  4721. // If a C string is compared with an STL string object, we know it's meant
  4722. // to point to a NUL-terminated string, and thus can print it as a string.
  4723. #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
  4724. template <> \
  4725. class FormatForComparison<CharType*, OtherStringType> { \
  4726. public: \
  4727. static ::std::string Format(CharType* value) { \
  4728. return ::testing::PrintToString(value); \
  4729. } \
  4730. }
  4731. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
  4732. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
  4733. #ifdef __cpp_char8_t
  4734. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
  4735. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
  4736. #endif
  4737. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
  4738. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
  4739. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
  4740. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
  4741. #if GTEST_HAS_STD_WSTRING
  4742. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
  4743. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
  4744. #endif
  4745. #undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
  4746. // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
  4747. // operand to be used in a failure message. The type (but not value)
  4748. // of the other operand may affect the format. This allows us to
  4749. // print a char* as a raw pointer when it is compared against another
  4750. // char* or void*, and print it as a C string when it is compared
  4751. // against an std::string object, for example.
  4752. //
  4753. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  4754. template <typename T1, typename T2>
  4755. std::string FormatForComparisonFailureMessage(
  4756. const T1& value, const T2& /* other_operand */) {
  4757. return FormatForComparison<T1, T2>::Format(value);
  4758. }
  4759. // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
  4760. // value to the given ostream. The caller must ensure that
  4761. // 'ostream_ptr' is not NULL, or the behavior is undefined.
  4762. //
  4763. // We define UniversalPrinter as a class template (as opposed to a
  4764. // function template), as we need to partially specialize it for
  4765. // reference types, which cannot be done with function templates.
  4766. template <typename T>
  4767. class UniversalPrinter;
  4768. // Prints the given value using the << operator if it has one;
  4769. // otherwise prints the bytes in it. This is what
  4770. // UniversalPrinter<T>::Print() does when PrintTo() is not specialized
  4771. // or overloaded for type T.
  4772. //
  4773. // A user can override this behavior for a class type Foo by defining
  4774. // an overload of PrintTo() in the namespace where Foo is defined. We
  4775. // give the user this option as sometimes defining a << operator for
  4776. // Foo is not desirable (e.g. the coding style may prevent doing it,
  4777. // or there is already a << operator but it doesn't do what the user
  4778. // wants).
  4779. template <typename T>
  4780. void PrintTo(const T& value, ::std::ostream* os) {
  4781. internal::PrintWithFallback(value, os);
  4782. }
  4783. // The following list of PrintTo() overloads tells
  4784. // UniversalPrinter<T>::Print() how to print standard types (built-in
  4785. // types, strings, plain arrays, and pointers).
  4786. // Overloads for various char types.
  4787. GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
  4788. GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
  4789. inline void PrintTo(char c, ::std::ostream* os) {
  4790. // When printing a plain char, we always treat it as unsigned. This
  4791. // way, the output won't be affected by whether the compiler thinks
  4792. // char is signed or not.
  4793. PrintTo(static_cast<unsigned char>(c), os);
  4794. }
  4795. // Overloads for other simple built-in types.
  4796. inline void PrintTo(bool x, ::std::ostream* os) {
  4797. *os << (x ? "true" : "false");
  4798. }
  4799. // Overload for wchar_t type.
  4800. // Prints a wchar_t as a symbol if it is printable or as its internal
  4801. // code otherwise and also as its decimal code (except for L'\0').
  4802. // The L'\0' char is printed as "L'\\0'". The decimal code is printed
  4803. // as signed integer when wchar_t is implemented by the compiler
  4804. // as a signed type and is printed as an unsigned integer when wchar_t
  4805. // is implemented as an unsigned type.
  4806. GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
  4807. GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
  4808. inline void PrintTo(char16_t c, ::std::ostream* os) {
  4809. PrintTo(ImplicitCast_<char32_t>(c), os);
  4810. }
  4811. #ifdef __cpp_char8_t
  4812. inline void PrintTo(char8_t c, ::std::ostream* os) {
  4813. PrintTo(ImplicitCast_<char32_t>(c), os);
  4814. }
  4815. #endif
  4816. // Overloads for C strings.
  4817. GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
  4818. inline void PrintTo(char* s, ::std::ostream* os) {
  4819. PrintTo(ImplicitCast_<const char*>(s), os);
  4820. }
  4821. // signed/unsigned char is often used for representing binary data, so
  4822. // we print pointers to it as void* to be safe.
  4823. inline void PrintTo(const signed char* s, ::std::ostream* os) {
  4824. PrintTo(ImplicitCast_<const void*>(s), os);
  4825. }
  4826. inline void PrintTo(signed char* s, ::std::ostream* os) {
  4827. PrintTo(ImplicitCast_<const void*>(s), os);
  4828. }
  4829. inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
  4830. PrintTo(ImplicitCast_<const void*>(s), os);
  4831. }
  4832. inline void PrintTo(unsigned char* s, ::std::ostream* os) {
  4833. PrintTo(ImplicitCast_<const void*>(s), os);
  4834. }
  4835. #ifdef __cpp_char8_t
  4836. // Overloads for u8 strings.
  4837. void PrintTo(const char8_t* s, ::std::ostream* os);
  4838. inline void PrintTo(char8_t* s, ::std::ostream* os) {
  4839. PrintTo(ImplicitCast_<const char8_t*>(s), os);
  4840. }
  4841. #endif
  4842. // Overloads for u16 strings.
  4843. void PrintTo(const char16_t* s, ::std::ostream* os);
  4844. inline void PrintTo(char16_t* s, ::std::ostream* os) {
  4845. PrintTo(ImplicitCast_<const char16_t*>(s), os);
  4846. }
  4847. // Overloads for u32 strings.
  4848. void PrintTo(const char32_t* s, ::std::ostream* os);
  4849. inline void PrintTo(char32_t* s, ::std::ostream* os) {
  4850. PrintTo(ImplicitCast_<const char32_t*>(s), os);
  4851. }
  4852. // MSVC can be configured to define wchar_t as a typedef of unsigned
  4853. // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
  4854. // type. When wchar_t is a typedef, defining an overload for const
  4855. // wchar_t* would cause unsigned short* be printed as a wide string,
  4856. // possibly causing invalid memory accesses.
  4857. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  4858. // Overloads for wide C strings
  4859. GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
  4860. inline void PrintTo(wchar_t* s, ::std::ostream* os) {
  4861. PrintTo(ImplicitCast_<const wchar_t*>(s), os);
  4862. }
  4863. #endif
  4864. // Overload for C arrays. Multi-dimensional arrays are printed
  4865. // properly.
  4866. // Prints the given number of elements in an array, without printing
  4867. // the curly braces.
  4868. template <typename T>
  4869. void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
  4870. UniversalPrint(a[0], os);
  4871. for (size_t i = 1; i != count; i++) {
  4872. *os << ", ";
  4873. UniversalPrint(a[i], os);
  4874. }
  4875. }
  4876. // Overloads for ::std::string.
  4877. GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
  4878. inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
  4879. PrintStringTo(s, os);
  4880. }
  4881. // Overloads for ::std::u8string
  4882. #ifdef __cpp_char8_t
  4883. GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
  4884. inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
  4885. PrintU8StringTo(s, os);
  4886. }
  4887. #endif
  4888. // Overloads for ::std::u16string
  4889. GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
  4890. inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
  4891. PrintU16StringTo(s, os);
  4892. }
  4893. // Overloads for ::std::u32string
  4894. GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
  4895. inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
  4896. PrintU32StringTo(s, os);
  4897. }
  4898. // Overloads for ::std::wstring.
  4899. #if GTEST_HAS_STD_WSTRING
  4900. GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
  4901. inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
  4902. PrintWideStringTo(s, os);
  4903. }
  4904. #endif // GTEST_HAS_STD_WSTRING
  4905. #if GTEST_INTERNAL_HAS_STRING_VIEW
  4906. // Overload for internal::StringView.
  4907. inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
  4908. PrintTo(::std::string(sp), os);
  4909. }
  4910. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  4911. inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
  4912. template <typename T>
  4913. void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
  4914. UniversalPrinter<T&>::Print(ref.get(), os);
  4915. }
  4916. inline const void* VoidifyPointer(const void* p) { return p; }
  4917. inline const void* VoidifyPointer(volatile const void* p) {
  4918. return const_cast<const void*>(p);
  4919. }
  4920. template <typename T, typename Ptr>
  4921. void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {
  4922. if (ptr == nullptr) {
  4923. *os << "(nullptr)";
  4924. } else {
  4925. // We can't print the value. Just print the pointer..
  4926. *os << "(" << (VoidifyPointer)(ptr.get()) << ")";
  4927. }
  4928. }
  4929. template <typename T, typename Ptr,
  4930. typename = typename std::enable_if<!std::is_void<T>::value &&
  4931. !std::is_array<T>::value>::type>
  4932. void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {
  4933. if (ptr == nullptr) {
  4934. *os << "(nullptr)";
  4935. } else {
  4936. *os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";
  4937. UniversalPrinter<T>::Print(*ptr, os);
  4938. *os << ")";
  4939. }
  4940. }
  4941. template <typename T, typename D>
  4942. void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {
  4943. (PrintSmartPointer<T>)(ptr, os, 0);
  4944. }
  4945. template <typename T>
  4946. void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
  4947. (PrintSmartPointer<T>)(ptr, os, 0);
  4948. }
  4949. // Helper function for printing a tuple. T must be instantiated with
  4950. // a tuple type.
  4951. template <typename T>
  4952. void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
  4953. ::std::ostream*) {}
  4954. template <typename T, size_t I>
  4955. void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
  4956. ::std::ostream* os) {
  4957. PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
  4958. GTEST_INTENTIONAL_CONST_COND_PUSH_()
  4959. if (I > 1) {
  4960. GTEST_INTENTIONAL_CONST_COND_POP_()
  4961. *os << ", ";
  4962. }
  4963. UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
  4964. std::get<I - 1>(t), os);
  4965. }
  4966. template <typename... Types>
  4967. void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
  4968. *os << "(";
  4969. PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
  4970. *os << ")";
  4971. }
  4972. // Overload for std::pair.
  4973. template <typename T1, typename T2>
  4974. void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
  4975. *os << '(';
  4976. // We cannot use UniversalPrint(value.first, os) here, as T1 may be
  4977. // a reference type. The same for printing value.second.
  4978. UniversalPrinter<T1>::Print(value.first, os);
  4979. *os << ", ";
  4980. UniversalPrinter<T2>::Print(value.second, os);
  4981. *os << ')';
  4982. }
  4983. #if GTEST_HAS_RTTI
  4984. inline void PrintTo(const ::std::type_info& value, ::std::ostream* os) {
  4985. internal::PrintTo<::std::type_info>(value, os);
  4986. *os << " (\"" << value.name() << "\")";
  4987. }
  4988. inline void PrintTo(const ::std::type_index& value, ::std::ostream* os) {
  4989. internal::PrintTo<::std::type_index>(value, os);
  4990. *os << " (\"" << value.name() << "\")";
  4991. }
  4992. #endif // GTEST_HAS_RTTI
  4993. // Implements printing a non-reference type T by letting the compiler
  4994. // pick the right overload of PrintTo() for T.
  4995. template <typename T>
  4996. class UniversalPrinter {
  4997. public:
  4998. // MSVC warns about adding const to a function type, so we want to
  4999. // disable the warning.
  5000. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
  5001. // Note: we deliberately don't call this PrintTo(), as that name
  5002. // conflicts with ::testing::internal::PrintTo in the body of the
  5003. // function.
  5004. static void Print(const T& value, ::std::ostream* os) {
  5005. // By default, ::testing::internal::PrintTo() is used for printing
  5006. // the value.
  5007. //
  5008. // Thanks to Koenig look-up, if T is a class and has its own
  5009. // PrintTo() function defined in its namespace, that function will
  5010. // be visible here. Since it is more specific than the generic ones
  5011. // in ::testing::internal, it will be picked by the compiler in the
  5012. // following statement - exactly what we want.
  5013. PrintTo(value, os);
  5014. }
  5015. GTEST_DISABLE_MSC_WARNINGS_POP_()
  5016. };
  5017. // Remove any const-qualifiers before passing a type to UniversalPrinter.
  5018. template <typename T>
  5019. class UniversalPrinter<const T> : public UniversalPrinter<T> {};
  5020. #if GTEST_INTERNAL_HAS_ANY
  5021. // Printer for std::any / absl::any
  5022. template <>
  5023. class UniversalPrinter<Any> {
  5024. public:
  5025. static void Print(const Any& value, ::std::ostream* os) {
  5026. if (value.has_value()) {
  5027. *os << "value of type " << GetTypeName(value);
  5028. } else {
  5029. *os << "no value";
  5030. }
  5031. }
  5032. private:
  5033. static std::string GetTypeName(const Any& value) {
  5034. #if GTEST_HAS_RTTI
  5035. return internal::GetTypeName(value.type());
  5036. #else
  5037. static_cast<void>(value); // possibly unused
  5038. return "<unknown_type>";
  5039. #endif // GTEST_HAS_RTTI
  5040. }
  5041. };
  5042. #endif // GTEST_INTERNAL_HAS_ANY
  5043. #if GTEST_INTERNAL_HAS_OPTIONAL
  5044. // Printer for std::optional / absl::optional
  5045. template <typename T>
  5046. class UniversalPrinter<Optional<T>> {
  5047. public:
  5048. static void Print(const Optional<T>& value, ::std::ostream* os) {
  5049. *os << '(';
  5050. if (!value) {
  5051. *os << "nullopt";
  5052. } else {
  5053. UniversalPrint(*value, os);
  5054. }
  5055. *os << ')';
  5056. }
  5057. };
  5058. #endif // GTEST_INTERNAL_HAS_OPTIONAL
  5059. #if GTEST_INTERNAL_HAS_VARIANT
  5060. // Printer for std::variant / absl::variant
  5061. template <typename... T>
  5062. class UniversalPrinter<Variant<T...>> {
  5063. public:
  5064. static void Print(const Variant<T...>& value, ::std::ostream* os) {
  5065. *os << '(';
  5066. #if GTEST_HAS_ABSL
  5067. absl::visit(Visitor{os, value.index()}, value);
  5068. #else
  5069. std::visit(Visitor{os, value.index()}, value);
  5070. #endif // GTEST_HAS_ABSL
  5071. *os << ')';
  5072. }
  5073. private:
  5074. struct Visitor {
  5075. template <typename U>
  5076. void operator()(const U& u) const {
  5077. *os << "'" << GetTypeName<U>() << "(index = " << index
  5078. << ")' with value ";
  5079. UniversalPrint(u, os);
  5080. }
  5081. ::std::ostream* os;
  5082. std::size_t index;
  5083. };
  5084. };
  5085. #endif // GTEST_INTERNAL_HAS_VARIANT
  5086. // UniversalPrintArray(begin, len, os) prints an array of 'len'
  5087. // elements, starting at address 'begin'.
  5088. template <typename T>
  5089. void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
  5090. if (len == 0) {
  5091. *os << "{}";
  5092. } else {
  5093. *os << "{ ";
  5094. const size_t kThreshold = 18;
  5095. const size_t kChunkSize = 8;
  5096. // If the array has more than kThreshold elements, we'll have to
  5097. // omit some details by printing only the first and the last
  5098. // kChunkSize elements.
  5099. if (len <= kThreshold) {
  5100. PrintRawArrayTo(begin, len, os);
  5101. } else {
  5102. PrintRawArrayTo(begin, kChunkSize, os);
  5103. *os << ", ..., ";
  5104. PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
  5105. }
  5106. *os << " }";
  5107. }
  5108. }
  5109. // This overload prints a (const) char array compactly.
  5110. GTEST_API_ void UniversalPrintArray(
  5111. const char* begin, size_t len, ::std::ostream* os);
  5112. #ifdef __cpp_char8_t
  5113. // This overload prints a (const) char8_t array compactly.
  5114. GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
  5115. ::std::ostream* os);
  5116. #endif
  5117. // This overload prints a (const) char16_t array compactly.
  5118. GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,
  5119. ::std::ostream* os);
  5120. // This overload prints a (const) char32_t array compactly.
  5121. GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
  5122. ::std::ostream* os);
  5123. // This overload prints a (const) wchar_t array compactly.
  5124. GTEST_API_ void UniversalPrintArray(
  5125. const wchar_t* begin, size_t len, ::std::ostream* os);
  5126. // Implements printing an array type T[N].
  5127. template <typename T, size_t N>
  5128. class UniversalPrinter<T[N]> {
  5129. public:
  5130. // Prints the given array, omitting some elements when there are too
  5131. // many.
  5132. static void Print(const T (&a)[N], ::std::ostream* os) {
  5133. UniversalPrintArray(a, N, os);
  5134. }
  5135. };
  5136. // Implements printing a reference type T&.
  5137. template <typename T>
  5138. class UniversalPrinter<T&> {
  5139. public:
  5140. // MSVC warns about adding const to a function type, so we want to
  5141. // disable the warning.
  5142. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
  5143. static void Print(const T& value, ::std::ostream* os) {
  5144. // Prints the address of the value. We use reinterpret_cast here
  5145. // as static_cast doesn't compile when T is a function type.
  5146. *os << "@" << reinterpret_cast<const void*>(&value) << " ";
  5147. // Then prints the value itself.
  5148. UniversalPrint(value, os);
  5149. }
  5150. GTEST_DISABLE_MSC_WARNINGS_POP_()
  5151. };
  5152. // Prints a value tersely: for a reference type, the referenced value
  5153. // (but not the address) is printed; for a (const) char pointer, the
  5154. // NUL-terminated string (but not the pointer) is printed.
  5155. template <typename T>
  5156. class UniversalTersePrinter {
  5157. public:
  5158. static void Print(const T& value, ::std::ostream* os) {
  5159. UniversalPrint(value, os);
  5160. }
  5161. };
  5162. template <typename T>
  5163. class UniversalTersePrinter<T&> {
  5164. public:
  5165. static void Print(const T& value, ::std::ostream* os) {
  5166. UniversalPrint(value, os);
  5167. }
  5168. };
  5169. template <typename T, size_t N>
  5170. class UniversalTersePrinter<T[N]> {
  5171. public:
  5172. static void Print(const T (&value)[N], ::std::ostream* os) {
  5173. UniversalPrinter<T[N]>::Print(value, os);
  5174. }
  5175. };
  5176. template <>
  5177. class UniversalTersePrinter<const char*> {
  5178. public:
  5179. static void Print(const char* str, ::std::ostream* os) {
  5180. if (str == nullptr) {
  5181. *os << "NULL";
  5182. } else {
  5183. UniversalPrint(std::string(str), os);
  5184. }
  5185. }
  5186. };
  5187. template <>
  5188. class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
  5189. };
  5190. #ifdef __cpp_char8_t
  5191. template <>
  5192. class UniversalTersePrinter<const char8_t*> {
  5193. public:
  5194. static void Print(const char8_t* str, ::std::ostream* os) {
  5195. if (str == nullptr) {
  5196. *os << "NULL";
  5197. } else {
  5198. UniversalPrint(::std::u8string(str), os);
  5199. }
  5200. }
  5201. };
  5202. template <>
  5203. class UniversalTersePrinter<char8_t*>
  5204. : public UniversalTersePrinter<const char8_t*> {};
  5205. #endif
  5206. template <>
  5207. class UniversalTersePrinter<const char16_t*> {
  5208. public:
  5209. static void Print(const char16_t* str, ::std::ostream* os) {
  5210. if (str == nullptr) {
  5211. *os << "NULL";
  5212. } else {
  5213. UniversalPrint(::std::u16string(str), os);
  5214. }
  5215. }
  5216. };
  5217. template <>
  5218. class UniversalTersePrinter<char16_t*>
  5219. : public UniversalTersePrinter<const char16_t*> {};
  5220. template <>
  5221. class UniversalTersePrinter<const char32_t*> {
  5222. public:
  5223. static void Print(const char32_t* str, ::std::ostream* os) {
  5224. if (str == nullptr) {
  5225. *os << "NULL";
  5226. } else {
  5227. UniversalPrint(::std::u32string(str), os);
  5228. }
  5229. }
  5230. };
  5231. template <>
  5232. class UniversalTersePrinter<char32_t*>
  5233. : public UniversalTersePrinter<const char32_t*> {};
  5234. #if GTEST_HAS_STD_WSTRING
  5235. template <>
  5236. class UniversalTersePrinter<const wchar_t*> {
  5237. public:
  5238. static void Print(const wchar_t* str, ::std::ostream* os) {
  5239. if (str == nullptr) {
  5240. *os << "NULL";
  5241. } else {
  5242. UniversalPrint(::std::wstring(str), os);
  5243. }
  5244. }
  5245. };
  5246. #endif
  5247. template <>
  5248. class UniversalTersePrinter<wchar_t*> {
  5249. public:
  5250. static void Print(wchar_t* str, ::std::ostream* os) {
  5251. UniversalTersePrinter<const wchar_t*>::Print(str, os);
  5252. }
  5253. };
  5254. template <typename T>
  5255. void UniversalTersePrint(const T& value, ::std::ostream* os) {
  5256. UniversalTersePrinter<T>::Print(value, os);
  5257. }
  5258. // Prints a value using the type inferred by the compiler. The
  5259. // difference between this and UniversalTersePrint() is that for a
  5260. // (const) char pointer, this prints both the pointer and the
  5261. // NUL-terminated string.
  5262. template <typename T>
  5263. void UniversalPrint(const T& value, ::std::ostream* os) {
  5264. // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
  5265. // UniversalPrinter with T directly.
  5266. typedef T T1;
  5267. UniversalPrinter<T1>::Print(value, os);
  5268. }
  5269. typedef ::std::vector< ::std::string> Strings;
  5270. // Tersely prints the first N fields of a tuple to a string vector,
  5271. // one element for each field.
  5272. template <typename Tuple>
  5273. void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
  5274. Strings*) {}
  5275. template <typename Tuple, size_t I>
  5276. void TersePrintPrefixToStrings(const Tuple& t,
  5277. std::integral_constant<size_t, I>,
  5278. Strings* strings) {
  5279. TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
  5280. strings);
  5281. ::std::stringstream ss;
  5282. UniversalTersePrint(std::get<I - 1>(t), &ss);
  5283. strings->push_back(ss.str());
  5284. }
  5285. // Prints the fields of a tuple tersely to a string vector, one
  5286. // element for each field. See the comment before
  5287. // UniversalTersePrint() for how we define "tersely".
  5288. template <typename Tuple>
  5289. Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
  5290. Strings result;
  5291. TersePrintPrefixToStrings(
  5292. value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
  5293. &result);
  5294. return result;
  5295. }
  5296. } // namespace internal
  5297. template <typename T>
  5298. ::std::string PrintToString(const T& value) {
  5299. ::std::stringstream ss;
  5300. internal::UniversalTersePrinter<T>::Print(value, &ss);
  5301. return ss.str();
  5302. }
  5303. } // namespace testing
  5304. // Include any custom printer added by the local installation.
  5305. // We must include this header at the end to make sure it can use the
  5306. // declarations from this file.
  5307. // Copyright 2015, Google Inc.
  5308. // All rights reserved.
  5309. //
  5310. // Redistribution and use in source and binary forms, with or without
  5311. // modification, are permitted provided that the following conditions are
  5312. // met:
  5313. //
  5314. // * Redistributions of source code must retain the above copyright
  5315. // notice, this list of conditions and the following disclaimer.
  5316. // * Redistributions in binary form must reproduce the above
  5317. // copyright notice, this list of conditions and the following disclaimer
  5318. // in the documentation and/or other materials provided with the
  5319. // distribution.
  5320. // * Neither the name of Google Inc. nor the names of its
  5321. // contributors may be used to endorse or promote products derived from
  5322. // this software without specific prior written permission.
  5323. //
  5324. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  5325. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5326. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  5327. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  5328. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  5329. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5330. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  5331. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  5332. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  5333. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  5334. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5335. //
  5336. // This file provides an injection point for custom printers in a local
  5337. // installation of gTest.
  5338. // It will be included from gtest-printers.h and the overrides in this file
  5339. // will be visible to everyone.
  5340. //
  5341. // Injection point for custom user configurations. See README for details
  5342. //
  5343. // ** Custom implementation starts here **
  5344. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
  5345. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
  5346. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
  5347. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
  5348. // MSVC warning C5046 is new as of VS2017 version 15.8.
  5349. #if defined(_MSC_VER) && _MSC_VER >= 1915
  5350. #define GTEST_MAYBE_5046_ 5046
  5351. #else
  5352. #define GTEST_MAYBE_5046_
  5353. #endif
  5354. GTEST_DISABLE_MSC_WARNINGS_PUSH_(
  5355. 4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
  5356. clients of class B */
  5357. /* Symbol involving type with internal linkage not defined */)
  5358. namespace testing {
  5359. // To implement a matcher Foo for type T, define:
  5360. // 1. a class FooMatcherMatcher that implements the matcher interface:
  5361. // using is_gtest_matcher = void;
  5362. // bool MatchAndExplain(const T&, std::ostream*);
  5363. // (MatchResultListener* can also be used instead of std::ostream*)
  5364. // void DescribeTo(std::ostream*);
  5365. // void DescribeNegationTo(std::ostream*);
  5366. //
  5367. // 2. a factory function that creates a Matcher<T> object from a
  5368. // FooMatcherMatcher.
  5369. class MatchResultListener {
  5370. public:
  5371. // Creates a listener object with the given underlying ostream. The
  5372. // listener does not own the ostream, and does not dereference it
  5373. // in the constructor or destructor.
  5374. explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
  5375. virtual ~MatchResultListener() = 0; // Makes this class abstract.
  5376. // Streams x to the underlying ostream; does nothing if the ostream
  5377. // is NULL.
  5378. template <typename T>
  5379. MatchResultListener& operator<<(const T& x) {
  5380. if (stream_ != nullptr) *stream_ << x;
  5381. return *this;
  5382. }
  5383. // Returns the underlying ostream.
  5384. ::std::ostream* stream() { return stream_; }
  5385. // Returns true if and only if the listener is interested in an explanation
  5386. // of the match result. A matcher's MatchAndExplain() method can use
  5387. // this information to avoid generating the explanation when no one
  5388. // intends to hear it.
  5389. bool IsInterested() const { return stream_ != nullptr; }
  5390. private:
  5391. ::std::ostream* const stream_;
  5392. GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
  5393. };
  5394. inline MatchResultListener::~MatchResultListener() {
  5395. }
  5396. // An instance of a subclass of this knows how to describe itself as a
  5397. // matcher.
  5398. class MatcherDescriberInterface {
  5399. public:
  5400. virtual ~MatcherDescriberInterface() {}
  5401. // Describes this matcher to an ostream. The function should print
  5402. // a verb phrase that describes the property a value matching this
  5403. // matcher should have. The subject of the verb phrase is the value
  5404. // being matched. For example, the DescribeTo() method of the Gt(7)
  5405. // matcher prints "is greater than 7".
  5406. virtual void DescribeTo(::std::ostream* os) const = 0;
  5407. // Describes the negation of this matcher to an ostream. For
  5408. // example, if the description of this matcher is "is greater than
  5409. // 7", the negated description could be "is not greater than 7".
  5410. // You are not required to override this when implementing
  5411. // MatcherInterface, but it is highly advised so that your matcher
  5412. // can produce good error messages.
  5413. virtual void DescribeNegationTo(::std::ostream* os) const {
  5414. *os << "not (";
  5415. DescribeTo(os);
  5416. *os << ")";
  5417. }
  5418. };
  5419. // The implementation of a matcher.
  5420. template <typename T>
  5421. class MatcherInterface : public MatcherDescriberInterface {
  5422. public:
  5423. // Returns true if and only if the matcher matches x; also explains the
  5424. // match result to 'listener' if necessary (see the next paragraph), in
  5425. // the form of a non-restrictive relative clause ("which ...",
  5426. // "whose ...", etc) that describes x. For example, the
  5427. // MatchAndExplain() method of the Pointee(...) matcher should
  5428. // generate an explanation like "which points to ...".
  5429. //
  5430. // Implementations of MatchAndExplain() should add an explanation of
  5431. // the match result *if and only if* they can provide additional
  5432. // information that's not already present (or not obvious) in the
  5433. // print-out of x and the matcher's description. Whether the match
  5434. // succeeds is not a factor in deciding whether an explanation is
  5435. // needed, as sometimes the caller needs to print a failure message
  5436. // when the match succeeds (e.g. when the matcher is used inside
  5437. // Not()).
  5438. //
  5439. // For example, a "has at least 10 elements" matcher should explain
  5440. // what the actual element count is, regardless of the match result,
  5441. // as it is useful information to the reader; on the other hand, an
  5442. // "is empty" matcher probably only needs to explain what the actual
  5443. // size is when the match fails, as it's redundant to say that the
  5444. // size is 0 when the value is already known to be empty.
  5445. //
  5446. // You should override this method when defining a new matcher.
  5447. //
  5448. // It's the responsibility of the caller (Google Test) to guarantee
  5449. // that 'listener' is not NULL. This helps to simplify a matcher's
  5450. // implementation when it doesn't care about the performance, as it
  5451. // can talk to 'listener' without checking its validity first.
  5452. // However, in order to implement dummy listeners efficiently,
  5453. // listener->stream() may be NULL.
  5454. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
  5455. // Inherits these methods from MatcherDescriberInterface:
  5456. // virtual void DescribeTo(::std::ostream* os) const = 0;
  5457. // virtual void DescribeNegationTo(::std::ostream* os) const;
  5458. };
  5459. namespace internal {
  5460. struct AnyEq {
  5461. template <typename A, typename B>
  5462. bool operator()(const A& a, const B& b) const { return a == b; }
  5463. };
  5464. struct AnyNe {
  5465. template <typename A, typename B>
  5466. bool operator()(const A& a, const B& b) const { return a != b; }
  5467. };
  5468. struct AnyLt {
  5469. template <typename A, typename B>
  5470. bool operator()(const A& a, const B& b) const { return a < b; }
  5471. };
  5472. struct AnyGt {
  5473. template <typename A, typename B>
  5474. bool operator()(const A& a, const B& b) const { return a > b; }
  5475. };
  5476. struct AnyLe {
  5477. template <typename A, typename B>
  5478. bool operator()(const A& a, const B& b) const { return a <= b; }
  5479. };
  5480. struct AnyGe {
  5481. template <typename A, typename B>
  5482. bool operator()(const A& a, const B& b) const { return a >= b; }
  5483. };
  5484. // A match result listener that ignores the explanation.
  5485. class DummyMatchResultListener : public MatchResultListener {
  5486. public:
  5487. DummyMatchResultListener() : MatchResultListener(nullptr) {}
  5488. private:
  5489. GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
  5490. };
  5491. // A match result listener that forwards the explanation to a given
  5492. // ostream. The difference between this and MatchResultListener is
  5493. // that the former is concrete.
  5494. class StreamMatchResultListener : public MatchResultListener {
  5495. public:
  5496. explicit StreamMatchResultListener(::std::ostream* os)
  5497. : MatchResultListener(os) {}
  5498. private:
  5499. GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
  5500. };
  5501. struct SharedPayloadBase {
  5502. std::atomic<int> ref{1};
  5503. void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
  5504. bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
  5505. };
  5506. template <typename T>
  5507. struct SharedPayload : SharedPayloadBase {
  5508. explicit SharedPayload(const T& v) : value(v) {}
  5509. explicit SharedPayload(T&& v) : value(std::move(v)) {}
  5510. static void Destroy(SharedPayloadBase* shared) {
  5511. delete static_cast<SharedPayload*>(shared);
  5512. }
  5513. T value;
  5514. };
  5515. template <typename T>
  5516. using is_trivially_copy_constructible =
  5517. #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 5
  5518. std::has_trivial_copy_constructor<T>;
  5519. #else
  5520. std::is_trivially_copy_constructible<T>;
  5521. #endif
  5522. // An internal class for implementing Matcher<T>, which will derive
  5523. // from it. We put functionalities common to all Matcher<T>
  5524. // specializations here to avoid code duplication.
  5525. template <typename T>
  5526. class MatcherBase : private MatcherDescriberInterface {
  5527. public:
  5528. // Returns true if and only if the matcher matches x; also explains the
  5529. // match result to 'listener'.
  5530. bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
  5531. GTEST_CHECK_(vtable_ != nullptr);
  5532. return vtable_->match_and_explain(*this, x, listener);
  5533. }
  5534. // Returns true if and only if this matcher matches x.
  5535. bool Matches(const T& x) const {
  5536. DummyMatchResultListener dummy;
  5537. return MatchAndExplain(x, &dummy);
  5538. }
  5539. // Describes this matcher to an ostream.
  5540. void DescribeTo(::std::ostream* os) const final {
  5541. GTEST_CHECK_(vtable_ != nullptr);
  5542. vtable_->describe(*this, os, false);
  5543. }
  5544. // Describes the negation of this matcher to an ostream.
  5545. void DescribeNegationTo(::std::ostream* os) const final {
  5546. GTEST_CHECK_(vtable_ != nullptr);
  5547. vtable_->describe(*this, os, true);
  5548. }
  5549. // Explains why x matches, or doesn't match, the matcher.
  5550. void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
  5551. StreamMatchResultListener listener(os);
  5552. MatchAndExplain(x, &listener);
  5553. }
  5554. // Returns the describer for this matcher object; retains ownership
  5555. // of the describer, which is only guaranteed to be alive when
  5556. // this matcher object is alive.
  5557. const MatcherDescriberInterface* GetDescriber() const {
  5558. if (vtable_ == nullptr) return nullptr;
  5559. return vtable_->get_describer(*this);
  5560. }
  5561. protected:
  5562. MatcherBase() : vtable_(nullptr), buffer_() {}
  5563. // Constructs a matcher from its implementation.
  5564. template <typename U>
  5565. explicit MatcherBase(const MatcherInterface<U>* impl)
  5566. : vtable_(nullptr), buffer_() {
  5567. Init(impl);
  5568. }
  5569. template <typename M, typename = typename std::remove_reference<
  5570. M>::type::is_gtest_matcher>
  5571. MatcherBase(M&& m) : vtable_(nullptr), buffer_() { // NOLINT
  5572. Init(std::forward<M>(m));
  5573. }
  5574. MatcherBase(const MatcherBase& other)
  5575. : vtable_(other.vtable_), buffer_(other.buffer_) {
  5576. if (IsShared()) buffer_.shared->Ref();
  5577. }
  5578. MatcherBase& operator=(const MatcherBase& other) {
  5579. if (this == &other) return *this;
  5580. Destroy();
  5581. vtable_ = other.vtable_;
  5582. buffer_ = other.buffer_;
  5583. if (IsShared()) buffer_.shared->Ref();
  5584. return *this;
  5585. }
  5586. MatcherBase(MatcherBase&& other)
  5587. : vtable_(other.vtable_), buffer_(other.buffer_) {
  5588. other.vtable_ = nullptr;
  5589. }
  5590. MatcherBase& operator=(MatcherBase&& other) {
  5591. if (this == &other) return *this;
  5592. Destroy();
  5593. vtable_ = other.vtable_;
  5594. buffer_ = other.buffer_;
  5595. other.vtable_ = nullptr;
  5596. return *this;
  5597. }
  5598. ~MatcherBase() override { Destroy(); }
  5599. private:
  5600. struct VTable {
  5601. bool (*match_and_explain)(const MatcherBase&, const T&,
  5602. MatchResultListener*);
  5603. void (*describe)(const MatcherBase&, std::ostream*, bool negation);
  5604. // Returns the captured object if it implements the interface, otherwise
  5605. // returns the MatcherBase itself.
  5606. const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
  5607. // Called on shared instances when the reference count reaches 0.
  5608. void (*shared_destroy)(SharedPayloadBase*);
  5609. };
  5610. bool IsShared() const {
  5611. return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
  5612. }
  5613. // If the implementation uses a listener, call that.
  5614. template <typename P>
  5615. static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
  5616. MatchResultListener* listener)
  5617. -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
  5618. return P::Get(m).MatchAndExplain(value, listener->stream());
  5619. }
  5620. template <typename P>
  5621. static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
  5622. MatchResultListener* listener)
  5623. -> decltype(P::Get(m).MatchAndExplain(value, listener)) {
  5624. return P::Get(m).MatchAndExplain(value, listener);
  5625. }
  5626. template <typename P>
  5627. static void DescribeImpl(const MatcherBase& m, std::ostream* os,
  5628. bool negation) {
  5629. if (negation) {
  5630. P::Get(m).DescribeNegationTo(os);
  5631. } else {
  5632. P::Get(m).DescribeTo(os);
  5633. }
  5634. }
  5635. template <typename P>
  5636. static const MatcherDescriberInterface* GetDescriberImpl(
  5637. const MatcherBase& m) {
  5638. // If the impl is a MatcherDescriberInterface, then return it.
  5639. // Otherwise use MatcherBase itself.
  5640. // This allows us to implement the GetDescriber() function without support
  5641. // from the impl, but some users really want to get their impl back when
  5642. // they call GetDescriber().
  5643. // We use std::get on a tuple as a workaround of not having `if constexpr`.
  5644. return std::get<(
  5645. std::is_convertible<decltype(&P::Get(m)),
  5646. const MatcherDescriberInterface*>::value
  5647. ? 1
  5648. : 0)>(std::make_tuple(&m, &P::Get(m)));
  5649. }
  5650. template <typename P>
  5651. const VTable* GetVTable() {
  5652. static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
  5653. &DescribeImpl<P>, &GetDescriberImpl<P>,
  5654. P::shared_destroy};
  5655. return &kVTable;
  5656. }
  5657. union Buffer {
  5658. // Add some types to give Buffer some common alignment/size use cases.
  5659. void* ptr;
  5660. double d;
  5661. int64_t i;
  5662. // And add one for the out-of-line cases.
  5663. SharedPayloadBase* shared;
  5664. };
  5665. void Destroy() {
  5666. if (IsShared() && buffer_.shared->Unref()) {
  5667. vtable_->shared_destroy(buffer_.shared);
  5668. }
  5669. }
  5670. template <typename M>
  5671. static constexpr bool IsInlined() {
  5672. return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
  5673. is_trivially_copy_constructible<M>::value &&
  5674. std::is_trivially_destructible<M>::value;
  5675. }
  5676. template <typename M, bool = MatcherBase::IsInlined<M>()>
  5677. struct ValuePolicy {
  5678. static const M& Get(const MatcherBase& m) {
  5679. // When inlined along with Init, need to be explicit to avoid violating
  5680. // strict aliasing rules.
  5681. const M *ptr = static_cast<const M*>(
  5682. static_cast<const void*>(&m.buffer_));
  5683. return *ptr;
  5684. }
  5685. static void Init(MatcherBase& m, M impl) {
  5686. ::new (static_cast<void*>(&m.buffer_)) M(impl);
  5687. }
  5688. static constexpr auto shared_destroy = nullptr;
  5689. };
  5690. template <typename M>
  5691. struct ValuePolicy<M, false> {
  5692. using Shared = SharedPayload<M>;
  5693. static const M& Get(const MatcherBase& m) {
  5694. return static_cast<Shared*>(m.buffer_.shared)->value;
  5695. }
  5696. template <typename Arg>
  5697. static void Init(MatcherBase& m, Arg&& arg) {
  5698. m.buffer_.shared = new Shared(std::forward<Arg>(arg));
  5699. }
  5700. static constexpr auto shared_destroy = &Shared::Destroy;
  5701. };
  5702. template <typename U, bool B>
  5703. struct ValuePolicy<const MatcherInterface<U>*, B> {
  5704. using M = const MatcherInterface<U>;
  5705. using Shared = SharedPayload<std::unique_ptr<M>>;
  5706. static const M& Get(const MatcherBase& m) {
  5707. return *static_cast<Shared*>(m.buffer_.shared)->value;
  5708. }
  5709. static void Init(MatcherBase& m, M* impl) {
  5710. m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
  5711. }
  5712. static constexpr auto shared_destroy = &Shared::Destroy;
  5713. };
  5714. template <typename M>
  5715. void Init(M&& m) {
  5716. using MM = typename std::decay<M>::type;
  5717. using Policy = ValuePolicy<MM>;
  5718. vtable_ = GetVTable<Policy>();
  5719. Policy::Init(*this, std::forward<M>(m));
  5720. }
  5721. const VTable* vtable_;
  5722. Buffer buffer_;
  5723. };
  5724. } // namespace internal
  5725. // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
  5726. // object that can check whether a value of type T matches. The
  5727. // implementation of Matcher<T> is just a std::shared_ptr to const
  5728. // MatcherInterface<T>. Don't inherit from Matcher!
  5729. template <typename T>
  5730. class Matcher : public internal::MatcherBase<T> {
  5731. public:
  5732. // Constructs a null matcher. Needed for storing Matcher objects in STL
  5733. // containers. A default-constructed matcher is not yet initialized. You
  5734. // cannot use it until a valid value has been assigned to it.
  5735. explicit Matcher() {} // NOLINT
  5736. // Constructs a matcher from its implementation.
  5737. explicit Matcher(const MatcherInterface<const T&>* impl)
  5738. : internal::MatcherBase<T>(impl) {}
  5739. template <typename U>
  5740. explicit Matcher(
  5741. const MatcherInterface<U>* impl,
  5742. typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
  5743. nullptr)
  5744. : internal::MatcherBase<T>(impl) {}
  5745. template <typename M, typename = typename std::remove_reference<
  5746. M>::type::is_gtest_matcher>
  5747. Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {} // NOLINT
  5748. // Implicit constructor here allows people to write
  5749. // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
  5750. Matcher(T value); // NOLINT
  5751. };
  5752. // The following two specializations allow the user to write str
  5753. // instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
  5754. // matcher is expected.
  5755. template <>
  5756. class GTEST_API_ Matcher<const std::string&>
  5757. : public internal::MatcherBase<const std::string&> {
  5758. public:
  5759. Matcher() {}
  5760. explicit Matcher(const MatcherInterface<const std::string&>* impl)
  5761. : internal::MatcherBase<const std::string&>(impl) {}
  5762. template <typename M, typename = typename std::remove_reference<
  5763. M>::type::is_gtest_matcher>
  5764. Matcher(M&& m) // NOLINT
  5765. : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
  5766. // Allows the user to write str instead of Eq(str) sometimes, where
  5767. // str is a std::string object.
  5768. Matcher(const std::string& s); // NOLINT
  5769. // Allows the user to write "foo" instead of Eq("foo") sometimes.
  5770. Matcher(const char* s); // NOLINT
  5771. };
  5772. template <>
  5773. class GTEST_API_ Matcher<std::string>
  5774. : public internal::MatcherBase<std::string> {
  5775. public:
  5776. Matcher() {}
  5777. explicit Matcher(const MatcherInterface<const std::string&>* impl)
  5778. : internal::MatcherBase<std::string>(impl) {}
  5779. explicit Matcher(const MatcherInterface<std::string>* impl)
  5780. : internal::MatcherBase<std::string>(impl) {}
  5781. template <typename M, typename = typename std::remove_reference<
  5782. M>::type::is_gtest_matcher>
  5783. Matcher(M&& m) // NOLINT
  5784. : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
  5785. // Allows the user to write str instead of Eq(str) sometimes, where
  5786. // str is a string object.
  5787. Matcher(const std::string& s); // NOLINT
  5788. // Allows the user to write "foo" instead of Eq("foo") sometimes.
  5789. Matcher(const char* s); // NOLINT
  5790. };
  5791. #if GTEST_INTERNAL_HAS_STRING_VIEW
  5792. // The following two specializations allow the user to write str
  5793. // instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
  5794. // matcher is expected.
  5795. template <>
  5796. class GTEST_API_ Matcher<const internal::StringView&>
  5797. : public internal::MatcherBase<const internal::StringView&> {
  5798. public:
  5799. Matcher() {}
  5800. explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
  5801. : internal::MatcherBase<const internal::StringView&>(impl) {}
  5802. template <typename M, typename = typename std::remove_reference<
  5803. M>::type::is_gtest_matcher>
  5804. Matcher(M&& m) // NOLINT
  5805. : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
  5806. }
  5807. // Allows the user to write str instead of Eq(str) sometimes, where
  5808. // str is a std::string object.
  5809. Matcher(const std::string& s); // NOLINT
  5810. // Allows the user to write "foo" instead of Eq("foo") sometimes.
  5811. Matcher(const char* s); // NOLINT
  5812. // Allows the user to pass absl::string_views or std::string_views directly.
  5813. Matcher(internal::StringView s); // NOLINT
  5814. };
  5815. template <>
  5816. class GTEST_API_ Matcher<internal::StringView>
  5817. : public internal::MatcherBase<internal::StringView> {
  5818. public:
  5819. Matcher() {}
  5820. explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
  5821. : internal::MatcherBase<internal::StringView>(impl) {}
  5822. explicit Matcher(const MatcherInterface<internal::StringView>* impl)
  5823. : internal::MatcherBase<internal::StringView>(impl) {}
  5824. template <typename M, typename = typename std::remove_reference<
  5825. M>::type::is_gtest_matcher>
  5826. Matcher(M&& m) // NOLINT
  5827. : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
  5828. // Allows the user to write str instead of Eq(str) sometimes, where
  5829. // str is a std::string object.
  5830. Matcher(const std::string& s); // NOLINT
  5831. // Allows the user to write "foo" instead of Eq("foo") sometimes.
  5832. Matcher(const char* s); // NOLINT
  5833. // Allows the user to pass absl::string_views or std::string_views directly.
  5834. Matcher(internal::StringView s); // NOLINT
  5835. };
  5836. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  5837. // Prints a matcher in a human-readable format.
  5838. template <typename T>
  5839. std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
  5840. matcher.DescribeTo(&os);
  5841. return os;
  5842. }
  5843. // The PolymorphicMatcher class template makes it easy to implement a
  5844. // polymorphic matcher (i.e. a matcher that can match values of more
  5845. // than one type, e.g. Eq(n) and NotNull()).
  5846. //
  5847. // To define a polymorphic matcher, a user should provide an Impl
  5848. // class that has a DescribeTo() method and a DescribeNegationTo()
  5849. // method, and define a member function (or member function template)
  5850. //
  5851. // bool MatchAndExplain(const Value& value,
  5852. // MatchResultListener* listener) const;
  5853. //
  5854. // See the definition of NotNull() for a complete example.
  5855. template <class Impl>
  5856. class PolymorphicMatcher {
  5857. public:
  5858. explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
  5859. // Returns a mutable reference to the underlying matcher
  5860. // implementation object.
  5861. Impl& mutable_impl() { return impl_; }
  5862. // Returns an immutable reference to the underlying matcher
  5863. // implementation object.
  5864. const Impl& impl() const { return impl_; }
  5865. template <typename T>
  5866. operator Matcher<T>() const {
  5867. return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
  5868. }
  5869. private:
  5870. template <typename T>
  5871. class MonomorphicImpl : public MatcherInterface<T> {
  5872. public:
  5873. explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
  5874. void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
  5875. void DescribeNegationTo(::std::ostream* os) const override {
  5876. impl_.DescribeNegationTo(os);
  5877. }
  5878. bool MatchAndExplain(T x, MatchResultListener* listener) const override {
  5879. return impl_.MatchAndExplain(x, listener);
  5880. }
  5881. private:
  5882. const Impl impl_;
  5883. };
  5884. Impl impl_;
  5885. };
  5886. // Creates a matcher from its implementation.
  5887. // DEPRECATED: Especially in the generic code, prefer:
  5888. // Matcher<T>(new MyMatcherImpl<const T&>(...));
  5889. //
  5890. // MakeMatcher may create a Matcher that accepts its argument by value, which
  5891. // leads to unnecessary copies & lack of support for non-copyable types.
  5892. template <typename T>
  5893. inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
  5894. return Matcher<T>(impl);
  5895. }
  5896. // Creates a polymorphic matcher from its implementation. This is
  5897. // easier to use than the PolymorphicMatcher<Impl> constructor as it
  5898. // doesn't require you to explicitly write the template argument, e.g.
  5899. //
  5900. // MakePolymorphicMatcher(foo);
  5901. // vs
  5902. // PolymorphicMatcher<TypeOfFoo>(foo);
  5903. template <class Impl>
  5904. inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
  5905. return PolymorphicMatcher<Impl>(impl);
  5906. }
  5907. namespace internal {
  5908. // Implements a matcher that compares a given value with a
  5909. // pre-supplied value using one of the ==, <=, <, etc, operators. The
  5910. // two values being compared don't have to have the same type.
  5911. //
  5912. // The matcher defined here is polymorphic (for example, Eq(5) can be
  5913. // used to match an int, a short, a double, etc). Therefore we use
  5914. // a template type conversion operator in the implementation.
  5915. //
  5916. // The following template definition assumes that the Rhs parameter is
  5917. // a "bare" type (i.e. neither 'const T' nor 'T&').
  5918. template <typename D, typename Rhs, typename Op>
  5919. class ComparisonBase {
  5920. public:
  5921. explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
  5922. using is_gtest_matcher = void;
  5923. template <typename Lhs>
  5924. bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
  5925. return Op()(lhs, Unwrap(rhs_));
  5926. }
  5927. void DescribeTo(std::ostream* os) const {
  5928. *os << D::Desc() << " ";
  5929. UniversalPrint(Unwrap(rhs_), os);
  5930. }
  5931. void DescribeNegationTo(std::ostream* os) const {
  5932. *os << D::NegatedDesc() << " ";
  5933. UniversalPrint(Unwrap(rhs_), os);
  5934. }
  5935. private:
  5936. template <typename T>
  5937. static const T& Unwrap(const T& v) {
  5938. return v;
  5939. }
  5940. template <typename T>
  5941. static const T& Unwrap(std::reference_wrapper<T> v) {
  5942. return v;
  5943. }
  5944. Rhs rhs_;
  5945. };
  5946. template <typename Rhs>
  5947. class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
  5948. public:
  5949. explicit EqMatcher(const Rhs& rhs)
  5950. : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
  5951. static const char* Desc() { return "is equal to"; }
  5952. static const char* NegatedDesc() { return "isn't equal to"; }
  5953. };
  5954. template <typename Rhs>
  5955. class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
  5956. public:
  5957. explicit NeMatcher(const Rhs& rhs)
  5958. : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
  5959. static const char* Desc() { return "isn't equal to"; }
  5960. static const char* NegatedDesc() { return "is equal to"; }
  5961. };
  5962. template <typename Rhs>
  5963. class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
  5964. public:
  5965. explicit LtMatcher(const Rhs& rhs)
  5966. : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
  5967. static const char* Desc() { return "is <"; }
  5968. static const char* NegatedDesc() { return "isn't <"; }
  5969. };
  5970. template <typename Rhs>
  5971. class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
  5972. public:
  5973. explicit GtMatcher(const Rhs& rhs)
  5974. : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
  5975. static const char* Desc() { return "is >"; }
  5976. static const char* NegatedDesc() { return "isn't >"; }
  5977. };
  5978. template <typename Rhs>
  5979. class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
  5980. public:
  5981. explicit LeMatcher(const Rhs& rhs)
  5982. : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
  5983. static const char* Desc() { return "is <="; }
  5984. static const char* NegatedDesc() { return "isn't <="; }
  5985. };
  5986. template <typename Rhs>
  5987. class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
  5988. public:
  5989. explicit GeMatcher(const Rhs& rhs)
  5990. : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
  5991. static const char* Desc() { return "is >="; }
  5992. static const char* NegatedDesc() { return "isn't >="; }
  5993. };
  5994. template <typename T, typename = typename std::enable_if<
  5995. std::is_constructible<std::string, T>::value>::type>
  5996. using StringLike = T;
  5997. // Implements polymorphic matchers MatchesRegex(regex) and
  5998. // ContainsRegex(regex), which can be used as a Matcher<T> as long as
  5999. // T can be converted to a string.
  6000. class MatchesRegexMatcher {
  6001. public:
  6002. MatchesRegexMatcher(const RE* regex, bool full_match)
  6003. : regex_(regex), full_match_(full_match) {}
  6004. #if GTEST_INTERNAL_HAS_STRING_VIEW
  6005. bool MatchAndExplain(const internal::StringView& s,
  6006. MatchResultListener* listener) const {
  6007. return MatchAndExplain(std::string(s), listener);
  6008. }
  6009. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  6010. // Accepts pointer types, particularly:
  6011. // const char*
  6012. // char*
  6013. // const wchar_t*
  6014. // wchar_t*
  6015. template <typename CharType>
  6016. bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
  6017. return s != nullptr && MatchAndExplain(std::string(s), listener);
  6018. }
  6019. // Matches anything that can convert to std::string.
  6020. //
  6021. // This is a template, not just a plain function with const std::string&,
  6022. // because absl::string_view has some interfering non-explicit constructors.
  6023. template <class MatcheeStringType>
  6024. bool MatchAndExplain(const MatcheeStringType& s,
  6025. MatchResultListener* /* listener */) const {
  6026. const std::string& s2(s);
  6027. return full_match_ ? RE::FullMatch(s2, *regex_)
  6028. : RE::PartialMatch(s2, *regex_);
  6029. }
  6030. void DescribeTo(::std::ostream* os) const {
  6031. *os << (full_match_ ? "matches" : "contains") << " regular expression ";
  6032. UniversalPrinter<std::string>::Print(regex_->pattern(), os);
  6033. }
  6034. void DescribeNegationTo(::std::ostream* os) const {
  6035. *os << "doesn't " << (full_match_ ? "match" : "contain")
  6036. << " regular expression ";
  6037. UniversalPrinter<std::string>::Print(regex_->pattern(), os);
  6038. }
  6039. private:
  6040. const std::shared_ptr<const RE> regex_;
  6041. const bool full_match_;
  6042. };
  6043. } // namespace internal
  6044. // Matches a string that fully matches regular expression 'regex'.
  6045. // The matcher takes ownership of 'regex'.
  6046. inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
  6047. const internal::RE* regex) {
  6048. return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
  6049. }
  6050. template <typename T = std::string>
  6051. PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
  6052. const internal::StringLike<T>& regex) {
  6053. return MatchesRegex(new internal::RE(std::string(regex)));
  6054. }
  6055. // Matches a string that contains regular expression 'regex'.
  6056. // The matcher takes ownership of 'regex'.
  6057. inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
  6058. const internal::RE* regex) {
  6059. return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
  6060. }
  6061. template <typename T = std::string>
  6062. PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
  6063. const internal::StringLike<T>& regex) {
  6064. return ContainsRegex(new internal::RE(std::string(regex)));
  6065. }
  6066. // Creates a polymorphic matcher that matches anything equal to x.
  6067. // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
  6068. // wouldn't compile.
  6069. template <typename T>
  6070. inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
  6071. // Constructs a Matcher<T> from a 'value' of type T. The constructed
  6072. // matcher matches any value that's equal to 'value'.
  6073. template <typename T>
  6074. Matcher<T>::Matcher(T value) { *this = Eq(value); }
  6075. // Creates a monomorphic matcher that matches anything with type Lhs
  6076. // and equal to rhs. A user may need to use this instead of Eq(...)
  6077. // in order to resolve an overloading ambiguity.
  6078. //
  6079. // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
  6080. // or Matcher<T>(x), but more readable than the latter.
  6081. //
  6082. // We could define similar monomorphic matchers for other comparison
  6083. // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
  6084. // it yet as those are used much less than Eq() in practice. A user
  6085. // can always write Matcher<T>(Lt(5)) to be explicit about the type,
  6086. // for example.
  6087. template <typename Lhs, typename Rhs>
  6088. inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
  6089. // Creates a polymorphic matcher that matches anything >= x.
  6090. template <typename Rhs>
  6091. inline internal::GeMatcher<Rhs> Ge(Rhs x) {
  6092. return internal::GeMatcher<Rhs>(x);
  6093. }
  6094. // Creates a polymorphic matcher that matches anything > x.
  6095. template <typename Rhs>
  6096. inline internal::GtMatcher<Rhs> Gt(Rhs x) {
  6097. return internal::GtMatcher<Rhs>(x);
  6098. }
  6099. // Creates a polymorphic matcher that matches anything <= x.
  6100. template <typename Rhs>
  6101. inline internal::LeMatcher<Rhs> Le(Rhs x) {
  6102. return internal::LeMatcher<Rhs>(x);
  6103. }
  6104. // Creates a polymorphic matcher that matches anything < x.
  6105. template <typename Rhs>
  6106. inline internal::LtMatcher<Rhs> Lt(Rhs x) {
  6107. return internal::LtMatcher<Rhs>(x);
  6108. }
  6109. // Creates a polymorphic matcher that matches anything != x.
  6110. template <typename Rhs>
  6111. inline internal::NeMatcher<Rhs> Ne(Rhs x) {
  6112. return internal::NeMatcher<Rhs>(x);
  6113. }
  6114. } // namespace testing
  6115. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
  6116. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
  6117. #include <stdio.h>
  6118. #include <memory>
  6119. namespace testing {
  6120. namespace internal {
  6121. GTEST_DECLARE_string_(internal_run_death_test);
  6122. // Names of the flags (needed for parsing Google Test flags).
  6123. const char kDeathTestStyleFlag[] = "death_test_style";
  6124. const char kDeathTestUseFork[] = "death_test_use_fork";
  6125. const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
  6126. #if GTEST_HAS_DEATH_TEST
  6127. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  6128. /* class A needs to have dll-interface to be used by clients of class B */)
  6129. // DeathTest is a class that hides much of the complexity of the
  6130. // GTEST_DEATH_TEST_ macro. It is abstract; its static Create method
  6131. // returns a concrete class that depends on the prevailing death test
  6132. // style, as defined by the --gtest_death_test_style and/or
  6133. // --gtest_internal_run_death_test flags.
  6134. // In describing the results of death tests, these terms are used with
  6135. // the corresponding definitions:
  6136. //
  6137. // exit status: The integer exit information in the format specified
  6138. // by wait(2)
  6139. // exit code: The integer code passed to exit(3), _exit(2), or
  6140. // returned from main()
  6141. class GTEST_API_ DeathTest {
  6142. public:
  6143. // Create returns false if there was an error determining the
  6144. // appropriate action to take for the current death test; for example,
  6145. // if the gtest_death_test_style flag is set to an invalid value.
  6146. // The LastMessage method will return a more detailed message in that
  6147. // case. Otherwise, the DeathTest pointer pointed to by the "test"
  6148. // argument is set. If the death test should be skipped, the pointer
  6149. // is set to NULL; otherwise, it is set to the address of a new concrete
  6150. // DeathTest object that controls the execution of the current test.
  6151. static bool Create(const char* statement, Matcher<const std::string&> matcher,
  6152. const char* file, int line, DeathTest** test);
  6153. DeathTest();
  6154. virtual ~DeathTest() { }
  6155. // A helper class that aborts a death test when it's deleted.
  6156. class ReturnSentinel {
  6157. public:
  6158. explicit ReturnSentinel(DeathTest* test) : test_(test) { }
  6159. ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
  6160. private:
  6161. DeathTest* const test_;
  6162. GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
  6163. } GTEST_ATTRIBUTE_UNUSED_;
  6164. // An enumeration of possible roles that may be taken when a death
  6165. // test is encountered. EXECUTE means that the death test logic should
  6166. // be executed immediately. OVERSEE means that the program should prepare
  6167. // the appropriate environment for a child process to execute the death
  6168. // test, then wait for it to complete.
  6169. enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
  6170. // An enumeration of the three reasons that a test might be aborted.
  6171. enum AbortReason {
  6172. TEST_ENCOUNTERED_RETURN_STATEMENT,
  6173. TEST_THREW_EXCEPTION,
  6174. TEST_DID_NOT_DIE
  6175. };
  6176. // Assumes one of the above roles.
  6177. virtual TestRole AssumeRole() = 0;
  6178. // Waits for the death test to finish and returns its status.
  6179. virtual int Wait() = 0;
  6180. // Returns true if the death test passed; that is, the test process
  6181. // exited during the test, its exit status matches a user-supplied
  6182. // predicate, and its stderr output matches a user-supplied regular
  6183. // expression.
  6184. // The user-supplied predicate may be a macro expression rather
  6185. // than a function pointer or functor, or else Wait and Passed could
  6186. // be combined.
  6187. virtual bool Passed(bool exit_status_ok) = 0;
  6188. // Signals that the death test did not die as expected.
  6189. virtual void Abort(AbortReason reason) = 0;
  6190. // Returns a human-readable outcome message regarding the outcome of
  6191. // the last death test.
  6192. static const char* LastMessage();
  6193. static void set_last_death_test_message(const std::string& message);
  6194. private:
  6195. // A string containing a description of the outcome of the last death test.
  6196. static std::string last_death_test_message_;
  6197. GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
  6198. };
  6199. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  6200. // Factory interface for death tests. May be mocked out for testing.
  6201. class DeathTestFactory {
  6202. public:
  6203. virtual ~DeathTestFactory() { }
  6204. virtual bool Create(const char* statement,
  6205. Matcher<const std::string&> matcher, const char* file,
  6206. int line, DeathTest** test) = 0;
  6207. };
  6208. // A concrete DeathTestFactory implementation for normal use.
  6209. class DefaultDeathTestFactory : public DeathTestFactory {
  6210. public:
  6211. bool Create(const char* statement, Matcher<const std::string&> matcher,
  6212. const char* file, int line, DeathTest** test) override;
  6213. };
  6214. // Returns true if exit_status describes a process that was terminated
  6215. // by a signal, or exited normally with a nonzero exit code.
  6216. GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
  6217. // A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
  6218. // and interpreted as a regex (rather than an Eq matcher) for legacy
  6219. // compatibility.
  6220. inline Matcher<const ::std::string&> MakeDeathTestMatcher(
  6221. ::testing::internal::RE regex) {
  6222. return ContainsRegex(regex.pattern());
  6223. }
  6224. inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
  6225. return ContainsRegex(regex);
  6226. }
  6227. inline Matcher<const ::std::string&> MakeDeathTestMatcher(
  6228. const ::std::string& regex) {
  6229. return ContainsRegex(regex);
  6230. }
  6231. // If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
  6232. // used directly.
  6233. inline Matcher<const ::std::string&> MakeDeathTestMatcher(
  6234. Matcher<const ::std::string&> matcher) {
  6235. return matcher;
  6236. }
  6237. // Traps C++ exceptions escaping statement and reports them as test
  6238. // failures. Note that trapping SEH exceptions is not implemented here.
  6239. # if GTEST_HAS_EXCEPTIONS
  6240. # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
  6241. try { \
  6242. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  6243. } catch (const ::std::exception& gtest_exception) { \
  6244. fprintf(\
  6245. stderr, \
  6246. "\n%s: Caught std::exception-derived exception escaping the " \
  6247. "death test statement. Exception message: %s\n", \
  6248. ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
  6249. gtest_exception.what()); \
  6250. fflush(stderr); \
  6251. death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
  6252. } catch (...) { \
  6253. death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
  6254. }
  6255. # else
  6256. # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
  6257. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
  6258. # endif
  6259. // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
  6260. // ASSERT_EXIT*, and EXPECT_EXIT*.
  6261. #define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail) \
  6262. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  6263. if (::testing::internal::AlwaysTrue()) { \
  6264. ::testing::internal::DeathTest* gtest_dt; \
  6265. if (!::testing::internal::DeathTest::Create( \
  6266. #statement, \
  6267. ::testing::internal::MakeDeathTestMatcher(regex_or_matcher), \
  6268. __FILE__, __LINE__, &gtest_dt)) { \
  6269. goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
  6270. } \
  6271. if (gtest_dt != nullptr) { \
  6272. std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \
  6273. switch (gtest_dt->AssumeRole()) { \
  6274. case ::testing::internal::DeathTest::OVERSEE_TEST: \
  6275. if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
  6276. goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
  6277. } \
  6278. break; \
  6279. case ::testing::internal::DeathTest::EXECUTE_TEST: { \
  6280. ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
  6281. gtest_dt); \
  6282. GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
  6283. gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
  6284. break; \
  6285. } \
  6286. default: \
  6287. break; \
  6288. } \
  6289. } \
  6290. } else \
  6291. GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \
  6292. : fail(::testing::internal::DeathTest::LastMessage())
  6293. // The symbol "fail" here expands to something into which a message
  6294. // can be streamed.
  6295. // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
  6296. // NDEBUG mode. In this case we need the statements to be executed and the macro
  6297. // must accept a streamed message even though the message is never printed.
  6298. // The regex object is not evaluated, but it is used to prevent "unused"
  6299. // warnings and to avoid an expression that doesn't compile in debug mode.
  6300. #define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
  6301. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  6302. if (::testing::internal::AlwaysTrue()) { \
  6303. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  6304. } else if (!::testing::internal::AlwaysTrue()) { \
  6305. ::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
  6306. } else \
  6307. ::testing::Message()
  6308. // A class representing the parsed contents of the
  6309. // --gtest_internal_run_death_test flag, as it existed when
  6310. // RUN_ALL_TESTS was called.
  6311. class InternalRunDeathTestFlag {
  6312. public:
  6313. InternalRunDeathTestFlag(const std::string& a_file,
  6314. int a_line,
  6315. int an_index,
  6316. int a_write_fd)
  6317. : file_(a_file), line_(a_line), index_(an_index),
  6318. write_fd_(a_write_fd) {}
  6319. ~InternalRunDeathTestFlag() {
  6320. if (write_fd_ >= 0)
  6321. posix::Close(write_fd_);
  6322. }
  6323. const std::string& file() const { return file_; }
  6324. int line() const { return line_; }
  6325. int index() const { return index_; }
  6326. int write_fd() const { return write_fd_; }
  6327. private:
  6328. std::string file_;
  6329. int line_;
  6330. int index_;
  6331. int write_fd_;
  6332. GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
  6333. };
  6334. // Returns a newly created InternalRunDeathTestFlag object with fields
  6335. // initialized from the GTEST_FLAG(internal_run_death_test) flag if
  6336. // the flag is specified; otherwise returns NULL.
  6337. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
  6338. #endif // GTEST_HAS_DEATH_TEST
  6339. } // namespace internal
  6340. } // namespace testing
  6341. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
  6342. namespace testing {
  6343. // This flag controls the style of death tests. Valid values are "threadsafe",
  6344. // meaning that the death test child process will re-execute the test binary
  6345. // from the start, running only a single death test, or "fast",
  6346. // meaning that the child process will execute the test logic immediately
  6347. // after forking.
  6348. GTEST_DECLARE_string_(death_test_style);
  6349. #if GTEST_HAS_DEATH_TEST
  6350. namespace internal {
  6351. // Returns a Boolean value indicating whether the caller is currently
  6352. // executing in the context of the death test child process. Tools such as
  6353. // Valgrind heap checkers may need this to modify their behavior in death
  6354. // tests. IMPORTANT: This is an internal utility. Using it may break the
  6355. // implementation of death tests. User code MUST NOT use it.
  6356. GTEST_API_ bool InDeathTestChild();
  6357. } // namespace internal
  6358. // The following macros are useful for writing death tests.
  6359. // Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
  6360. // executed:
  6361. //
  6362. // 1. It generates a warning if there is more than one active
  6363. // thread. This is because it's safe to fork() or clone() only
  6364. // when there is a single thread.
  6365. //
  6366. // 2. The parent process clone()s a sub-process and runs the death
  6367. // test in it; the sub-process exits with code 0 at the end of the
  6368. // death test, if it hasn't exited already.
  6369. //
  6370. // 3. The parent process waits for the sub-process to terminate.
  6371. //
  6372. // 4. The parent process checks the exit code and error message of
  6373. // the sub-process.
  6374. //
  6375. // Examples:
  6376. //
  6377. // ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");
  6378. // for (int i = 0; i < 5; i++) {
  6379. // EXPECT_DEATH(server.ProcessRequest(i),
  6380. // "Invalid request .* in ProcessRequest()")
  6381. // << "Failed to die on request " << i;
  6382. // }
  6383. //
  6384. // ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
  6385. //
  6386. // bool KilledBySIGHUP(int exit_code) {
  6387. // return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;
  6388. // }
  6389. //
  6390. // ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
  6391. //
  6392. // On the regular expressions used in death tests:
  6393. //
  6394. // GOOGLETEST_CM0005 DO NOT DELETE
  6395. // On POSIX-compliant systems (*nix), we use the <regex.h> library,
  6396. // which uses the POSIX extended regex syntax.
  6397. //
  6398. // On other platforms (e.g. Windows or Mac), we only support a simple regex
  6399. // syntax implemented as part of Google Test. This limited
  6400. // implementation should be enough most of the time when writing
  6401. // death tests; though it lacks many features you can find in PCRE
  6402. // or POSIX extended regex syntax. For example, we don't support
  6403. // union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and
  6404. // repetition count ("x{5,7}"), among others.
  6405. //
  6406. // Below is the syntax that we do support. We chose it to be a
  6407. // subset of both PCRE and POSIX extended regex, so it's easy to
  6408. // learn wherever you come from. In the following: 'A' denotes a
  6409. // literal character, period (.), or a single \\ escape sequence;
  6410. // 'x' and 'y' denote regular expressions; 'm' and 'n' are for
  6411. // natural numbers.
  6412. //
  6413. // c matches any literal character c
  6414. // \\d matches any decimal digit
  6415. // \\D matches any character that's not a decimal digit
  6416. // \\f matches \f
  6417. // \\n matches \n
  6418. // \\r matches \r
  6419. // \\s matches any ASCII whitespace, including \n
  6420. // \\S matches any character that's not a whitespace
  6421. // \\t matches \t
  6422. // \\v matches \v
  6423. // \\w matches any letter, _, or decimal digit
  6424. // \\W matches any character that \\w doesn't match
  6425. // \\c matches any literal character c, which must be a punctuation
  6426. // . matches any single character except \n
  6427. // A? matches 0 or 1 occurrences of A
  6428. // A* matches 0 or many occurrences of A
  6429. // A+ matches 1 or many occurrences of A
  6430. // ^ matches the beginning of a string (not that of each line)
  6431. // $ matches the end of a string (not that of each line)
  6432. // xy matches x followed by y
  6433. //
  6434. // If you accidentally use PCRE or POSIX extended regex features
  6435. // not implemented by us, you will get a run-time failure. In that
  6436. // case, please try to rewrite your regular expression within the
  6437. // above syntax.
  6438. //
  6439. // This implementation is *not* meant to be as highly tuned or robust
  6440. // as a compiled regex library, but should perform well enough for a
  6441. // death test, which already incurs significant overhead by launching
  6442. // a child process.
  6443. //
  6444. // Known caveats:
  6445. //
  6446. // A "threadsafe" style death test obtains the path to the test
  6447. // program from argv[0] and re-executes it in the sub-process. For
  6448. // simplicity, the current implementation doesn't search the PATH
  6449. // when launching the sub-process. This means that the user must
  6450. // invoke the test program via a path that contains at least one
  6451. // path separator (e.g. path/to/foo_test and
  6452. // /absolute/path/to/bar_test are fine, but foo_test is not). This
  6453. // is rarely a problem as people usually don't put the test binary
  6454. // directory in PATH.
  6455. //
  6456. // Asserts that a given statement causes the program to exit, with an
  6457. // integer exit status that satisfies predicate, and emitting error output
  6458. // that matches regex.
  6459. # define ASSERT_EXIT(statement, predicate, regex) \
  6460. GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_)
  6461. // Like ASSERT_EXIT, but continues on to successive tests in the
  6462. // test suite, if any:
  6463. # define EXPECT_EXIT(statement, predicate, regex) \
  6464. GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_)
  6465. // Asserts that a given statement causes the program to exit, either by
  6466. // explicitly exiting with a nonzero exit code or being killed by a
  6467. // signal, and emitting error output that matches regex.
  6468. # define ASSERT_DEATH(statement, regex) \
  6469. ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
  6470. // Like ASSERT_DEATH, but continues on to successive tests in the
  6471. // test suite, if any:
  6472. # define EXPECT_DEATH(statement, regex) \
  6473. EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
  6474. // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
  6475. // Tests that an exit code describes a normal exit with a given exit code.
  6476. class GTEST_API_ ExitedWithCode {
  6477. public:
  6478. explicit ExitedWithCode(int exit_code);
  6479. ExitedWithCode(const ExitedWithCode&) = default;
  6480. void operator=(const ExitedWithCode& other) = delete;
  6481. bool operator()(int exit_status) const;
  6482. private:
  6483. const int exit_code_;
  6484. };
  6485. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6486. // Tests that an exit code describes an exit due to termination by a
  6487. // given signal.
  6488. // GOOGLETEST_CM0006 DO NOT DELETE
  6489. class GTEST_API_ KilledBySignal {
  6490. public:
  6491. explicit KilledBySignal(int signum);
  6492. bool operator()(int exit_status) const;
  6493. private:
  6494. const int signum_;
  6495. };
  6496. # endif // !GTEST_OS_WINDOWS
  6497. // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
  6498. // The death testing framework causes this to have interesting semantics,
  6499. // since the sideeffects of the call are only visible in opt mode, and not
  6500. // in debug mode.
  6501. //
  6502. // In practice, this can be used to test functions that utilize the
  6503. // LOG(DFATAL) macro using the following style:
  6504. //
  6505. // int DieInDebugOr12(int* sideeffect) {
  6506. // if (sideeffect) {
  6507. // *sideeffect = 12;
  6508. // }
  6509. // LOG(DFATAL) << "death";
  6510. // return 12;
  6511. // }
  6512. //
  6513. // TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) {
  6514. // int sideeffect = 0;
  6515. // // Only asserts in dbg.
  6516. // EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
  6517. //
  6518. // #ifdef NDEBUG
  6519. // // opt-mode has sideeffect visible.
  6520. // EXPECT_EQ(12, sideeffect);
  6521. // #else
  6522. // // dbg-mode no visible sideeffect.
  6523. // EXPECT_EQ(0, sideeffect);
  6524. // #endif
  6525. // }
  6526. //
  6527. // This will assert that DieInDebugReturn12InOpt() crashes in debug
  6528. // mode, usually due to a DCHECK or LOG(DFATAL), but returns the
  6529. // appropriate fallback value (12 in this case) in opt mode. If you
  6530. // need to test that a function has appropriate side-effects in opt
  6531. // mode, include assertions against the side-effects. A general
  6532. // pattern for this is:
  6533. //
  6534. // EXPECT_DEBUG_DEATH({
  6535. // // Side-effects here will have an effect after this statement in
  6536. // // opt mode, but none in debug mode.
  6537. // EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
  6538. // }, "death");
  6539. //
  6540. # ifdef NDEBUG
  6541. # define EXPECT_DEBUG_DEATH(statement, regex) \
  6542. GTEST_EXECUTE_STATEMENT_(statement, regex)
  6543. # define ASSERT_DEBUG_DEATH(statement, regex) \
  6544. GTEST_EXECUTE_STATEMENT_(statement, regex)
  6545. # else
  6546. # define EXPECT_DEBUG_DEATH(statement, regex) \
  6547. EXPECT_DEATH(statement, regex)
  6548. # define ASSERT_DEBUG_DEATH(statement, regex) \
  6549. ASSERT_DEATH(statement, regex)
  6550. # endif // NDEBUG for EXPECT_DEBUG_DEATH
  6551. #endif // GTEST_HAS_DEATH_TEST
  6552. // This macro is used for implementing macros such as
  6553. // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
  6554. // death tests are not supported. Those macros must compile on such systems
  6555. // if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters
  6556. // on systems that support death tests. This allows one to write such a macro on
  6557. // a system that does not support death tests and be sure that it will compile
  6558. // on a death-test supporting system. It is exposed publicly so that systems
  6559. // that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST
  6560. // can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and
  6561. // ASSERT_DEATH_IF_SUPPORTED.
  6562. //
  6563. // Parameters:
  6564. // statement - A statement that a macro such as EXPECT_DEATH would test
  6565. // for program termination. This macro has to make sure this
  6566. // statement is compiled but not executed, to ensure that
  6567. // EXPECT_DEATH_IF_SUPPORTED compiles with a certain
  6568. // parameter if and only if EXPECT_DEATH compiles with it.
  6569. // regex - A regex that a macro such as EXPECT_DEATH would use to test
  6570. // the output of statement. This parameter has to be
  6571. // compiled but not evaluated by this macro, to ensure that
  6572. // this macro only accepts expressions that a macro such as
  6573. // EXPECT_DEATH would accept.
  6574. // terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
  6575. // and a return statement for ASSERT_DEATH_IF_SUPPORTED.
  6576. // This ensures that ASSERT_DEATH_IF_SUPPORTED will not
  6577. // compile inside functions where ASSERT_DEATH doesn't
  6578. // compile.
  6579. //
  6580. // The branch that has an always false condition is used to ensure that
  6581. // statement and regex are compiled (and thus syntactically correct) but
  6582. // never executed. The unreachable code macro protects the terminator
  6583. // statement from generating an 'unreachable code' warning in case
  6584. // statement unconditionally returns or throws. The Message constructor at
  6585. // the end allows the syntax of streaming additional messages into the
  6586. // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
  6587. # define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
  6588. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  6589. if (::testing::internal::AlwaysTrue()) { \
  6590. GTEST_LOG_(WARNING) \
  6591. << "Death tests are not supported on this platform.\n" \
  6592. << "Statement '" #statement "' cannot be verified."; \
  6593. } else if (::testing::internal::AlwaysFalse()) { \
  6594. ::testing::internal::RE::PartialMatch(".*", (regex)); \
  6595. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  6596. terminator; \
  6597. } else \
  6598. ::testing::Message()
  6599. // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
  6600. // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
  6601. // death tests are supported; otherwise they just issue a warning. This is
  6602. // useful when you are combining death test assertions with normal test
  6603. // assertions in one test.
  6604. #if GTEST_HAS_DEATH_TEST
  6605. # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
  6606. EXPECT_DEATH(statement, regex)
  6607. # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
  6608. ASSERT_DEATH(statement, regex)
  6609. #else
  6610. # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
  6611. GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
  6612. # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
  6613. GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
  6614. #endif
  6615. } // namespace testing
  6616. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
  6617. // Copyright 2008, Google Inc.
  6618. // All rights reserved.
  6619. //
  6620. // Redistribution and use in source and binary forms, with or without
  6621. // modification, are permitted provided that the following conditions are
  6622. // met:
  6623. //
  6624. // * Redistributions of source code must retain the above copyright
  6625. // notice, this list of conditions and the following disclaimer.
  6626. // * Redistributions in binary form must reproduce the above
  6627. // copyright notice, this list of conditions and the following disclaimer
  6628. // in the documentation and/or other materials provided with the
  6629. // distribution.
  6630. // * Neither the name of Google Inc. nor the names of its
  6631. // contributors may be used to endorse or promote products derived from
  6632. // this software without specific prior written permission.
  6633. //
  6634. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6635. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6636. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6637. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6638. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6639. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6640. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6641. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6642. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6643. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6644. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6645. //
  6646. // Macros and functions for implementing parameterized tests
  6647. // in Google C++ Testing and Mocking Framework (Google Test)
  6648. //
  6649. // GOOGLETEST_CM0001 DO NOT DELETE
  6650. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
  6651. #define GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
  6652. // Value-parameterized tests allow you to test your code with different
  6653. // parameters without writing multiple copies of the same test.
  6654. //
  6655. // Here is how you use value-parameterized tests:
  6656. #if 0
  6657. // To write value-parameterized tests, first you should define a fixture
  6658. // class. It is usually derived from testing::TestWithParam<T> (see below for
  6659. // another inheritance scheme that's sometimes useful in more complicated
  6660. // class hierarchies), where the type of your parameter values.
  6661. // TestWithParam<T> is itself derived from testing::Test. T can be any
  6662. // copyable type. If it's a raw pointer, you are responsible for managing the
  6663. // lifespan of the pointed values.
  6664. class FooTest : public ::testing::TestWithParam<const char*> {
  6665. // You can implement all the usual class fixture members here.
  6666. };
  6667. // Then, use the TEST_P macro to define as many parameterized tests
  6668. // for this fixture as you want. The _P suffix is for "parameterized"
  6669. // or "pattern", whichever you prefer to think.
  6670. TEST_P(FooTest, DoesBlah) {
  6671. // Inside a test, access the test parameter with the GetParam() method
  6672. // of the TestWithParam<T> class:
  6673. EXPECT_TRUE(foo.Blah(GetParam()));
  6674. ...
  6675. }
  6676. TEST_P(FooTest, HasBlahBlah) {
  6677. ...
  6678. }
  6679. // Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test
  6680. // case with any set of parameters you want. Google Test defines a number
  6681. // of functions for generating test parameters. They return what we call
  6682. // (surprise!) parameter generators. Here is a summary of them, which
  6683. // are all in the testing namespace:
  6684. //
  6685. //
  6686. // Range(begin, end [, step]) - Yields values {begin, begin+step,
  6687. // begin+step+step, ...}. The values do not
  6688. // include end. step defaults to 1.
  6689. // Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}.
  6690. // ValuesIn(container) - Yields values from a C-style array, an STL
  6691. // ValuesIn(begin,end) container, or an iterator range [begin, end).
  6692. // Bool() - Yields sequence {false, true}.
  6693. // Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product
  6694. // for the math savvy) of the values generated
  6695. // by the N generators.
  6696. //
  6697. // For more details, see comments at the definitions of these functions below
  6698. // in this file.
  6699. //
  6700. // The following statement will instantiate tests from the FooTest test suite
  6701. // each with parameter values "meeny", "miny", and "moe".
  6702. INSTANTIATE_TEST_SUITE_P(InstantiationName,
  6703. FooTest,
  6704. Values("meeny", "miny", "moe"));
  6705. // To distinguish different instances of the pattern, (yes, you
  6706. // can instantiate it more than once) the first argument to the
  6707. // INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the
  6708. // actual test suite name. Remember to pick unique prefixes for different
  6709. // instantiations. The tests from the instantiation above will have
  6710. // these names:
  6711. //
  6712. // * InstantiationName/FooTest.DoesBlah/0 for "meeny"
  6713. // * InstantiationName/FooTest.DoesBlah/1 for "miny"
  6714. // * InstantiationName/FooTest.DoesBlah/2 for "moe"
  6715. // * InstantiationName/FooTest.HasBlahBlah/0 for "meeny"
  6716. // * InstantiationName/FooTest.HasBlahBlah/1 for "miny"
  6717. // * InstantiationName/FooTest.HasBlahBlah/2 for "moe"
  6718. //
  6719. // You can use these names in --gtest_filter.
  6720. //
  6721. // This statement will instantiate all tests from FooTest again, each
  6722. // with parameter values "cat" and "dog":
  6723. const char* pets[] = {"cat", "dog"};
  6724. INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));
  6725. // The tests from the instantiation above will have these names:
  6726. //
  6727. // * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat"
  6728. // * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog"
  6729. // * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat"
  6730. // * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog"
  6731. //
  6732. // Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests
  6733. // in the given test suite, whether their definitions come before or
  6734. // AFTER the INSTANTIATE_TEST_SUITE_P statement.
  6735. //
  6736. // Please also note that generator expressions (including parameters to the
  6737. // generators) are evaluated in InitGoogleTest(), after main() has started.
  6738. // This allows the user on one hand, to adjust generator parameters in order
  6739. // to dynamically determine a set of tests to run and on the other hand,
  6740. // give the user a chance to inspect the generated tests with Google Test
  6741. // reflection API before RUN_ALL_TESTS() is executed.
  6742. //
  6743. // You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc
  6744. // for more examples.
  6745. //
  6746. // In the future, we plan to publish the API for defining new parameter
  6747. // generators. But for now this interface remains part of the internal
  6748. // implementation and is subject to change.
  6749. //
  6750. //
  6751. // A parameterized test fixture must be derived from testing::Test and from
  6752. // testing::WithParamInterface<T>, where T is the type of the parameter
  6753. // values. Inheriting from TestWithParam<T> satisfies that requirement because
  6754. // TestWithParam<T> inherits from both Test and WithParamInterface. In more
  6755. // complicated hierarchies, however, it is occasionally useful to inherit
  6756. // separately from Test and WithParamInterface. For example:
  6757. class BaseTest : public ::testing::Test {
  6758. // You can inherit all the usual members for a non-parameterized test
  6759. // fixture here.
  6760. };
  6761. class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {
  6762. // The usual test fixture members go here too.
  6763. };
  6764. TEST_F(BaseTest, HasFoo) {
  6765. // This is an ordinary non-parameterized test.
  6766. }
  6767. TEST_P(DerivedTest, DoesBlah) {
  6768. // GetParam works just the same here as if you inherit from TestWithParam.
  6769. EXPECT_TRUE(foo.Blah(GetParam()));
  6770. }
  6771. #endif // 0
  6772. #include <iterator>
  6773. #include <utility>
  6774. // Copyright 2008 Google Inc.
  6775. // All Rights Reserved.
  6776. //
  6777. // Redistribution and use in source and binary forms, with or without
  6778. // modification, are permitted provided that the following conditions are
  6779. // met:
  6780. //
  6781. // * Redistributions of source code must retain the above copyright
  6782. // notice, this list of conditions and the following disclaimer.
  6783. // * Redistributions in binary form must reproduce the above
  6784. // copyright notice, this list of conditions and the following disclaimer
  6785. // in the documentation and/or other materials provided with the
  6786. // distribution.
  6787. // * Neither the name of Google Inc. nor the names of its
  6788. // contributors may be used to endorse or promote products derived from
  6789. // this software without specific prior written permission.
  6790. //
  6791. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6792. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6793. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6794. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6795. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6796. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6797. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6798. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6799. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6800. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6801. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6802. // Type and function utilities for implementing parameterized tests.
  6803. // GOOGLETEST_CM0001 DO NOT DELETE
  6804. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
  6805. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
  6806. #include <ctype.h>
  6807. #include <cassert>
  6808. #include <iterator>
  6809. #include <memory>
  6810. #include <set>
  6811. #include <tuple>
  6812. #include <type_traits>
  6813. #include <utility>
  6814. #include <vector>
  6815. // Copyright 2008, Google Inc.
  6816. // All rights reserved.
  6817. //
  6818. // Redistribution and use in source and binary forms, with or without
  6819. // modification, are permitted provided that the following conditions are
  6820. // met:
  6821. //
  6822. // * Redistributions of source code must retain the above copyright
  6823. // notice, this list of conditions and the following disclaimer.
  6824. // * Redistributions in binary form must reproduce the above
  6825. // copyright notice, this list of conditions and the following disclaimer
  6826. // in the documentation and/or other materials provided with the
  6827. // distribution.
  6828. // * Neither the name of Google Inc. nor the names of its
  6829. // contributors may be used to endorse or promote products derived from
  6830. // this software without specific prior written permission.
  6831. //
  6832. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6833. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6834. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6835. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6836. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6837. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6838. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6839. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6840. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6841. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6842. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6843. //
  6844. // GOOGLETEST_CM0001 DO NOT DELETE
  6845. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
  6846. #define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
  6847. #include <iosfwd>
  6848. #include <vector>
  6849. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  6850. /* class A needs to have dll-interface to be used by clients of class B */)
  6851. namespace testing {
  6852. // A copyable object representing the result of a test part (i.e. an
  6853. // assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
  6854. //
  6855. // Don't inherit from TestPartResult as its destructor is not virtual.
  6856. class GTEST_API_ TestPartResult {
  6857. public:
  6858. // The possible outcomes of a test part (i.e. an assertion or an
  6859. // explicit SUCCEED(), FAIL(), or ADD_FAILURE()).
  6860. enum Type {
  6861. kSuccess, // Succeeded.
  6862. kNonFatalFailure, // Failed but the test can continue.
  6863. kFatalFailure, // Failed and the test should be terminated.
  6864. kSkip // Skipped.
  6865. };
  6866. // C'tor. TestPartResult does NOT have a default constructor.
  6867. // Always use this constructor (with parameters) to create a
  6868. // TestPartResult object.
  6869. TestPartResult(Type a_type, const char* a_file_name, int a_line_number,
  6870. const char* a_message)
  6871. : type_(a_type),
  6872. file_name_(a_file_name == nullptr ? "" : a_file_name),
  6873. line_number_(a_line_number),
  6874. summary_(ExtractSummary(a_message)),
  6875. message_(a_message) {}
  6876. // Gets the outcome of the test part.
  6877. Type type() const { return type_; }
  6878. // Gets the name of the source file where the test part took place, or
  6879. // NULL if it's unknown.
  6880. const char* file_name() const {
  6881. return file_name_.empty() ? nullptr : file_name_.c_str();
  6882. }
  6883. // Gets the line in the source file where the test part took place,
  6884. // or -1 if it's unknown.
  6885. int line_number() const { return line_number_; }
  6886. // Gets the summary of the failure message.
  6887. const char* summary() const { return summary_.c_str(); }
  6888. // Gets the message associated with the test part.
  6889. const char* message() const { return message_.c_str(); }
  6890. // Returns true if and only if the test part was skipped.
  6891. bool skipped() const { return type_ == kSkip; }
  6892. // Returns true if and only if the test part passed.
  6893. bool passed() const { return type_ == kSuccess; }
  6894. // Returns true if and only if the test part non-fatally failed.
  6895. bool nonfatally_failed() const { return type_ == kNonFatalFailure; }
  6896. // Returns true if and only if the test part fatally failed.
  6897. bool fatally_failed() const { return type_ == kFatalFailure; }
  6898. // Returns true if and only if the test part failed.
  6899. bool failed() const { return fatally_failed() || nonfatally_failed(); }
  6900. private:
  6901. Type type_;
  6902. // Gets the summary of the failure message by omitting the stack
  6903. // trace in it.
  6904. static std::string ExtractSummary(const char* message);
  6905. // The name of the source file where the test part took place, or
  6906. // "" if the source file is unknown.
  6907. std::string file_name_;
  6908. // The line in the source file where the test part took place, or -1
  6909. // if the line number is unknown.
  6910. int line_number_;
  6911. std::string summary_; // The test failure summary.
  6912. std::string message_; // The test failure message.
  6913. };
  6914. // Prints a TestPartResult object.
  6915. std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
  6916. // An array of TestPartResult objects.
  6917. //
  6918. // Don't inherit from TestPartResultArray as its destructor is not
  6919. // virtual.
  6920. class GTEST_API_ TestPartResultArray {
  6921. public:
  6922. TestPartResultArray() {}
  6923. // Appends the given TestPartResult to the array.
  6924. void Append(const TestPartResult& result);
  6925. // Returns the TestPartResult at the given index (0-based).
  6926. const TestPartResult& GetTestPartResult(int index) const;
  6927. // Returns the number of TestPartResult objects in the array.
  6928. int size() const;
  6929. private:
  6930. std::vector<TestPartResult> array_;
  6931. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray);
  6932. };
  6933. // This interface knows how to report a test part result.
  6934. class GTEST_API_ TestPartResultReporterInterface {
  6935. public:
  6936. virtual ~TestPartResultReporterInterface() {}
  6937. virtual void ReportTestPartResult(const TestPartResult& result) = 0;
  6938. };
  6939. namespace internal {
  6940. // This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a
  6941. // statement generates new fatal failures. To do so it registers itself as the
  6942. // current test part result reporter. Besides checking if fatal failures were
  6943. // reported, it only delegates the reporting to the former result reporter.
  6944. // The original result reporter is restored in the destructor.
  6945. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  6946. class GTEST_API_ HasNewFatalFailureHelper
  6947. : public TestPartResultReporterInterface {
  6948. public:
  6949. HasNewFatalFailureHelper();
  6950. ~HasNewFatalFailureHelper() override;
  6951. void ReportTestPartResult(const TestPartResult& result) override;
  6952. bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
  6953. private:
  6954. bool has_new_fatal_failure_;
  6955. TestPartResultReporterInterface* original_reporter_;
  6956. GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper);
  6957. };
  6958. } // namespace internal
  6959. } // namespace testing
  6960. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  6961. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
  6962. namespace testing {
  6963. // Input to a parameterized test name generator, describing a test parameter.
  6964. // Consists of the parameter value and the integer parameter index.
  6965. template <class ParamType>
  6966. struct TestParamInfo {
  6967. TestParamInfo(const ParamType& a_param, size_t an_index) :
  6968. param(a_param),
  6969. index(an_index) {}
  6970. ParamType param;
  6971. size_t index;
  6972. };
  6973. // A builtin parameterized test name generator which returns the result of
  6974. // testing::PrintToString.
  6975. struct PrintToStringParamName {
  6976. template <class ParamType>
  6977. std::string operator()(const TestParamInfo<ParamType>& info) const {
  6978. return PrintToString(info.param);
  6979. }
  6980. };
  6981. namespace internal {
  6982. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  6983. // Utility Functions
  6984. // Outputs a message explaining invalid registration of different
  6985. // fixture class for the same test suite. This may happen when
  6986. // TEST_P macro is used to define two tests with the same name
  6987. // but in different namespaces.
  6988. GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
  6989. CodeLocation code_location);
  6990. template <typename> class ParamGeneratorInterface;
  6991. template <typename> class ParamGenerator;
  6992. // Interface for iterating over elements provided by an implementation
  6993. // of ParamGeneratorInterface<T>.
  6994. template <typename T>
  6995. class ParamIteratorInterface {
  6996. public:
  6997. virtual ~ParamIteratorInterface() {}
  6998. // A pointer to the base generator instance.
  6999. // Used only for the purposes of iterator comparison
  7000. // to make sure that two iterators belong to the same generator.
  7001. virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;
  7002. // Advances iterator to point to the next element
  7003. // provided by the generator. The caller is responsible
  7004. // for not calling Advance() on an iterator equal to
  7005. // BaseGenerator()->End().
  7006. virtual void Advance() = 0;
  7007. // Clones the iterator object. Used for implementing copy semantics
  7008. // of ParamIterator<T>.
  7009. virtual ParamIteratorInterface* Clone() const = 0;
  7010. // Dereferences the current iterator and provides (read-only) access
  7011. // to the pointed value. It is the caller's responsibility not to call
  7012. // Current() on an iterator equal to BaseGenerator()->End().
  7013. // Used for implementing ParamGenerator<T>::operator*().
  7014. virtual const T* Current() const = 0;
  7015. // Determines whether the given iterator and other point to the same
  7016. // element in the sequence generated by the generator.
  7017. // Used for implementing ParamGenerator<T>::operator==().
  7018. virtual bool Equals(const ParamIteratorInterface& other) const = 0;
  7019. };
  7020. // Class iterating over elements provided by an implementation of
  7021. // ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
  7022. // and implements the const forward iterator concept.
  7023. template <typename T>
  7024. class ParamIterator {
  7025. public:
  7026. typedef T value_type;
  7027. typedef const T& reference;
  7028. typedef ptrdiff_t difference_type;
  7029. // ParamIterator assumes ownership of the impl_ pointer.
  7030. ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
  7031. ParamIterator& operator=(const ParamIterator& other) {
  7032. if (this != &other)
  7033. impl_.reset(other.impl_->Clone());
  7034. return *this;
  7035. }
  7036. const T& operator*() const { return *impl_->Current(); }
  7037. const T* operator->() const { return impl_->Current(); }
  7038. // Prefix version of operator++.
  7039. ParamIterator& operator++() {
  7040. impl_->Advance();
  7041. return *this;
  7042. }
  7043. // Postfix version of operator++.
  7044. ParamIterator operator++(int /*unused*/) {
  7045. ParamIteratorInterface<T>* clone = impl_->Clone();
  7046. impl_->Advance();
  7047. return ParamIterator(clone);
  7048. }
  7049. bool operator==(const ParamIterator& other) const {
  7050. return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);
  7051. }
  7052. bool operator!=(const ParamIterator& other) const {
  7053. return !(*this == other);
  7054. }
  7055. private:
  7056. friend class ParamGenerator<T>;
  7057. explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
  7058. std::unique_ptr<ParamIteratorInterface<T> > impl_;
  7059. };
  7060. // ParamGeneratorInterface<T> is the binary interface to access generators
  7061. // defined in other translation units.
  7062. template <typename T>
  7063. class ParamGeneratorInterface {
  7064. public:
  7065. typedef T ParamType;
  7066. virtual ~ParamGeneratorInterface() {}
  7067. // Generator interface definition
  7068. virtual ParamIteratorInterface<T>* Begin() const = 0;
  7069. virtual ParamIteratorInterface<T>* End() const = 0;
  7070. };
  7071. // Wraps ParamGeneratorInterface<T> and provides general generator syntax
  7072. // compatible with the STL Container concept.
  7073. // This class implements copy initialization semantics and the contained
  7074. // ParamGeneratorInterface<T> instance is shared among all copies
  7075. // of the original object. This is possible because that instance is immutable.
  7076. template<typename T>
  7077. class ParamGenerator {
  7078. public:
  7079. typedef ParamIterator<T> iterator;
  7080. explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}
  7081. ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}
  7082. ParamGenerator& operator=(const ParamGenerator& other) {
  7083. impl_ = other.impl_;
  7084. return *this;
  7085. }
  7086. iterator begin() const { return iterator(impl_->Begin()); }
  7087. iterator end() const { return iterator(impl_->End()); }
  7088. private:
  7089. std::shared_ptr<const ParamGeneratorInterface<T> > impl_;
  7090. };
  7091. // Generates values from a range of two comparable values. Can be used to
  7092. // generate sequences of user-defined types that implement operator+() and
  7093. // operator<().
  7094. // This class is used in the Range() function.
  7095. template <typename T, typename IncrementT>
  7096. class RangeGenerator : public ParamGeneratorInterface<T> {
  7097. public:
  7098. RangeGenerator(T begin, T end, IncrementT step)
  7099. : begin_(begin), end_(end),
  7100. step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
  7101. ~RangeGenerator() override {}
  7102. ParamIteratorInterface<T>* Begin() const override {
  7103. return new Iterator(this, begin_, 0, step_);
  7104. }
  7105. ParamIteratorInterface<T>* End() const override {
  7106. return new Iterator(this, end_, end_index_, step_);
  7107. }
  7108. private:
  7109. class Iterator : public ParamIteratorInterface<T> {
  7110. public:
  7111. Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
  7112. IncrementT step)
  7113. : base_(base), value_(value), index_(index), step_(step) {}
  7114. ~Iterator() override {}
  7115. const ParamGeneratorInterface<T>* BaseGenerator() const override {
  7116. return base_;
  7117. }
  7118. void Advance() override {
  7119. value_ = static_cast<T>(value_ + step_);
  7120. index_++;
  7121. }
  7122. ParamIteratorInterface<T>* Clone() const override {
  7123. return new Iterator(*this);
  7124. }
  7125. const T* Current() const override { return &value_; }
  7126. bool Equals(const ParamIteratorInterface<T>& other) const override {
  7127. // Having the same base generator guarantees that the other
  7128. // iterator is of the same type and we can downcast.
  7129. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
  7130. << "The program attempted to compare iterators "
  7131. << "from different generators." << std::endl;
  7132. const int other_index =
  7133. CheckedDowncastToActualType<const Iterator>(&other)->index_;
  7134. return index_ == other_index;
  7135. }
  7136. private:
  7137. Iterator(const Iterator& other)
  7138. : ParamIteratorInterface<T>(),
  7139. base_(other.base_), value_(other.value_), index_(other.index_),
  7140. step_(other.step_) {}
  7141. // No implementation - assignment is unsupported.
  7142. void operator=(const Iterator& other);
  7143. const ParamGeneratorInterface<T>* const base_;
  7144. T value_;
  7145. int index_;
  7146. const IncrementT step_;
  7147. }; // class RangeGenerator::Iterator
  7148. static int CalculateEndIndex(const T& begin,
  7149. const T& end,
  7150. const IncrementT& step) {
  7151. int end_index = 0;
  7152. for (T i = begin; i < end; i = static_cast<T>(i + step))
  7153. end_index++;
  7154. return end_index;
  7155. }
  7156. // No implementation - assignment is unsupported.
  7157. void operator=(const RangeGenerator& other);
  7158. const T begin_;
  7159. const T end_;
  7160. const IncrementT step_;
  7161. // The index for the end() iterator. All the elements in the generated
  7162. // sequence are indexed (0-based) to aid iterator comparison.
  7163. const int end_index_;
  7164. }; // class RangeGenerator
  7165. // Generates values from a pair of STL-style iterators. Used in the
  7166. // ValuesIn() function. The elements are copied from the source range
  7167. // since the source can be located on the stack, and the generator
  7168. // is likely to persist beyond that stack frame.
  7169. template <typename T>
  7170. class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
  7171. public:
  7172. template <typename ForwardIterator>
  7173. ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
  7174. : container_(begin, end) {}
  7175. ~ValuesInIteratorRangeGenerator() override {}
  7176. ParamIteratorInterface<T>* Begin() const override {
  7177. return new Iterator(this, container_.begin());
  7178. }
  7179. ParamIteratorInterface<T>* End() const override {
  7180. return new Iterator(this, container_.end());
  7181. }
  7182. private:
  7183. typedef typename ::std::vector<T> ContainerType;
  7184. class Iterator : public ParamIteratorInterface<T> {
  7185. public:
  7186. Iterator(const ParamGeneratorInterface<T>* base,
  7187. typename ContainerType::const_iterator iterator)
  7188. : base_(base), iterator_(iterator) {}
  7189. ~Iterator() override {}
  7190. const ParamGeneratorInterface<T>* BaseGenerator() const override {
  7191. return base_;
  7192. }
  7193. void Advance() override {
  7194. ++iterator_;
  7195. value_.reset();
  7196. }
  7197. ParamIteratorInterface<T>* Clone() const override {
  7198. return new Iterator(*this);
  7199. }
  7200. // We need to use cached value referenced by iterator_ because *iterator_
  7201. // can return a temporary object (and of type other then T), so just
  7202. // having "return &*iterator_;" doesn't work.
  7203. // value_ is updated here and not in Advance() because Advance()
  7204. // can advance iterator_ beyond the end of the range, and we cannot
  7205. // detect that fact. The client code, on the other hand, is
  7206. // responsible for not calling Current() on an out-of-range iterator.
  7207. const T* Current() const override {
  7208. if (value_.get() == nullptr) value_.reset(new T(*iterator_));
  7209. return value_.get();
  7210. }
  7211. bool Equals(const ParamIteratorInterface<T>& other) const override {
  7212. // Having the same base generator guarantees that the other
  7213. // iterator is of the same type and we can downcast.
  7214. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
  7215. << "The program attempted to compare iterators "
  7216. << "from different generators." << std::endl;
  7217. return iterator_ ==
  7218. CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
  7219. }
  7220. private:
  7221. Iterator(const Iterator& other)
  7222. // The explicit constructor call suppresses a false warning
  7223. // emitted by gcc when supplied with the -Wextra option.
  7224. : ParamIteratorInterface<T>(),
  7225. base_(other.base_),
  7226. iterator_(other.iterator_) {}
  7227. const ParamGeneratorInterface<T>* const base_;
  7228. typename ContainerType::const_iterator iterator_;
  7229. // A cached value of *iterator_. We keep it here to allow access by
  7230. // pointer in the wrapping iterator's operator->().
  7231. // value_ needs to be mutable to be accessed in Current().
  7232. // Use of std::unique_ptr helps manage cached value's lifetime,
  7233. // which is bound by the lifespan of the iterator itself.
  7234. mutable std::unique_ptr<const T> value_;
  7235. }; // class ValuesInIteratorRangeGenerator::Iterator
  7236. // No implementation - assignment is unsupported.
  7237. void operator=(const ValuesInIteratorRangeGenerator& other);
  7238. const ContainerType container_;
  7239. }; // class ValuesInIteratorRangeGenerator
  7240. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7241. //
  7242. // Default parameterized test name generator, returns a string containing the
  7243. // integer test parameter index.
  7244. template <class ParamType>
  7245. std::string DefaultParamName(const TestParamInfo<ParamType>& info) {
  7246. Message name_stream;
  7247. name_stream << info.index;
  7248. return name_stream.GetString();
  7249. }
  7250. template <typename T = int>
  7251. void TestNotEmpty() {
  7252. static_assert(sizeof(T) == 0, "Empty arguments are not allowed.");
  7253. }
  7254. template <typename T = int>
  7255. void TestNotEmpty(const T&) {}
  7256. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7257. //
  7258. // Stores a parameter value and later creates tests parameterized with that
  7259. // value.
  7260. template <class TestClass>
  7261. class ParameterizedTestFactory : public TestFactoryBase {
  7262. public:
  7263. typedef typename TestClass::ParamType ParamType;
  7264. explicit ParameterizedTestFactory(ParamType parameter) :
  7265. parameter_(parameter) {}
  7266. Test* CreateTest() override {
  7267. TestClass::SetParam(&parameter_);
  7268. return new TestClass();
  7269. }
  7270. private:
  7271. const ParamType parameter_;
  7272. GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
  7273. };
  7274. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7275. //
  7276. // TestMetaFactoryBase is a base class for meta-factories that create
  7277. // test factories for passing into MakeAndRegisterTestInfo function.
  7278. template <class ParamType>
  7279. class TestMetaFactoryBase {
  7280. public:
  7281. virtual ~TestMetaFactoryBase() {}
  7282. virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
  7283. };
  7284. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7285. //
  7286. // TestMetaFactory creates test factories for passing into
  7287. // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
  7288. // ownership of test factory pointer, same factory object cannot be passed
  7289. // into that method twice. But ParameterizedTestSuiteInfo is going to call
  7290. // it for each Test/Parameter value combination. Thus it needs meta factory
  7291. // creator class.
  7292. template <class TestSuite>
  7293. class TestMetaFactory
  7294. : public TestMetaFactoryBase<typename TestSuite::ParamType> {
  7295. public:
  7296. using ParamType = typename TestSuite::ParamType;
  7297. TestMetaFactory() {}
  7298. TestFactoryBase* CreateTestFactory(ParamType parameter) override {
  7299. return new ParameterizedTestFactory<TestSuite>(parameter);
  7300. }
  7301. private:
  7302. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
  7303. };
  7304. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7305. //
  7306. // ParameterizedTestSuiteInfoBase is a generic interface
  7307. // to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase
  7308. // accumulates test information provided by TEST_P macro invocations
  7309. // and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations
  7310. // and uses that information to register all resulting test instances
  7311. // in RegisterTests method. The ParameterizeTestSuiteRegistry class holds
  7312. // a collection of pointers to the ParameterizedTestSuiteInfo objects
  7313. // and calls RegisterTests() on each of them when asked.
  7314. class ParameterizedTestSuiteInfoBase {
  7315. public:
  7316. virtual ~ParameterizedTestSuiteInfoBase() {}
  7317. // Base part of test suite name for display purposes.
  7318. virtual const std::string& GetTestSuiteName() const = 0;
  7319. // Test suite id to verify identity.
  7320. virtual TypeId GetTestSuiteTypeId() const = 0;
  7321. // UnitTest class invokes this method to register tests in this
  7322. // test suite right before running them in RUN_ALL_TESTS macro.
  7323. // This method should not be called more than once on any single
  7324. // instance of a ParameterizedTestSuiteInfoBase derived class.
  7325. virtual void RegisterTests() = 0;
  7326. protected:
  7327. ParameterizedTestSuiteInfoBase() {}
  7328. private:
  7329. GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase);
  7330. };
  7331. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7332. //
  7333. // Report a the name of a test_suit as safe to ignore
  7334. // as the side effect of construction of this type.
  7335. struct MarkAsIgnored {
  7336. explicit MarkAsIgnored(const char* test_suite);
  7337. };
  7338. GTEST_API_ void InsertSyntheticTestCase(const std::string& name,
  7339. CodeLocation location, bool has_test_p);
  7340. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7341. //
  7342. // ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P
  7343. // macro invocations for a particular test suite and generators
  7344. // obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that
  7345. // test suite. It registers tests with all values generated by all
  7346. // generators when asked.
  7347. template <class TestSuite>
  7348. class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
  7349. public:
  7350. // ParamType and GeneratorCreationFunc are private types but are required
  7351. // for declarations of public methods AddTestPattern() and
  7352. // AddTestSuiteInstantiation().
  7353. using ParamType = typename TestSuite::ParamType;
  7354. // A function that returns an instance of appropriate generator type.
  7355. typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
  7356. using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&);
  7357. explicit ParameterizedTestSuiteInfo(const char* name,
  7358. CodeLocation code_location)
  7359. : test_suite_name_(name), code_location_(code_location) {}
  7360. // Test suite base name for display purposes.
  7361. const std::string& GetTestSuiteName() const override {
  7362. return test_suite_name_;
  7363. }
  7364. // Test suite id to verify identity.
  7365. TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }
  7366. // TEST_P macro uses AddTestPattern() to record information
  7367. // about a single test in a LocalTestInfo structure.
  7368. // test_suite_name is the base name of the test suite (without invocation
  7369. // prefix). test_base_name is the name of an individual test without
  7370. // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
  7371. // test suite base name and DoBar is test base name.
  7372. void AddTestPattern(const char* test_suite_name, const char* test_base_name,
  7373. TestMetaFactoryBase<ParamType>* meta_factory,
  7374. CodeLocation code_location) {
  7375. tests_.push_back(std::shared_ptr<TestInfo>(new TestInfo(
  7376. test_suite_name, test_base_name, meta_factory, code_location)));
  7377. }
  7378. // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
  7379. // about a generator.
  7380. int AddTestSuiteInstantiation(const std::string& instantiation_name,
  7381. GeneratorCreationFunc* func,
  7382. ParamNameGeneratorFunc* name_func,
  7383. const char* file, int line) {
  7384. instantiations_.push_back(
  7385. InstantiationInfo(instantiation_name, func, name_func, file, line));
  7386. return 0; // Return value used only to run this method in namespace scope.
  7387. }
  7388. // UnitTest class invokes this method to register tests in this test suite
  7389. // right before running tests in RUN_ALL_TESTS macro.
  7390. // This method should not be called more than once on any single
  7391. // instance of a ParameterizedTestSuiteInfoBase derived class.
  7392. // UnitTest has a guard to prevent from calling this method more than once.
  7393. void RegisterTests() override {
  7394. bool generated_instantiations = false;
  7395. for (typename TestInfoContainer::iterator test_it = tests_.begin();
  7396. test_it != tests_.end(); ++test_it) {
  7397. std::shared_ptr<TestInfo> test_info = *test_it;
  7398. for (typename InstantiationContainer::iterator gen_it =
  7399. instantiations_.begin(); gen_it != instantiations_.end();
  7400. ++gen_it) {
  7401. const std::string& instantiation_name = gen_it->name;
  7402. ParamGenerator<ParamType> generator((*gen_it->generator)());
  7403. ParamNameGeneratorFunc* name_func = gen_it->name_func;
  7404. const char* file = gen_it->file;
  7405. int line = gen_it->line;
  7406. std::string test_suite_name;
  7407. if ( !instantiation_name.empty() )
  7408. test_suite_name = instantiation_name + "/";
  7409. test_suite_name += test_info->test_suite_base_name;
  7410. size_t i = 0;
  7411. std::set<std::string> test_param_names;
  7412. for (typename ParamGenerator<ParamType>::iterator param_it =
  7413. generator.begin();
  7414. param_it != generator.end(); ++param_it, ++i) {
  7415. generated_instantiations = true;
  7416. Message test_name_stream;
  7417. std::string param_name = name_func(
  7418. TestParamInfo<ParamType>(*param_it, i));
  7419. GTEST_CHECK_(IsValidParamName(param_name))
  7420. << "Parameterized test name '" << param_name
  7421. << "' is invalid, in " << file
  7422. << " line " << line << std::endl;
  7423. GTEST_CHECK_(test_param_names.count(param_name) == 0)
  7424. << "Duplicate parameterized test name '" << param_name
  7425. << "', in " << file << " line " << line << std::endl;
  7426. test_param_names.insert(param_name);
  7427. if (!test_info->test_base_name.empty()) {
  7428. test_name_stream << test_info->test_base_name << "/";
  7429. }
  7430. test_name_stream << param_name;
  7431. MakeAndRegisterTestInfo(
  7432. test_suite_name.c_str(), test_name_stream.GetString().c_str(),
  7433. nullptr, // No type parameter.
  7434. PrintToString(*param_it).c_str(), test_info->code_location,
  7435. GetTestSuiteTypeId(),
  7436. SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
  7437. SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
  7438. test_info->test_meta_factory->CreateTestFactory(*param_it));
  7439. } // for param_it
  7440. } // for gen_it
  7441. } // for test_it
  7442. if (!generated_instantiations) {
  7443. // There are no generaotrs, or they all generate nothing ...
  7444. InsertSyntheticTestCase(GetTestSuiteName(), code_location_,
  7445. !tests_.empty());
  7446. }
  7447. } // RegisterTests
  7448. private:
  7449. // LocalTestInfo structure keeps information about a single test registered
  7450. // with TEST_P macro.
  7451. struct TestInfo {
  7452. TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
  7453. TestMetaFactoryBase<ParamType>* a_test_meta_factory,
  7454. CodeLocation a_code_location)
  7455. : test_suite_base_name(a_test_suite_base_name),
  7456. test_base_name(a_test_base_name),
  7457. test_meta_factory(a_test_meta_factory),
  7458. code_location(a_code_location) {}
  7459. const std::string test_suite_base_name;
  7460. const std::string test_base_name;
  7461. const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
  7462. const CodeLocation code_location;
  7463. };
  7464. using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
  7465. // Records data received from INSTANTIATE_TEST_SUITE_P macros:
  7466. // <Instantiation name, Sequence generator creation function,
  7467. // Name generator function, Source file, Source line>
  7468. struct InstantiationInfo {
  7469. InstantiationInfo(const std::string &name_in,
  7470. GeneratorCreationFunc* generator_in,
  7471. ParamNameGeneratorFunc* name_func_in,
  7472. const char* file_in,
  7473. int line_in)
  7474. : name(name_in),
  7475. generator(generator_in),
  7476. name_func(name_func_in),
  7477. file(file_in),
  7478. line(line_in) {}
  7479. std::string name;
  7480. GeneratorCreationFunc* generator;
  7481. ParamNameGeneratorFunc* name_func;
  7482. const char* file;
  7483. int line;
  7484. };
  7485. typedef ::std::vector<InstantiationInfo> InstantiationContainer;
  7486. static bool IsValidParamName(const std::string& name) {
  7487. // Check for empty string
  7488. if (name.empty())
  7489. return false;
  7490. // Check for invalid characters
  7491. for (std::string::size_type index = 0; index < name.size(); ++index) {
  7492. if (!isalnum(name[index]) && name[index] != '_')
  7493. return false;
  7494. }
  7495. return true;
  7496. }
  7497. const std::string test_suite_name_;
  7498. CodeLocation code_location_;
  7499. TestInfoContainer tests_;
  7500. InstantiationContainer instantiations_;
  7501. GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo);
  7502. }; // class ParameterizedTestSuiteInfo
  7503. // Legacy API is deprecated but still available
  7504. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  7505. template <class TestCase>
  7506. using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
  7507. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  7508. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7509. //
  7510. // ParameterizedTestSuiteRegistry contains a map of
  7511. // ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P
  7512. // and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding
  7513. // ParameterizedTestSuiteInfo descriptors.
  7514. class ParameterizedTestSuiteRegistry {
  7515. public:
  7516. ParameterizedTestSuiteRegistry() {}
  7517. ~ParameterizedTestSuiteRegistry() {
  7518. for (auto& test_suite_info : test_suite_infos_) {
  7519. delete test_suite_info;
  7520. }
  7521. }
  7522. // Looks up or creates and returns a structure containing information about
  7523. // tests and instantiations of a particular test suite.
  7524. template <class TestSuite>
  7525. ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder(
  7526. const char* test_suite_name, CodeLocation code_location) {
  7527. ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr;
  7528. for (auto& test_suite_info : test_suite_infos_) {
  7529. if (test_suite_info->GetTestSuiteName() == test_suite_name) {
  7530. if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {
  7531. // Complain about incorrect usage of Google Test facilities
  7532. // and terminate the program since we cannot guaranty correct
  7533. // test suite setup and tear-down in this case.
  7534. ReportInvalidTestSuiteType(test_suite_name, code_location);
  7535. posix::Abort();
  7536. } else {
  7537. // At this point we are sure that the object we found is of the same
  7538. // type we are looking for, so we downcast it to that type
  7539. // without further checks.
  7540. typed_test_info = CheckedDowncastToActualType<
  7541. ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info);
  7542. }
  7543. break;
  7544. }
  7545. }
  7546. if (typed_test_info == nullptr) {
  7547. typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>(
  7548. test_suite_name, code_location);
  7549. test_suite_infos_.push_back(typed_test_info);
  7550. }
  7551. return typed_test_info;
  7552. }
  7553. void RegisterTests() {
  7554. for (auto& test_suite_info : test_suite_infos_) {
  7555. test_suite_info->RegisterTests();
  7556. }
  7557. }
  7558. // Legacy API is deprecated but still available
  7559. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  7560. template <class TestCase>
  7561. ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
  7562. const char* test_case_name, CodeLocation code_location) {
  7563. return GetTestSuitePatternHolder<TestCase>(test_case_name, code_location);
  7564. }
  7565. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  7566. private:
  7567. using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>;
  7568. TestSuiteInfoContainer test_suite_infos_;
  7569. GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry);
  7570. };
  7571. // Keep track of what type-parameterized test suite are defined and
  7572. // where as well as which are intatiated. This allows susequently
  7573. // identifying suits that are defined but never used.
  7574. class TypeParameterizedTestSuiteRegistry {
  7575. public:
  7576. // Add a suite definition
  7577. void RegisterTestSuite(const char* test_suite_name,
  7578. CodeLocation code_location);
  7579. // Add an instantiation of a suit.
  7580. void RegisterInstantiation(const char* test_suite_name);
  7581. // For each suit repored as defined but not reported as instantiation,
  7582. // emit a test that reports that fact (configurably, as an error).
  7583. void CheckForInstantiations();
  7584. private:
  7585. struct TypeParameterizedTestSuiteInfo {
  7586. explicit TypeParameterizedTestSuiteInfo(CodeLocation c)
  7587. : code_location(c), instantiated(false) {}
  7588. CodeLocation code_location;
  7589. bool instantiated;
  7590. };
  7591. std::map<std::string, TypeParameterizedTestSuiteInfo> suites_;
  7592. };
  7593. } // namespace internal
  7594. // Forward declarations of ValuesIn(), which is implemented in
  7595. // include/gtest/gtest-param-test.h.
  7596. template <class Container>
  7597. internal::ParamGenerator<typename Container::value_type> ValuesIn(
  7598. const Container& container);
  7599. namespace internal {
  7600. // Used in the Values() function to provide polymorphic capabilities.
  7601. #ifdef _MSC_VER
  7602. #pragma warning(push)
  7603. #pragma warning(disable : 4100)
  7604. #endif
  7605. template <typename... Ts>
  7606. class ValueArray {
  7607. public:
  7608. explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}
  7609. template <typename T>
  7610. operator ParamGenerator<T>() const { // NOLINT
  7611. return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>()));
  7612. }
  7613. private:
  7614. template <typename T, size_t... I>
  7615. std::vector<T> MakeVector(IndexSequence<I...>) const {
  7616. return std::vector<T>{static_cast<T>(v_.template Get<I>())...};
  7617. }
  7618. FlatTuple<Ts...> v_;
  7619. };
  7620. #ifdef _MSC_VER
  7621. #pragma warning(pop)
  7622. #endif
  7623. template <typename... T>
  7624. class CartesianProductGenerator
  7625. : public ParamGeneratorInterface<::std::tuple<T...>> {
  7626. public:
  7627. typedef ::std::tuple<T...> ParamType;
  7628. CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
  7629. : generators_(g) {}
  7630. ~CartesianProductGenerator() override {}
  7631. ParamIteratorInterface<ParamType>* Begin() const override {
  7632. return new Iterator(this, generators_, false);
  7633. }
  7634. ParamIteratorInterface<ParamType>* End() const override {
  7635. return new Iterator(this, generators_, true);
  7636. }
  7637. private:
  7638. template <class I>
  7639. class IteratorImpl;
  7640. template <size_t... I>
  7641. class IteratorImpl<IndexSequence<I...>>
  7642. : public ParamIteratorInterface<ParamType> {
  7643. public:
  7644. IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
  7645. const std::tuple<ParamGenerator<T>...>& generators, bool is_end)
  7646. : base_(base),
  7647. begin_(std::get<I>(generators).begin()...),
  7648. end_(std::get<I>(generators).end()...),
  7649. current_(is_end ? end_ : begin_) {
  7650. ComputeCurrentValue();
  7651. }
  7652. ~IteratorImpl() override {}
  7653. const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
  7654. return base_;
  7655. }
  7656. // Advance should not be called on beyond-of-range iterators
  7657. // so no component iterators must be beyond end of range, either.
  7658. void Advance() override {
  7659. assert(!AtEnd());
  7660. // Advance the last iterator.
  7661. ++std::get<sizeof...(T) - 1>(current_);
  7662. // if that reaches end, propagate that up.
  7663. AdvanceIfEnd<sizeof...(T) - 1>();
  7664. ComputeCurrentValue();
  7665. }
  7666. ParamIteratorInterface<ParamType>* Clone() const override {
  7667. return new IteratorImpl(*this);
  7668. }
  7669. const ParamType* Current() const override { return current_value_.get(); }
  7670. bool Equals(const ParamIteratorInterface<ParamType>& other) const override {
  7671. // Having the same base generator guarantees that the other
  7672. // iterator is of the same type and we can downcast.
  7673. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
  7674. << "The program attempted to compare iterators "
  7675. << "from different generators." << std::endl;
  7676. const IteratorImpl* typed_other =
  7677. CheckedDowncastToActualType<const IteratorImpl>(&other);
  7678. // We must report iterators equal if they both point beyond their
  7679. // respective ranges. That can happen in a variety of fashions,
  7680. // so we have to consult AtEnd().
  7681. if (AtEnd() && typed_other->AtEnd()) return true;
  7682. bool same = true;
  7683. bool dummy[] = {
  7684. (same = same && std::get<I>(current_) ==
  7685. std::get<I>(typed_other->current_))...};
  7686. (void)dummy;
  7687. return same;
  7688. }
  7689. private:
  7690. template <size_t ThisI>
  7691. void AdvanceIfEnd() {
  7692. if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return;
  7693. bool last = ThisI == 0;
  7694. if (last) {
  7695. // We are done. Nothing else to propagate.
  7696. return;
  7697. }
  7698. constexpr size_t NextI = ThisI - (ThisI != 0);
  7699. std::get<ThisI>(current_) = std::get<ThisI>(begin_);
  7700. ++std::get<NextI>(current_);
  7701. AdvanceIfEnd<NextI>();
  7702. }
  7703. void ComputeCurrentValue() {
  7704. if (!AtEnd())
  7705. current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...);
  7706. }
  7707. bool AtEnd() const {
  7708. bool at_end = false;
  7709. bool dummy[] = {
  7710. (at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...};
  7711. (void)dummy;
  7712. return at_end;
  7713. }
  7714. const ParamGeneratorInterface<ParamType>* const base_;
  7715. std::tuple<typename ParamGenerator<T>::iterator...> begin_;
  7716. std::tuple<typename ParamGenerator<T>::iterator...> end_;
  7717. std::tuple<typename ParamGenerator<T>::iterator...> current_;
  7718. std::shared_ptr<ParamType> current_value_;
  7719. };
  7720. using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>;
  7721. std::tuple<ParamGenerator<T>...> generators_;
  7722. };
  7723. template <class... Gen>
  7724. class CartesianProductHolder {
  7725. public:
  7726. CartesianProductHolder(const Gen&... g) : generators_(g...) {}
  7727. template <typename... T>
  7728. operator ParamGenerator<::std::tuple<T...>>() const {
  7729. return ParamGenerator<::std::tuple<T...>>(
  7730. new CartesianProductGenerator<T...>(generators_));
  7731. }
  7732. private:
  7733. std::tuple<Gen...> generators_;
  7734. };
  7735. } // namespace internal
  7736. } // namespace testing
  7737. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
  7738. namespace testing {
  7739. // Functions producing parameter generators.
  7740. //
  7741. // Google Test uses these generators to produce parameters for value-
  7742. // parameterized tests. When a parameterized test suite is instantiated
  7743. // with a particular generator, Google Test creates and runs tests
  7744. // for each element in the sequence produced by the generator.
  7745. //
  7746. // In the following sample, tests from test suite FooTest are instantiated
  7747. // each three times with parameter values 3, 5, and 8:
  7748. //
  7749. // class FooTest : public TestWithParam<int> { ... };
  7750. //
  7751. // TEST_P(FooTest, TestThis) {
  7752. // }
  7753. // TEST_P(FooTest, TestThat) {
  7754. // }
  7755. // INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8));
  7756. //
  7757. // Range() returns generators providing sequences of values in a range.
  7758. //
  7759. // Synopsis:
  7760. // Range(start, end)
  7761. // - returns a generator producing a sequence of values {start, start+1,
  7762. // start+2, ..., }.
  7763. // Range(start, end, step)
  7764. // - returns a generator producing a sequence of values {start, start+step,
  7765. // start+step+step, ..., }.
  7766. // Notes:
  7767. // * The generated sequences never include end. For example, Range(1, 5)
  7768. // returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2)
  7769. // returns a generator producing {1, 3, 5, 7}.
  7770. // * start and end must have the same type. That type may be any integral or
  7771. // floating-point type or a user defined type satisfying these conditions:
  7772. // * It must be assignable (have operator=() defined).
  7773. // * It must have operator+() (operator+(int-compatible type) for
  7774. // two-operand version).
  7775. // * It must have operator<() defined.
  7776. // Elements in the resulting sequences will also have that type.
  7777. // * Condition start < end must be satisfied in order for resulting sequences
  7778. // to contain any elements.
  7779. //
  7780. template <typename T, typename IncrementT>
  7781. internal::ParamGenerator<T> Range(T start, T end, IncrementT step) {
  7782. return internal::ParamGenerator<T>(
  7783. new internal::RangeGenerator<T, IncrementT>(start, end, step));
  7784. }
  7785. template <typename T>
  7786. internal::ParamGenerator<T> Range(T start, T end) {
  7787. return Range(start, end, 1);
  7788. }
  7789. // ValuesIn() function allows generation of tests with parameters coming from
  7790. // a container.
  7791. //
  7792. // Synopsis:
  7793. // ValuesIn(const T (&array)[N])
  7794. // - returns a generator producing sequences with elements from
  7795. // a C-style array.
  7796. // ValuesIn(const Container& container)
  7797. // - returns a generator producing sequences with elements from
  7798. // an STL-style container.
  7799. // ValuesIn(Iterator begin, Iterator end)
  7800. // - returns a generator producing sequences with elements from
  7801. // a range [begin, end) defined by a pair of STL-style iterators. These
  7802. // iterators can also be plain C pointers.
  7803. //
  7804. // Please note that ValuesIn copies the values from the containers
  7805. // passed in and keeps them to generate tests in RUN_ALL_TESTS().
  7806. //
  7807. // Examples:
  7808. //
  7809. // This instantiates tests from test suite StringTest
  7810. // each with C-string values of "foo", "bar", and "baz":
  7811. //
  7812. // const char* strings[] = {"foo", "bar", "baz"};
  7813. // INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings));
  7814. //
  7815. // This instantiates tests from test suite StlStringTest
  7816. // each with STL strings with values "a" and "b":
  7817. //
  7818. // ::std::vector< ::std::string> GetParameterStrings() {
  7819. // ::std::vector< ::std::string> v;
  7820. // v.push_back("a");
  7821. // v.push_back("b");
  7822. // return v;
  7823. // }
  7824. //
  7825. // INSTANTIATE_TEST_SUITE_P(CharSequence,
  7826. // StlStringTest,
  7827. // ValuesIn(GetParameterStrings()));
  7828. //
  7829. //
  7830. // This will also instantiate tests from CharTest
  7831. // each with parameter values 'a' and 'b':
  7832. //
  7833. // ::std::list<char> GetParameterChars() {
  7834. // ::std::list<char> list;
  7835. // list.push_back('a');
  7836. // list.push_back('b');
  7837. // return list;
  7838. // }
  7839. // ::std::list<char> l = GetParameterChars();
  7840. // INSTANTIATE_TEST_SUITE_P(CharSequence2,
  7841. // CharTest,
  7842. // ValuesIn(l.begin(), l.end()));
  7843. //
  7844. template <typename ForwardIterator>
  7845. internal::ParamGenerator<
  7846. typename std::iterator_traits<ForwardIterator>::value_type>
  7847. ValuesIn(ForwardIterator begin, ForwardIterator end) {
  7848. typedef typename std::iterator_traits<ForwardIterator>::value_type ParamType;
  7849. return internal::ParamGenerator<ParamType>(
  7850. new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end));
  7851. }
  7852. template <typename T, size_t N>
  7853. internal::ParamGenerator<T> ValuesIn(const T (&array)[N]) {
  7854. return ValuesIn(array, array + N);
  7855. }
  7856. template <class Container>
  7857. internal::ParamGenerator<typename Container::value_type> ValuesIn(
  7858. const Container& container) {
  7859. return ValuesIn(container.begin(), container.end());
  7860. }
  7861. // Values() allows generating tests from explicitly specified list of
  7862. // parameters.
  7863. //
  7864. // Synopsis:
  7865. // Values(T v1, T v2, ..., T vN)
  7866. // - returns a generator producing sequences with elements v1, v2, ..., vN.
  7867. //
  7868. // For example, this instantiates tests from test suite BarTest each
  7869. // with values "one", "two", and "three":
  7870. //
  7871. // INSTANTIATE_TEST_SUITE_P(NumSequence,
  7872. // BarTest,
  7873. // Values("one", "two", "three"));
  7874. //
  7875. // This instantiates tests from test suite BazTest each with values 1, 2, 3.5.
  7876. // The exact type of values will depend on the type of parameter in BazTest.
  7877. //
  7878. // INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5));
  7879. //
  7880. //
  7881. template <typename... T>
  7882. internal::ValueArray<T...> Values(T... v) {
  7883. return internal::ValueArray<T...>(std::move(v)...);
  7884. }
  7885. // Bool() allows generating tests with parameters in a set of (false, true).
  7886. //
  7887. // Synopsis:
  7888. // Bool()
  7889. // - returns a generator producing sequences with elements {false, true}.
  7890. //
  7891. // It is useful when testing code that depends on Boolean flags. Combinations
  7892. // of multiple flags can be tested when several Bool()'s are combined using
  7893. // Combine() function.
  7894. //
  7895. // In the following example all tests in the test suite FlagDependentTest
  7896. // will be instantiated twice with parameters false and true.
  7897. //
  7898. // class FlagDependentTest : public testing::TestWithParam<bool> {
  7899. // virtual void SetUp() {
  7900. // external_flag = GetParam();
  7901. // }
  7902. // }
  7903. // INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());
  7904. //
  7905. inline internal::ParamGenerator<bool> Bool() {
  7906. return Values(false, true);
  7907. }
  7908. // Combine() allows the user to combine two or more sequences to produce
  7909. // values of a Cartesian product of those sequences' elements.
  7910. //
  7911. // Synopsis:
  7912. // Combine(gen1, gen2, ..., genN)
  7913. // - returns a generator producing sequences with elements coming from
  7914. // the Cartesian product of elements from the sequences generated by
  7915. // gen1, gen2, ..., genN. The sequence elements will have a type of
  7916. // std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
  7917. // of elements from sequences produces by gen1, gen2, ..., genN.
  7918. //
  7919. // Example:
  7920. //
  7921. // This will instantiate tests in test suite AnimalTest each one with
  7922. // the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
  7923. // tuple("dog", BLACK), and tuple("dog", WHITE):
  7924. //
  7925. // enum Color { BLACK, GRAY, WHITE };
  7926. // class AnimalTest
  7927. // : public testing::TestWithParam<std::tuple<const char*, Color> > {...};
  7928. //
  7929. // TEST_P(AnimalTest, AnimalLooksNice) {...}
  7930. //
  7931. // INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
  7932. // Combine(Values("cat", "dog"),
  7933. // Values(BLACK, WHITE)));
  7934. //
  7935. // This will instantiate tests in FlagDependentTest with all variations of two
  7936. // Boolean flags:
  7937. //
  7938. // class FlagDependentTest
  7939. // : public testing::TestWithParam<std::tuple<bool, bool> > {
  7940. // virtual void SetUp() {
  7941. // // Assigns external_flag_1 and external_flag_2 values from the tuple.
  7942. // std::tie(external_flag_1, external_flag_2) = GetParam();
  7943. // }
  7944. // };
  7945. //
  7946. // TEST_P(FlagDependentTest, TestFeature1) {
  7947. // // Test your code using external_flag_1 and external_flag_2 here.
  7948. // }
  7949. // INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest,
  7950. // Combine(Bool(), Bool()));
  7951. //
  7952. template <typename... Generator>
  7953. internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
  7954. return internal::CartesianProductHolder<Generator...>(g...);
  7955. }
  7956. #define TEST_P(test_suite_name, test_name) \
  7957. class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
  7958. : public test_suite_name { \
  7959. public: \
  7960. GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
  7961. void TestBody() override; \
  7962. \
  7963. private: \
  7964. static int AddToRegistry() { \
  7965. ::testing::UnitTest::GetInstance() \
  7966. ->parameterized_test_registry() \
  7967. .GetTestSuitePatternHolder<test_suite_name>( \
  7968. GTEST_STRINGIFY_(test_suite_name), \
  7969. ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
  7970. ->AddTestPattern( \
  7971. GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \
  7972. new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
  7973. test_suite_name, test_name)>(), \
  7974. ::testing::internal::CodeLocation(__FILE__, __LINE__)); \
  7975. return 0; \
  7976. } \
  7977. static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
  7978. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
  7979. test_name)); \
  7980. }; \
  7981. int GTEST_TEST_CLASS_NAME_(test_suite_name, \
  7982. test_name)::gtest_registering_dummy_ = \
  7983. GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry(); \
  7984. void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
  7985. // The last argument to INSTANTIATE_TEST_SUITE_P allows the user to specify
  7986. // generator and an optional function or functor that generates custom test name
  7987. // suffixes based on the test parameters. Such a function or functor should
  7988. // accept one argument of type testing::TestParamInfo<class ParamType>, and
  7989. // return std::string.
  7990. //
  7991. // testing::PrintToStringParamName is a builtin test suffix generator that
  7992. // returns the value of testing::PrintToString(GetParam()).
  7993. //
  7994. // Note: test names must be non-empty, unique, and may only contain ASCII
  7995. // alphanumeric characters or underscore. Because PrintToString adds quotes
  7996. // to std::string and C strings, it won't work for these types.
  7997. #define GTEST_EXPAND_(arg) arg
  7998. #define GTEST_GET_FIRST_(first, ...) first
  7999. #define GTEST_GET_SECOND_(first, second, ...) second
  8000. #define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
  8001. static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
  8002. gtest_##prefix##test_suite_name##_EvalGenerator_() { \
  8003. return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
  8004. } \
  8005. static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
  8006. const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
  8007. if (::testing::internal::AlwaysFalse()) { \
  8008. ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
  8009. __VA_ARGS__, \
  8010. ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
  8011. DUMMY_PARAM_))); \
  8012. auto t = std::make_tuple(__VA_ARGS__); \
  8013. static_assert(std::tuple_size<decltype(t)>::value <= 2, \
  8014. "Too Many Args!"); \
  8015. } \
  8016. return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
  8017. __VA_ARGS__, \
  8018. ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
  8019. DUMMY_PARAM_))))(info); \
  8020. } \
  8021. static int gtest_##prefix##test_suite_name##_dummy_ \
  8022. GTEST_ATTRIBUTE_UNUSED_ = \
  8023. ::testing::UnitTest::GetInstance() \
  8024. ->parameterized_test_registry() \
  8025. .GetTestSuitePatternHolder<test_suite_name>( \
  8026. GTEST_STRINGIFY_(test_suite_name), \
  8027. ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
  8028. ->AddTestSuiteInstantiation( \
  8029. GTEST_STRINGIFY_(prefix), \
  8030. &gtest_##prefix##test_suite_name##_EvalGenerator_, \
  8031. &gtest_##prefix##test_suite_name##_EvalGenerateName_, \
  8032. __FILE__, __LINE__)
  8033. // Allow Marking a Parameterized test class as not needing to be instantiated.
  8034. #define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \
  8035. namespace gtest_do_not_use_outside_namespace_scope {} \
  8036. static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
  8037. GTEST_STRINGIFY_(T))
  8038. // Legacy API is deprecated but still available
  8039. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8040. #define INSTANTIATE_TEST_CASE_P \
  8041. static_assert(::testing::internal::InstantiateTestCase_P_IsDeprecated(), \
  8042. ""); \
  8043. INSTANTIATE_TEST_SUITE_P
  8044. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8045. } // namespace testing
  8046. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
  8047. // Copyright 2006, Google Inc.
  8048. // All rights reserved.
  8049. //
  8050. // Redistribution and use in source and binary forms, with or without
  8051. // modification, are permitted provided that the following conditions are
  8052. // met:
  8053. //
  8054. // * Redistributions of source code must retain the above copyright
  8055. // notice, this list of conditions and the following disclaimer.
  8056. // * Redistributions in binary form must reproduce the above
  8057. // copyright notice, this list of conditions and the following disclaimer
  8058. // in the documentation and/or other materials provided with the
  8059. // distribution.
  8060. // * Neither the name of Google Inc. nor the names of its
  8061. // contributors may be used to endorse or promote products derived from
  8062. // this software without specific prior written permission.
  8063. //
  8064. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8065. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8066. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8067. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8068. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8069. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8070. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8071. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8072. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8073. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8074. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8075. //
  8076. // Google C++ Testing and Mocking Framework definitions useful in production code.
  8077. // GOOGLETEST_CM0003 DO NOT DELETE
  8078. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
  8079. #define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
  8080. // When you need to test the private or protected members of a class,
  8081. // use the FRIEND_TEST macro to declare your tests as friends of the
  8082. // class. For example:
  8083. //
  8084. // class MyClass {
  8085. // private:
  8086. // void PrivateMethod();
  8087. // FRIEND_TEST(MyClassTest, PrivateMethodWorks);
  8088. // };
  8089. //
  8090. // class MyClassTest : public testing::Test {
  8091. // // ...
  8092. // };
  8093. //
  8094. // TEST_F(MyClassTest, PrivateMethodWorks) {
  8095. // // Can call MyClass::PrivateMethod() here.
  8096. // }
  8097. //
  8098. // Note: The test class must be in the same namespace as the class being tested.
  8099. // For example, putting MyClassTest in an anonymous namespace will not work.
  8100. #define FRIEND_TEST(test_case_name, test_name)\
  8101. friend class test_case_name##_##test_name##_Test
  8102. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
  8103. // Copyright 2008 Google Inc.
  8104. // All Rights Reserved.
  8105. //
  8106. // Redistribution and use in source and binary forms, with or without
  8107. // modification, are permitted provided that the following conditions are
  8108. // met:
  8109. //
  8110. // * Redistributions of source code must retain the above copyright
  8111. // notice, this list of conditions and the following disclaimer.
  8112. // * Redistributions in binary form must reproduce the above
  8113. // copyright notice, this list of conditions and the following disclaimer
  8114. // in the documentation and/or other materials provided with the
  8115. // distribution.
  8116. // * Neither the name of Google Inc. nor the names of its
  8117. // contributors may be used to endorse or promote products derived from
  8118. // this software without specific prior written permission.
  8119. //
  8120. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8121. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8122. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8123. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8124. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8125. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8126. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8127. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8128. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8129. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8130. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8131. // GOOGLETEST_CM0001 DO NOT DELETE
  8132. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
  8133. #define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
  8134. // This header implements typed tests and type-parameterized tests.
  8135. // Typed (aka type-driven) tests repeat the same test for types in a
  8136. // list. You must know which types you want to test with when writing
  8137. // typed tests. Here's how you do it:
  8138. #if 0
  8139. // First, define a fixture class template. It should be parameterized
  8140. // by a type. Remember to derive it from testing::Test.
  8141. template <typename T>
  8142. class FooTest : public testing::Test {
  8143. public:
  8144. ...
  8145. typedef std::list<T> List;
  8146. static T shared_;
  8147. T value_;
  8148. };
  8149. // Next, associate a list of types with the test suite, which will be
  8150. // repeated for each type in the list. The typedef is necessary for
  8151. // the macro to parse correctly.
  8152. typedef testing::Types<char, int, unsigned int> MyTypes;
  8153. TYPED_TEST_SUITE(FooTest, MyTypes);
  8154. // If the type list contains only one type, you can write that type
  8155. // directly without Types<...>:
  8156. // TYPED_TEST_SUITE(FooTest, int);
  8157. // Then, use TYPED_TEST() instead of TEST_F() to define as many typed
  8158. // tests for this test suite as you want.
  8159. TYPED_TEST(FooTest, DoesBlah) {
  8160. // Inside a test, refer to the special name TypeParam to get the type
  8161. // parameter. Since we are inside a derived class template, C++ requires
  8162. // us to visit the members of FooTest via 'this'.
  8163. TypeParam n = this->value_;
  8164. // To visit static members of the fixture, add the TestFixture::
  8165. // prefix.
  8166. n += TestFixture::shared_;
  8167. // To refer to typedefs in the fixture, add the "typename
  8168. // TestFixture::" prefix.
  8169. typename TestFixture::List values;
  8170. values.push_back(n);
  8171. ...
  8172. }
  8173. TYPED_TEST(FooTest, HasPropertyA) { ... }
  8174. // TYPED_TEST_SUITE takes an optional third argument which allows to specify a
  8175. // class that generates custom test name suffixes based on the type. This should
  8176. // be a class which has a static template function GetName(int index) returning
  8177. // a string for each type. The provided integer index equals the index of the
  8178. // type in the provided type list. In many cases the index can be ignored.
  8179. //
  8180. // For example:
  8181. // class MyTypeNames {
  8182. // public:
  8183. // template <typename T>
  8184. // static std::string GetName(int) {
  8185. // if (std::is_same<T, char>()) return "char";
  8186. // if (std::is_same<T, int>()) return "int";
  8187. // if (std::is_same<T, unsigned int>()) return "unsignedInt";
  8188. // }
  8189. // };
  8190. // TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames);
  8191. #endif // 0
  8192. // Type-parameterized tests are abstract test patterns parameterized
  8193. // by a type. Compared with typed tests, type-parameterized tests
  8194. // allow you to define the test pattern without knowing what the type
  8195. // parameters are. The defined pattern can be instantiated with
  8196. // different types any number of times, in any number of translation
  8197. // units.
  8198. //
  8199. // If you are designing an interface or concept, you can define a
  8200. // suite of type-parameterized tests to verify properties that any
  8201. // valid implementation of the interface/concept should have. Then,
  8202. // each implementation can easily instantiate the test suite to verify
  8203. // that it conforms to the requirements, without having to write
  8204. // similar tests repeatedly. Here's an example:
  8205. #if 0
  8206. // First, define a fixture class template. It should be parameterized
  8207. // by a type. Remember to derive it from testing::Test.
  8208. template <typename T>
  8209. class FooTest : public testing::Test {
  8210. ...
  8211. };
  8212. // Next, declare that you will define a type-parameterized test suite
  8213. // (the _P suffix is for "parameterized" or "pattern", whichever you
  8214. // prefer):
  8215. TYPED_TEST_SUITE_P(FooTest);
  8216. // Then, use TYPED_TEST_P() to define as many type-parameterized tests
  8217. // for this type-parameterized test suite as you want.
  8218. TYPED_TEST_P(FooTest, DoesBlah) {
  8219. // Inside a test, refer to TypeParam to get the type parameter.
  8220. TypeParam n = 0;
  8221. ...
  8222. }
  8223. TYPED_TEST_P(FooTest, HasPropertyA) { ... }
  8224. // Now the tricky part: you need to register all test patterns before
  8225. // you can instantiate them. The first argument of the macro is the
  8226. // test suite name; the rest are the names of the tests in this test
  8227. // case.
  8228. REGISTER_TYPED_TEST_SUITE_P(FooTest,
  8229. DoesBlah, HasPropertyA);
  8230. // Finally, you are free to instantiate the pattern with the types you
  8231. // want. If you put the above code in a header file, you can #include
  8232. // it in multiple C++ source files and instantiate it multiple times.
  8233. //
  8234. // To distinguish different instances of the pattern, the first
  8235. // argument to the INSTANTIATE_* macro is a prefix that will be added
  8236. // to the actual test suite name. Remember to pick unique prefixes for
  8237. // different instances.
  8238. typedef testing::Types<char, int, unsigned int> MyTypes;
  8239. INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
  8240. // If the type list contains only one type, you can write that type
  8241. // directly without Types<...>:
  8242. // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int);
  8243. //
  8244. // Similar to the optional argument of TYPED_TEST_SUITE above,
  8245. // INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to
  8246. // generate custom names.
  8247. // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames);
  8248. #endif // 0
  8249. // Implements typed tests.
  8250. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  8251. //
  8252. // Expands to the name of the typedef for the type parameters of the
  8253. // given test suite.
  8254. #define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_
  8255. // Expands to the name of the typedef for the NameGenerator, responsible for
  8256. // creating the suffixes of the name.
  8257. #define GTEST_NAME_GENERATOR_(TestSuiteName) \
  8258. gtest_type_params_##TestSuiteName##_NameGenerator
  8259. #define TYPED_TEST_SUITE(CaseName, Types, ...) \
  8260. typedef ::testing::internal::GenerateTypeList<Types>::type \
  8261. GTEST_TYPE_PARAMS_(CaseName); \
  8262. typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
  8263. GTEST_NAME_GENERATOR_(CaseName)
  8264. #define TYPED_TEST(CaseName, TestName) \
  8265. static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \
  8266. "test-name must not be empty"); \
  8267. template <typename gtest_TypeParam_> \
  8268. class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
  8269. : public CaseName<gtest_TypeParam_> { \
  8270. private: \
  8271. typedef CaseName<gtest_TypeParam_> TestFixture; \
  8272. typedef gtest_TypeParam_ TypeParam; \
  8273. void TestBody() override; \
  8274. }; \
  8275. static bool gtest_##CaseName##_##TestName##_registered_ \
  8276. GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \
  8277. CaseName, \
  8278. ::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \
  8279. TestName)>, \
  8280. GTEST_TYPE_PARAMS_( \
  8281. CaseName)>::Register("", \
  8282. ::testing::internal::CodeLocation( \
  8283. __FILE__, __LINE__), \
  8284. GTEST_STRINGIFY_(CaseName), \
  8285. GTEST_STRINGIFY_(TestName), 0, \
  8286. ::testing::internal::GenerateNames< \
  8287. GTEST_NAME_GENERATOR_(CaseName), \
  8288. GTEST_TYPE_PARAMS_(CaseName)>()); \
  8289. template <typename gtest_TypeParam_> \
  8290. void GTEST_TEST_CLASS_NAME_(CaseName, \
  8291. TestName)<gtest_TypeParam_>::TestBody()
  8292. // Legacy API is deprecated but still available
  8293. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8294. #define TYPED_TEST_CASE \
  8295. static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \
  8296. TYPED_TEST_SUITE
  8297. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8298. // Implements type-parameterized tests.
  8299. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  8300. //
  8301. // Expands to the namespace name that the type-parameterized tests for
  8302. // the given type-parameterized test suite are defined in. The exact
  8303. // name of the namespace is subject to change without notice.
  8304. #define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_
  8305. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  8306. //
  8307. // Expands to the name of the variable used to remember the names of
  8308. // the defined tests in the given test suite.
  8309. #define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \
  8310. gtest_typed_test_suite_p_state_##TestSuiteName##_
  8311. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.
  8312. //
  8313. // Expands to the name of the variable used to remember the names of
  8314. // the registered tests in the given test suite.
  8315. #define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \
  8316. gtest_registered_test_names_##TestSuiteName##_
  8317. // The variables defined in the type-parameterized test macros are
  8318. // static as typically these macros are used in a .h file that can be
  8319. // #included in multiple translation units linked together.
  8320. #define TYPED_TEST_SUITE_P(SuiteName) \
  8321. static ::testing::internal::TypedTestSuitePState \
  8322. GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName)
  8323. // Legacy API is deprecated but still available
  8324. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8325. #define TYPED_TEST_CASE_P \
  8326. static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \
  8327. TYPED_TEST_SUITE_P
  8328. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8329. #define TYPED_TEST_P(SuiteName, TestName) \
  8330. namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
  8331. template <typename gtest_TypeParam_> \
  8332. class TestName : public SuiteName<gtest_TypeParam_> { \
  8333. private: \
  8334. typedef SuiteName<gtest_TypeParam_> TestFixture; \
  8335. typedef gtest_TypeParam_ TypeParam; \
  8336. void TestBody() override; \
  8337. }; \
  8338. static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
  8339. GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
  8340. __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
  8341. GTEST_STRINGIFY_(TestName)); \
  8342. } \
  8343. template <typename gtest_TypeParam_> \
  8344. void GTEST_SUITE_NAMESPACE_( \
  8345. SuiteName)::TestName<gtest_TypeParam_>::TestBody()
  8346. // Note: this won't work correctly if the trailing arguments are macros.
  8347. #define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
  8348. namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
  8349. typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
  8350. } \
  8351. static const char* const GTEST_REGISTERED_TEST_NAMES_( \
  8352. SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
  8353. GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
  8354. GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__)
  8355. // Legacy API is deprecated but still available
  8356. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8357. #define REGISTER_TYPED_TEST_CASE_P \
  8358. static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \
  8359. ""); \
  8360. REGISTER_TYPED_TEST_SUITE_P
  8361. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8362. #define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \
  8363. static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \
  8364. "test-suit-prefix must not be empty"); \
  8365. static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \
  8366. ::testing::internal::TypeParameterizedTestSuite< \
  8367. SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
  8368. ::testing::internal::GenerateTypeList<Types>::type>:: \
  8369. Register(GTEST_STRINGIFY_(Prefix), \
  8370. ::testing::internal::CodeLocation(__FILE__, __LINE__), \
  8371. &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \
  8372. GTEST_STRINGIFY_(SuiteName), \
  8373. GTEST_REGISTERED_TEST_NAMES_(SuiteName), \
  8374. ::testing::internal::GenerateNames< \
  8375. ::testing::internal::NameGeneratorSelector< \
  8376. __VA_ARGS__>::type, \
  8377. ::testing::internal::GenerateTypeList<Types>::type>())
  8378. // Legacy API is deprecated but still available
  8379. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8380. #define INSTANTIATE_TYPED_TEST_CASE_P \
  8381. static_assert( \
  8382. ::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \
  8383. INSTANTIATE_TYPED_TEST_SUITE_P
  8384. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8385. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
  8386. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  8387. /* class A needs to have dll-interface to be used by clients of class B */)
  8388. namespace testing {
  8389. // Silence C4100 (unreferenced formal parameter) and 4805
  8390. // unsafe mix of type 'const int' and type 'const bool'
  8391. #ifdef _MSC_VER
  8392. # pragma warning(push)
  8393. # pragma warning(disable:4805)
  8394. # pragma warning(disable:4100)
  8395. #endif
  8396. // Declares the flags.
  8397. // This flag temporary enables the disabled tests.
  8398. GTEST_DECLARE_bool_(also_run_disabled_tests);
  8399. // This flag brings the debugger on an assertion failure.
  8400. GTEST_DECLARE_bool_(break_on_failure);
  8401. // This flag controls whether Google Test catches all test-thrown exceptions
  8402. // and logs them as failures.
  8403. GTEST_DECLARE_bool_(catch_exceptions);
  8404. // This flag enables using colors in terminal output. Available values are
  8405. // "yes" to enable colors, "no" (disable colors), or "auto" (the default)
  8406. // to let Google Test decide.
  8407. GTEST_DECLARE_string_(color);
  8408. // This flag controls whether the test runner should continue execution past
  8409. // first failure.
  8410. GTEST_DECLARE_bool_(fail_fast);
  8411. // This flag sets up the filter to select by name using a glob pattern
  8412. // the tests to run. If the filter is not given all tests are executed.
  8413. GTEST_DECLARE_string_(filter);
  8414. // This flag controls whether Google Test installs a signal handler that dumps
  8415. // debugging information when fatal signals are raised.
  8416. GTEST_DECLARE_bool_(install_failure_signal_handler);
  8417. // This flag causes the Google Test to list tests. None of the tests listed
  8418. // are actually run if the flag is provided.
  8419. GTEST_DECLARE_bool_(list_tests);
  8420. // This flag controls whether Google Test emits a detailed XML report to a file
  8421. // in addition to its normal textual output.
  8422. GTEST_DECLARE_string_(output);
  8423. // This flags control whether Google Test prints only test failures.
  8424. GTEST_DECLARE_bool_(brief);
  8425. // This flags control whether Google Test prints the elapsed time for each
  8426. // test.
  8427. GTEST_DECLARE_bool_(print_time);
  8428. // This flags control whether Google Test prints UTF8 characters as text.
  8429. GTEST_DECLARE_bool_(print_utf8);
  8430. // This flag specifies the random number seed.
  8431. GTEST_DECLARE_int32_(random_seed);
  8432. // This flag sets how many times the tests are repeated. The default value
  8433. // is 1. If the value is -1 the tests are repeating forever.
  8434. GTEST_DECLARE_int32_(repeat);
  8435. // This flag controls whether Google Test includes Google Test internal
  8436. // stack frames in failure stack traces.
  8437. GTEST_DECLARE_bool_(show_internal_stack_frames);
  8438. // When this flag is specified, tests' order is randomized on every iteration.
  8439. GTEST_DECLARE_bool_(shuffle);
  8440. // This flag specifies the maximum number of stack frames to be
  8441. // printed in a failure message.
  8442. GTEST_DECLARE_int32_(stack_trace_depth);
  8443. // When this flag is specified, a failed assertion will throw an
  8444. // exception if exceptions are enabled, or exit the program with a
  8445. // non-zero code otherwise. For use with an external test framework.
  8446. GTEST_DECLARE_bool_(throw_on_failure);
  8447. // When this flag is set with a "host:port" string, on supported
  8448. // platforms test results are streamed to the specified port on
  8449. // the specified host machine.
  8450. GTEST_DECLARE_string_(stream_result_to);
  8451. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  8452. GTEST_DECLARE_string_(flagfile);
  8453. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  8454. // The upper limit for valid stack trace depths.
  8455. const int kMaxStackTraceDepth = 100;
  8456. namespace internal {
  8457. class AssertHelper;
  8458. class DefaultGlobalTestPartResultReporter;
  8459. class ExecDeathTest;
  8460. class NoExecDeathTest;
  8461. class FinalSuccessChecker;
  8462. class GTestFlagSaver;
  8463. class StreamingListenerTest;
  8464. class TestResultAccessor;
  8465. class TestEventListenersAccessor;
  8466. class TestEventRepeater;
  8467. class UnitTestRecordPropertyTestHelper;
  8468. class WindowsDeathTest;
  8469. class FuchsiaDeathTest;
  8470. class UnitTestImpl* GetUnitTestImpl();
  8471. void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  8472. const std::string& message);
  8473. std::set<std::string>* GetIgnoredParameterizedTestSuites();
  8474. } // namespace internal
  8475. // The friend relationship of some of these classes is cyclic.
  8476. // If we don't forward declare them the compiler might confuse the classes
  8477. // in friendship clauses with same named classes on the scope.
  8478. class Test;
  8479. class TestSuite;
  8480. // Old API is still available but deprecated
  8481. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8482. using TestCase = TestSuite;
  8483. #endif
  8484. class TestInfo;
  8485. class UnitTest;
  8486. // A class for indicating whether an assertion was successful. When
  8487. // the assertion wasn't successful, the AssertionResult object
  8488. // remembers a non-empty message that describes how it failed.
  8489. //
  8490. // To create an instance of this class, use one of the factory functions
  8491. // (AssertionSuccess() and AssertionFailure()).
  8492. //
  8493. // This class is useful for two purposes:
  8494. // 1. Defining predicate functions to be used with Boolean test assertions
  8495. // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
  8496. // 2. Defining predicate-format functions to be
  8497. // used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
  8498. //
  8499. // For example, if you define IsEven predicate:
  8500. //
  8501. // testing::AssertionResult IsEven(int n) {
  8502. // if ((n % 2) == 0)
  8503. // return testing::AssertionSuccess();
  8504. // else
  8505. // return testing::AssertionFailure() << n << " is odd";
  8506. // }
  8507. //
  8508. // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
  8509. // will print the message
  8510. //
  8511. // Value of: IsEven(Fib(5))
  8512. // Actual: false (5 is odd)
  8513. // Expected: true
  8514. //
  8515. // instead of a more opaque
  8516. //
  8517. // Value of: IsEven(Fib(5))
  8518. // Actual: false
  8519. // Expected: true
  8520. //
  8521. // in case IsEven is a simple Boolean predicate.
  8522. //
  8523. // If you expect your predicate to be reused and want to support informative
  8524. // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
  8525. // about half as often as positive ones in our tests), supply messages for
  8526. // both success and failure cases:
  8527. //
  8528. // testing::AssertionResult IsEven(int n) {
  8529. // if ((n % 2) == 0)
  8530. // return testing::AssertionSuccess() << n << " is even";
  8531. // else
  8532. // return testing::AssertionFailure() << n << " is odd";
  8533. // }
  8534. //
  8535. // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
  8536. //
  8537. // Value of: IsEven(Fib(6))
  8538. // Actual: true (8 is even)
  8539. // Expected: false
  8540. //
  8541. // NB: Predicates that support negative Boolean assertions have reduced
  8542. // performance in positive ones so be careful not to use them in tests
  8543. // that have lots (tens of thousands) of positive Boolean assertions.
  8544. //
  8545. // To use this class with EXPECT_PRED_FORMAT assertions such as:
  8546. //
  8547. // // Verifies that Foo() returns an even number.
  8548. // EXPECT_PRED_FORMAT1(IsEven, Foo());
  8549. //
  8550. // you need to define:
  8551. //
  8552. // testing::AssertionResult IsEven(const char* expr, int n) {
  8553. // if ((n % 2) == 0)
  8554. // return testing::AssertionSuccess();
  8555. // else
  8556. // return testing::AssertionFailure()
  8557. // << "Expected: " << expr << " is even\n Actual: it's " << n;
  8558. // }
  8559. //
  8560. // If Foo() returns 5, you will see the following message:
  8561. //
  8562. // Expected: Foo() is even
  8563. // Actual: it's 5
  8564. //
  8565. class GTEST_API_ AssertionResult {
  8566. public:
  8567. // Copy constructor.
  8568. // Used in EXPECT_TRUE/FALSE(assertion_result).
  8569. AssertionResult(const AssertionResult& other);
  8570. // C4800 is a level 3 warning in Visual Studio 2015 and earlier.
  8571. // This warning is not emitted in Visual Studio 2017.
  8572. // This warning is off by default starting in Visual Studio 2019 but can be
  8573. // enabled with command-line options.
  8574. #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
  8575. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
  8576. #endif
  8577. // Used in the EXPECT_TRUE/FALSE(bool_expression).
  8578. //
  8579. // T must be contextually convertible to bool.
  8580. //
  8581. // The second parameter prevents this overload from being considered if
  8582. // the argument is implicitly convertible to AssertionResult. In that case
  8583. // we want AssertionResult's copy constructor to be used.
  8584. template <typename T>
  8585. explicit AssertionResult(
  8586. const T& success,
  8587. typename std::enable_if<
  8588. !std::is_convertible<T, AssertionResult>::value>::type*
  8589. /*enabler*/
  8590. = nullptr)
  8591. : success_(success) {}
  8592. #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
  8593. GTEST_DISABLE_MSC_WARNINGS_POP_()
  8594. #endif
  8595. // Assignment operator.
  8596. AssertionResult& operator=(AssertionResult other) {
  8597. swap(other);
  8598. return *this;
  8599. }
  8600. // Returns true if and only if the assertion succeeded.
  8601. operator bool() const { return success_; } // NOLINT
  8602. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  8603. AssertionResult operator!() const;
  8604. // Returns the text streamed into this AssertionResult. Test assertions
  8605. // use it when they fail (i.e., the predicate's outcome doesn't match the
  8606. // assertion's expectation). When nothing has been streamed into the
  8607. // object, returns an empty string.
  8608. const char* message() const {
  8609. return message_.get() != nullptr ? message_->c_str() : "";
  8610. }
  8611. // Deprecated; please use message() instead.
  8612. const char* failure_message() const { return message(); }
  8613. // Streams a custom failure message into this object.
  8614. template <typename T> AssertionResult& operator<<(const T& value) {
  8615. AppendMessage(Message() << value);
  8616. return *this;
  8617. }
  8618. // Allows streaming basic output manipulators such as endl or flush into
  8619. // this object.
  8620. AssertionResult& operator<<(
  8621. ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
  8622. AppendMessage(Message() << basic_manipulator);
  8623. return *this;
  8624. }
  8625. private:
  8626. // Appends the contents of message to message_.
  8627. void AppendMessage(const Message& a_message) {
  8628. if (message_.get() == nullptr) message_.reset(new ::std::string);
  8629. message_->append(a_message.GetString().c_str());
  8630. }
  8631. // Swap the contents of this AssertionResult with other.
  8632. void swap(AssertionResult& other);
  8633. // Stores result of the assertion predicate.
  8634. bool success_;
  8635. // Stores the message describing the condition in case the expectation
  8636. // construct is not satisfied with the predicate's outcome.
  8637. // Referenced via a pointer to avoid taking too much stack frame space
  8638. // with test assertions.
  8639. std::unique_ptr< ::std::string> message_;
  8640. };
  8641. // Makes a successful assertion result.
  8642. GTEST_API_ AssertionResult AssertionSuccess();
  8643. // Makes a failed assertion result.
  8644. GTEST_API_ AssertionResult AssertionFailure();
  8645. // Makes a failed assertion result with the given failure message.
  8646. // Deprecated; use AssertionFailure() << msg.
  8647. GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
  8648. } // namespace testing
  8649. // Includes the auto-generated header that implements a family of generic
  8650. // predicate assertion macros. This include comes late because it relies on
  8651. // APIs declared above.
  8652. // Copyright 2006, Google Inc.
  8653. // All rights reserved.
  8654. //
  8655. // Redistribution and use in source and binary forms, with or without
  8656. // modification, are permitted provided that the following conditions are
  8657. // met:
  8658. //
  8659. // * Redistributions of source code must retain the above copyright
  8660. // notice, this list of conditions and the following disclaimer.
  8661. // * Redistributions in binary form must reproduce the above
  8662. // copyright notice, this list of conditions and the following disclaimer
  8663. // in the documentation and/or other materials provided with the
  8664. // distribution.
  8665. // * Neither the name of Google Inc. nor the names of its
  8666. // contributors may be used to endorse or promote products derived from
  8667. // this software without specific prior written permission.
  8668. //
  8669. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8670. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8671. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8672. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8673. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8674. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8675. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8676. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8677. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8678. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8679. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8680. // This file is AUTOMATICALLY GENERATED on 01/02/2019 by command
  8681. // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND!
  8682. //
  8683. // Implements a family of generic predicate assertion macros.
  8684. // GOOGLETEST_CM0001 DO NOT DELETE
  8685. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
  8686. #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
  8687. namespace testing {
  8688. // This header implements a family of generic predicate assertion
  8689. // macros:
  8690. //
  8691. // ASSERT_PRED_FORMAT1(pred_format, v1)
  8692. // ASSERT_PRED_FORMAT2(pred_format, v1, v2)
  8693. // ...
  8694. //
  8695. // where pred_format is a function or functor that takes n (in the
  8696. // case of ASSERT_PRED_FORMATn) values and their source expression
  8697. // text, and returns a testing::AssertionResult. See the definition
  8698. // of ASSERT_EQ in gtest.h for an example.
  8699. //
  8700. // If you don't care about formatting, you can use the more
  8701. // restrictive version:
  8702. //
  8703. // ASSERT_PRED1(pred, v1)
  8704. // ASSERT_PRED2(pred, v1, v2)
  8705. // ...
  8706. //
  8707. // where pred is an n-ary function or functor that returns bool,
  8708. // and the values v1, v2, ..., must support the << operator for
  8709. // streaming to std::ostream.
  8710. //
  8711. // We also define the EXPECT_* variations.
  8712. //
  8713. // For now we only support predicates whose arity is at most 5.
  8714. // Please email googletestframework@googlegroups.com if you need
  8715. // support for higher arities.
  8716. // GTEST_ASSERT_ is the basic statement to which all of the assertions
  8717. // in this file reduce. Don't use this in your code.
  8718. #define GTEST_ASSERT_(expression, on_failure) \
  8719. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  8720. if (const ::testing::AssertionResult gtest_ar = (expression)) \
  8721. ; \
  8722. else \
  8723. on_failure(gtest_ar.failure_message())
  8724. // Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
  8725. // this in your code.
  8726. template <typename Pred,
  8727. typename T1>
  8728. AssertionResult AssertPred1Helper(const char* pred_text,
  8729. const char* e1,
  8730. Pred pred,
  8731. const T1& v1) {
  8732. if (pred(v1)) return AssertionSuccess();
  8733. return AssertionFailure()
  8734. << pred_text << "(" << e1 << ") evaluates to false, where"
  8735. << "\n"
  8736. << e1 << " evaluates to " << ::testing::PrintToString(v1);
  8737. }
  8738. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
  8739. // Don't use this in your code.
  8740. #define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\
  8741. GTEST_ASSERT_(pred_format(#v1, v1), \
  8742. on_failure)
  8743. // Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
  8744. // this in your code.
  8745. #define GTEST_PRED1_(pred, v1, on_failure)\
  8746. GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
  8747. #v1, \
  8748. pred, \
  8749. v1), on_failure)
  8750. // Unary predicate assertion macros.
  8751. #define EXPECT_PRED_FORMAT1(pred_format, v1) \
  8752. GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
  8753. #define EXPECT_PRED1(pred, v1) \
  8754. GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
  8755. #define ASSERT_PRED_FORMAT1(pred_format, v1) \
  8756. GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
  8757. #define ASSERT_PRED1(pred, v1) \
  8758. GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
  8759. // Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
  8760. // this in your code.
  8761. template <typename Pred,
  8762. typename T1,
  8763. typename T2>
  8764. AssertionResult AssertPred2Helper(const char* pred_text,
  8765. const char* e1,
  8766. const char* e2,
  8767. Pred pred,
  8768. const T1& v1,
  8769. const T2& v2) {
  8770. if (pred(v1, v2)) return AssertionSuccess();
  8771. return AssertionFailure()
  8772. << pred_text << "(" << e1 << ", " << e2
  8773. << ") evaluates to false, where"
  8774. << "\n"
  8775. << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
  8776. << e2 << " evaluates to " << ::testing::PrintToString(v2);
  8777. }
  8778. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
  8779. // Don't use this in your code.
  8780. #define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\
  8781. GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \
  8782. on_failure)
  8783. // Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
  8784. // this in your code.
  8785. #define GTEST_PRED2_(pred, v1, v2, on_failure)\
  8786. GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
  8787. #v1, \
  8788. #v2, \
  8789. pred, \
  8790. v1, \
  8791. v2), on_failure)
  8792. // Binary predicate assertion macros.
  8793. #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
  8794. GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_)
  8795. #define EXPECT_PRED2(pred, v1, v2) \
  8796. GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_)
  8797. #define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \
  8798. GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_)
  8799. #define ASSERT_PRED2(pred, v1, v2) \
  8800. GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
  8801. // Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
  8802. // this in your code.
  8803. template <typename Pred,
  8804. typename T1,
  8805. typename T2,
  8806. typename T3>
  8807. AssertionResult AssertPred3Helper(const char* pred_text,
  8808. const char* e1,
  8809. const char* e2,
  8810. const char* e3,
  8811. Pred pred,
  8812. const T1& v1,
  8813. const T2& v2,
  8814. const T3& v3) {
  8815. if (pred(v1, v2, v3)) return AssertionSuccess();
  8816. return AssertionFailure()
  8817. << pred_text << "(" << e1 << ", " << e2 << ", " << e3
  8818. << ") evaluates to false, where"
  8819. << "\n"
  8820. << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
  8821. << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
  8822. << e3 << " evaluates to " << ::testing::PrintToString(v3);
  8823. }
  8824. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
  8825. // Don't use this in your code.
  8826. #define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\
  8827. GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \
  8828. on_failure)
  8829. // Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
  8830. // this in your code.
  8831. #define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\
  8832. GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
  8833. #v1, \
  8834. #v2, \
  8835. #v3, \
  8836. pred, \
  8837. v1, \
  8838. v2, \
  8839. v3), on_failure)
  8840. // Ternary predicate assertion macros.
  8841. #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
  8842. GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
  8843. #define EXPECT_PRED3(pred, v1, v2, v3) \
  8844. GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
  8845. #define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \
  8846. GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_)
  8847. #define ASSERT_PRED3(pred, v1, v2, v3) \
  8848. GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
  8849. // Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
  8850. // this in your code.
  8851. template <typename Pred,
  8852. typename T1,
  8853. typename T2,
  8854. typename T3,
  8855. typename T4>
  8856. AssertionResult AssertPred4Helper(const char* pred_text,
  8857. const char* e1,
  8858. const char* e2,
  8859. const char* e3,
  8860. const char* e4,
  8861. Pred pred,
  8862. const T1& v1,
  8863. const T2& v2,
  8864. const T3& v3,
  8865. const T4& v4) {
  8866. if (pred(v1, v2, v3, v4)) return AssertionSuccess();
  8867. return AssertionFailure()
  8868. << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
  8869. << ") evaluates to false, where"
  8870. << "\n"
  8871. << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
  8872. << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
  8873. << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
  8874. << e4 << " evaluates to " << ::testing::PrintToString(v4);
  8875. }
  8876. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
  8877. // Don't use this in your code.
  8878. #define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\
  8879. GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \
  8880. on_failure)
  8881. // Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
  8882. // this in your code.
  8883. #define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\
  8884. GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
  8885. #v1, \
  8886. #v2, \
  8887. #v3, \
  8888. #v4, \
  8889. pred, \
  8890. v1, \
  8891. v2, \
  8892. v3, \
  8893. v4), on_failure)
  8894. // 4-ary predicate assertion macros.
  8895. #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
  8896. GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
  8897. #define EXPECT_PRED4(pred, v1, v2, v3, v4) \
  8898. GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
  8899. #define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
  8900. GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
  8901. #define ASSERT_PRED4(pred, v1, v2, v3, v4) \
  8902. GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
  8903. // Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
  8904. // this in your code.
  8905. template <typename Pred,
  8906. typename T1,
  8907. typename T2,
  8908. typename T3,
  8909. typename T4,
  8910. typename T5>
  8911. AssertionResult AssertPred5Helper(const char* pred_text,
  8912. const char* e1,
  8913. const char* e2,
  8914. const char* e3,
  8915. const char* e4,
  8916. const char* e5,
  8917. Pred pred,
  8918. const T1& v1,
  8919. const T2& v2,
  8920. const T3& v3,
  8921. const T4& v4,
  8922. const T5& v5) {
  8923. if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
  8924. return AssertionFailure()
  8925. << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
  8926. << ", " << e5 << ") evaluates to false, where"
  8927. << "\n"
  8928. << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
  8929. << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
  8930. << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
  8931. << e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n"
  8932. << e5 << " evaluates to " << ::testing::PrintToString(v5);
  8933. }
  8934. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
  8935. // Don't use this in your code.
  8936. #define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\
  8937. GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \
  8938. on_failure)
  8939. // Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
  8940. // this in your code.
  8941. #define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\
  8942. GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
  8943. #v1, \
  8944. #v2, \
  8945. #v3, \
  8946. #v4, \
  8947. #v5, \
  8948. pred, \
  8949. v1, \
  8950. v2, \
  8951. v3, \
  8952. v4, \
  8953. v5), on_failure)
  8954. // 5-ary predicate assertion macros.
  8955. #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
  8956. GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
  8957. #define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \
  8958. GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
  8959. #define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
  8960. GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
  8961. #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
  8962. GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
  8963. } // namespace testing
  8964. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
  8965. namespace testing {
  8966. // The abstract class that all tests inherit from.
  8967. //
  8968. // In Google Test, a unit test program contains one or many TestSuites, and
  8969. // each TestSuite contains one or many Tests.
  8970. //
  8971. // When you define a test using the TEST macro, you don't need to
  8972. // explicitly derive from Test - the TEST macro automatically does
  8973. // this for you.
  8974. //
  8975. // The only time you derive from Test is when defining a test fixture
  8976. // to be used in a TEST_F. For example:
  8977. //
  8978. // class FooTest : public testing::Test {
  8979. // protected:
  8980. // void SetUp() override { ... }
  8981. // void TearDown() override { ... }
  8982. // ...
  8983. // };
  8984. //
  8985. // TEST_F(FooTest, Bar) { ... }
  8986. // TEST_F(FooTest, Baz) { ... }
  8987. //
  8988. // Test is not copyable.
  8989. class GTEST_API_ Test {
  8990. public:
  8991. friend class TestInfo;
  8992. // The d'tor is virtual as we intend to inherit from Test.
  8993. virtual ~Test();
  8994. // Sets up the stuff shared by all tests in this test suite.
  8995. //
  8996. // Google Test will call Foo::SetUpTestSuite() before running the first
  8997. // test in test suite Foo. Hence a sub-class can define its own
  8998. // SetUpTestSuite() method to shadow the one defined in the super
  8999. // class.
  9000. static void SetUpTestSuite() {}
  9001. // Tears down the stuff shared by all tests in this test suite.
  9002. //
  9003. // Google Test will call Foo::TearDownTestSuite() after running the last
  9004. // test in test suite Foo. Hence a sub-class can define its own
  9005. // TearDownTestSuite() method to shadow the one defined in the super
  9006. // class.
  9007. static void TearDownTestSuite() {}
  9008. // Legacy API is deprecated but still available. Use SetUpTestSuite and
  9009. // TearDownTestSuite instead.
  9010. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9011. static void TearDownTestCase() {}
  9012. static void SetUpTestCase() {}
  9013. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9014. // Returns true if and only if the current test has a fatal failure.
  9015. static bool HasFatalFailure();
  9016. // Returns true if and only if the current test has a non-fatal failure.
  9017. static bool HasNonfatalFailure();
  9018. // Returns true if and only if the current test was skipped.
  9019. static bool IsSkipped();
  9020. // Returns true if and only if the current test has a (either fatal or
  9021. // non-fatal) failure.
  9022. static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
  9023. // Logs a property for the current test, test suite, or for the entire
  9024. // invocation of the test program when used outside of the context of a
  9025. // test suite. Only the last value for a given key is remembered. These
  9026. // are public static so they can be called from utility functions that are
  9027. // not members of the test fixture. Calls to RecordProperty made during
  9028. // lifespan of the test (from the moment its constructor starts to the
  9029. // moment its destructor finishes) will be output in XML as attributes of
  9030. // the <testcase> element. Properties recorded from fixture's
  9031. // SetUpTestSuite or TearDownTestSuite are logged as attributes of the
  9032. // corresponding <testsuite> element. Calls to RecordProperty made in the
  9033. // global context (before or after invocation of RUN_ALL_TESTS and from
  9034. // SetUp/TearDown method of Environment objects registered with Google
  9035. // Test) will be output as attributes of the <testsuites> element.
  9036. static void RecordProperty(const std::string& key, const std::string& value);
  9037. static void RecordProperty(const std::string& key, int value);
  9038. protected:
  9039. // Creates a Test object.
  9040. Test();
  9041. // Sets up the test fixture.
  9042. virtual void SetUp();
  9043. // Tears down the test fixture.
  9044. virtual void TearDown();
  9045. private:
  9046. // Returns true if and only if the current test has the same fixture class
  9047. // as the first test in the current test suite.
  9048. static bool HasSameFixtureClass();
  9049. // Runs the test after the test fixture has been set up.
  9050. //
  9051. // A sub-class must implement this to define the test logic.
  9052. //
  9053. // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
  9054. // Instead, use the TEST or TEST_F macro.
  9055. virtual void TestBody() = 0;
  9056. // Sets up, executes, and tears down the test.
  9057. void Run();
  9058. // Deletes self. We deliberately pick an unusual name for this
  9059. // internal method to avoid clashing with names used in user TESTs.
  9060. void DeleteSelf_() { delete this; }
  9061. const std::unique_ptr<GTEST_FLAG_SAVER_> gtest_flag_saver_;
  9062. // Often a user misspells SetUp() as Setup() and spends a long time
  9063. // wondering why it is never called by Google Test. The declaration of
  9064. // the following method is solely for catching such an error at
  9065. // compile time:
  9066. //
  9067. // - The return type is deliberately chosen to be not void, so it
  9068. // will be a conflict if void Setup() is declared in the user's
  9069. // test fixture.
  9070. //
  9071. // - This method is private, so it will be another compiler error
  9072. // if the method is called from the user's test fixture.
  9073. //
  9074. // DO NOT OVERRIDE THIS FUNCTION.
  9075. //
  9076. // If you see an error about overriding the following function or
  9077. // about it being private, you have mis-spelled SetUp() as Setup().
  9078. struct Setup_should_be_spelled_SetUp {};
  9079. virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
  9080. // We disallow copying Tests.
  9081. GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
  9082. };
  9083. typedef internal::TimeInMillis TimeInMillis;
  9084. // A copyable object representing a user specified test property which can be
  9085. // output as a key/value string pair.
  9086. //
  9087. // Don't inherit from TestProperty as its destructor is not virtual.
  9088. class TestProperty {
  9089. public:
  9090. // C'tor. TestProperty does NOT have a default constructor.
  9091. // Always use this constructor (with parameters) to create a
  9092. // TestProperty object.
  9093. TestProperty(const std::string& a_key, const std::string& a_value) :
  9094. key_(a_key), value_(a_value) {
  9095. }
  9096. // Gets the user supplied key.
  9097. const char* key() const {
  9098. return key_.c_str();
  9099. }
  9100. // Gets the user supplied value.
  9101. const char* value() const {
  9102. return value_.c_str();
  9103. }
  9104. // Sets a new value, overriding the one supplied in the constructor.
  9105. void SetValue(const std::string& new_value) {
  9106. value_ = new_value;
  9107. }
  9108. private:
  9109. // The key supplied by the user.
  9110. std::string key_;
  9111. // The value supplied by the user.
  9112. std::string value_;
  9113. };
  9114. // The result of a single Test. This includes a list of
  9115. // TestPartResults, a list of TestProperties, a count of how many
  9116. // death tests there are in the Test, and how much time it took to run
  9117. // the Test.
  9118. //
  9119. // TestResult is not copyable.
  9120. class GTEST_API_ TestResult {
  9121. public:
  9122. // Creates an empty TestResult.
  9123. TestResult();
  9124. // D'tor. Do not inherit from TestResult.
  9125. ~TestResult();
  9126. // Gets the number of all test parts. This is the sum of the number
  9127. // of successful test parts and the number of failed test parts.
  9128. int total_part_count() const;
  9129. // Returns the number of the test properties.
  9130. int test_property_count() const;
  9131. // Returns true if and only if the test passed (i.e. no test part failed).
  9132. bool Passed() const { return !Skipped() && !Failed(); }
  9133. // Returns true if and only if the test was skipped.
  9134. bool Skipped() const;
  9135. // Returns true if and only if the test failed.
  9136. bool Failed() const;
  9137. // Returns true if and only if the test fatally failed.
  9138. bool HasFatalFailure() const;
  9139. // Returns true if and only if the test has a non-fatal failure.
  9140. bool HasNonfatalFailure() const;
  9141. // Returns the elapsed time, in milliseconds.
  9142. TimeInMillis elapsed_time() const { return elapsed_time_; }
  9143. // Gets the time of the test case start, in ms from the start of the
  9144. // UNIX epoch.
  9145. TimeInMillis start_timestamp() const { return start_timestamp_; }
  9146. // Returns the i-th test part result among all the results. i can range from 0
  9147. // to total_part_count() - 1. If i is not in that range, aborts the program.
  9148. const TestPartResult& GetTestPartResult(int i) const;
  9149. // Returns the i-th test property. i can range from 0 to
  9150. // test_property_count() - 1. If i is not in that range, aborts the
  9151. // program.
  9152. const TestProperty& GetTestProperty(int i) const;
  9153. private:
  9154. friend class TestInfo;
  9155. friend class TestSuite;
  9156. friend class UnitTest;
  9157. friend class internal::DefaultGlobalTestPartResultReporter;
  9158. friend class internal::ExecDeathTest;
  9159. friend class internal::TestResultAccessor;
  9160. friend class internal::UnitTestImpl;
  9161. friend class internal::WindowsDeathTest;
  9162. friend class internal::FuchsiaDeathTest;
  9163. // Gets the vector of TestPartResults.
  9164. const std::vector<TestPartResult>& test_part_results() const {
  9165. return test_part_results_;
  9166. }
  9167. // Gets the vector of TestProperties.
  9168. const std::vector<TestProperty>& test_properties() const {
  9169. return test_properties_;
  9170. }
  9171. // Sets the start time.
  9172. void set_start_timestamp(TimeInMillis start) { start_timestamp_ = start; }
  9173. // Sets the elapsed time.
  9174. void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
  9175. // Adds a test property to the list. The property is validated and may add
  9176. // a non-fatal failure if invalid (e.g., if it conflicts with reserved
  9177. // key names). If a property is already recorded for the same key, the
  9178. // value will be updated, rather than storing multiple values for the same
  9179. // key. xml_element specifies the element for which the property is being
  9180. // recorded and is used for validation.
  9181. void RecordProperty(const std::string& xml_element,
  9182. const TestProperty& test_property);
  9183. // Adds a failure if the key is a reserved attribute of Google Test
  9184. // testsuite tags. Returns true if the property is valid.
  9185. // FIXME: Validate attribute names are legal and human readable.
  9186. static bool ValidateTestProperty(const std::string& xml_element,
  9187. const TestProperty& test_property);
  9188. // Adds a test part result to the list.
  9189. void AddTestPartResult(const TestPartResult& test_part_result);
  9190. // Returns the death test count.
  9191. int death_test_count() const { return death_test_count_; }
  9192. // Increments the death test count, returning the new count.
  9193. int increment_death_test_count() { return ++death_test_count_; }
  9194. // Clears the test part results.
  9195. void ClearTestPartResults();
  9196. // Clears the object.
  9197. void Clear();
  9198. // Protects mutable state of the property vector and of owned
  9199. // properties, whose values may be updated.
  9200. internal::Mutex test_properties_mutex_;
  9201. // The vector of TestPartResults
  9202. std::vector<TestPartResult> test_part_results_;
  9203. // The vector of TestProperties
  9204. std::vector<TestProperty> test_properties_;
  9205. // Running count of death tests.
  9206. int death_test_count_;
  9207. // The start time, in milliseconds since UNIX Epoch.
  9208. TimeInMillis start_timestamp_;
  9209. // The elapsed time, in milliseconds.
  9210. TimeInMillis elapsed_time_;
  9211. // We disallow copying TestResult.
  9212. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
  9213. }; // class TestResult
  9214. // A TestInfo object stores the following information about a test:
  9215. //
  9216. // Test suite name
  9217. // Test name
  9218. // Whether the test should be run
  9219. // A function pointer that creates the test object when invoked
  9220. // Test result
  9221. //
  9222. // The constructor of TestInfo registers itself with the UnitTest
  9223. // singleton such that the RUN_ALL_TESTS() macro knows which tests to
  9224. // run.
  9225. class GTEST_API_ TestInfo {
  9226. public:
  9227. // Destructs a TestInfo object. This function is not virtual, so
  9228. // don't inherit from TestInfo.
  9229. ~TestInfo();
  9230. // Returns the test suite name.
  9231. const char* test_suite_name() const { return test_suite_name_.c_str(); }
  9232. // Legacy API is deprecated but still available
  9233. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9234. const char* test_case_name() const { return test_suite_name(); }
  9235. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9236. // Returns the test name.
  9237. const char* name() const { return name_.c_str(); }
  9238. // Returns the name of the parameter type, or NULL if this is not a typed
  9239. // or a type-parameterized test.
  9240. const char* type_param() const {
  9241. if (type_param_.get() != nullptr) return type_param_->c_str();
  9242. return nullptr;
  9243. }
  9244. // Returns the text representation of the value parameter, or NULL if this
  9245. // is not a value-parameterized test.
  9246. const char* value_param() const {
  9247. if (value_param_.get() != nullptr) return value_param_->c_str();
  9248. return nullptr;
  9249. }
  9250. // Returns the file name where this test is defined.
  9251. const char* file() const { return location_.file.c_str(); }
  9252. // Returns the line where this test is defined.
  9253. int line() const { return location_.line; }
  9254. // Return true if this test should not be run because it's in another shard.
  9255. bool is_in_another_shard() const { return is_in_another_shard_; }
  9256. // Returns true if this test should run, that is if the test is not
  9257. // disabled (or it is disabled but the also_run_disabled_tests flag has
  9258. // been specified) and its full name matches the user-specified filter.
  9259. //
  9260. // Google Test allows the user to filter the tests by their full names.
  9261. // The full name of a test Bar in test suite Foo is defined as
  9262. // "Foo.Bar". Only the tests that match the filter will run.
  9263. //
  9264. // A filter is a colon-separated list of glob (not regex) patterns,
  9265. // optionally followed by a '-' and a colon-separated list of
  9266. // negative patterns (tests to exclude). A test is run if it
  9267. // matches one of the positive patterns and does not match any of
  9268. // the negative patterns.
  9269. //
  9270. // For example, *A*:Foo.* is a filter that matches any string that
  9271. // contains the character 'A' or starts with "Foo.".
  9272. bool should_run() const { return should_run_; }
  9273. // Returns true if and only if this test will appear in the XML report.
  9274. bool is_reportable() const {
  9275. // The XML report includes tests matching the filter, excluding those
  9276. // run in other shards.
  9277. return matches_filter_ && !is_in_another_shard_;
  9278. }
  9279. // Returns the result of the test.
  9280. const TestResult* result() const { return &result_; }
  9281. private:
  9282. #if GTEST_HAS_DEATH_TEST
  9283. friend class internal::DefaultDeathTestFactory;
  9284. #endif // GTEST_HAS_DEATH_TEST
  9285. friend class Test;
  9286. friend class TestSuite;
  9287. friend class internal::UnitTestImpl;
  9288. friend class internal::StreamingListenerTest;
  9289. friend TestInfo* internal::MakeAndRegisterTestInfo(
  9290. const char* test_suite_name, const char* name, const char* type_param,
  9291. const char* value_param, internal::CodeLocation code_location,
  9292. internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc,
  9293. internal::TearDownTestSuiteFunc tear_down_tc,
  9294. internal::TestFactoryBase* factory);
  9295. // Constructs a TestInfo object. The newly constructed instance assumes
  9296. // ownership of the factory object.
  9297. TestInfo(const std::string& test_suite_name, const std::string& name,
  9298. const char* a_type_param, // NULL if not a type-parameterized test
  9299. const char* a_value_param, // NULL if not a value-parameterized test
  9300. internal::CodeLocation a_code_location,
  9301. internal::TypeId fixture_class_id,
  9302. internal::TestFactoryBase* factory);
  9303. // Increments the number of death tests encountered in this test so
  9304. // far.
  9305. int increment_death_test_count() {
  9306. return result_.increment_death_test_count();
  9307. }
  9308. // Creates the test object, runs it, records its result, and then
  9309. // deletes it.
  9310. void Run();
  9311. // Skip and records the test result for this object.
  9312. void Skip();
  9313. static void ClearTestResult(TestInfo* test_info) {
  9314. test_info->result_.Clear();
  9315. }
  9316. // These fields are immutable properties of the test.
  9317. const std::string test_suite_name_; // test suite name
  9318. const std::string name_; // Test name
  9319. // Name of the parameter type, or NULL if this is not a typed or a
  9320. // type-parameterized test.
  9321. const std::unique_ptr<const ::std::string> type_param_;
  9322. // Text representation of the value parameter, or NULL if this is not a
  9323. // value-parameterized test.
  9324. const std::unique_ptr<const ::std::string> value_param_;
  9325. internal::CodeLocation location_;
  9326. const internal::TypeId fixture_class_id_; // ID of the test fixture class
  9327. bool should_run_; // True if and only if this test should run
  9328. bool is_disabled_; // True if and only if this test is disabled
  9329. bool matches_filter_; // True if this test matches the
  9330. // user-specified filter.
  9331. bool is_in_another_shard_; // Will be run in another shard.
  9332. internal::TestFactoryBase* const factory_; // The factory that creates
  9333. // the test object
  9334. // This field is mutable and needs to be reset before running the
  9335. // test for the second time.
  9336. TestResult result_;
  9337. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
  9338. };
  9339. // A test suite, which consists of a vector of TestInfos.
  9340. //
  9341. // TestSuite is not copyable.
  9342. class GTEST_API_ TestSuite {
  9343. public:
  9344. // Creates a TestSuite with the given name.
  9345. //
  9346. // TestSuite does NOT have a default constructor. Always use this
  9347. // constructor to create a TestSuite object.
  9348. //
  9349. // Arguments:
  9350. //
  9351. // name: name of the test suite
  9352. // a_type_param: the name of the test's type parameter, or NULL if
  9353. // this is not a type-parameterized test.
  9354. // set_up_tc: pointer to the function that sets up the test suite
  9355. // tear_down_tc: pointer to the function that tears down the test suite
  9356. TestSuite(const char* name, const char* a_type_param,
  9357. internal::SetUpTestSuiteFunc set_up_tc,
  9358. internal::TearDownTestSuiteFunc tear_down_tc);
  9359. // Destructor of TestSuite.
  9360. virtual ~TestSuite();
  9361. // Gets the name of the TestSuite.
  9362. const char* name() const { return name_.c_str(); }
  9363. // Returns the name of the parameter type, or NULL if this is not a
  9364. // type-parameterized test suite.
  9365. const char* type_param() const {
  9366. if (type_param_.get() != nullptr) return type_param_->c_str();
  9367. return nullptr;
  9368. }
  9369. // Returns true if any test in this test suite should run.
  9370. bool should_run() const { return should_run_; }
  9371. // Gets the number of successful tests in this test suite.
  9372. int successful_test_count() const;
  9373. // Gets the number of skipped tests in this test suite.
  9374. int skipped_test_count() const;
  9375. // Gets the number of failed tests in this test suite.
  9376. int failed_test_count() const;
  9377. // Gets the number of disabled tests that will be reported in the XML report.
  9378. int reportable_disabled_test_count() const;
  9379. // Gets the number of disabled tests in this test suite.
  9380. int disabled_test_count() const;
  9381. // Gets the number of tests to be printed in the XML report.
  9382. int reportable_test_count() const;
  9383. // Get the number of tests in this test suite that should run.
  9384. int test_to_run_count() const;
  9385. // Gets the number of all tests in this test suite.
  9386. int total_test_count() const;
  9387. // Returns true if and only if the test suite passed.
  9388. bool Passed() const { return !Failed(); }
  9389. // Returns true if and only if the test suite failed.
  9390. bool Failed() const {
  9391. return failed_test_count() > 0 || ad_hoc_test_result().Failed();
  9392. }
  9393. // Returns the elapsed time, in milliseconds.
  9394. TimeInMillis elapsed_time() const { return elapsed_time_; }
  9395. // Gets the time of the test suite start, in ms from the start of the
  9396. // UNIX epoch.
  9397. TimeInMillis start_timestamp() const { return start_timestamp_; }
  9398. // Returns the i-th test among all the tests. i can range from 0 to
  9399. // total_test_count() - 1. If i is not in that range, returns NULL.
  9400. const TestInfo* GetTestInfo(int i) const;
  9401. // Returns the TestResult that holds test properties recorded during
  9402. // execution of SetUpTestSuite and TearDownTestSuite.
  9403. const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
  9404. private:
  9405. friend class Test;
  9406. friend class internal::UnitTestImpl;
  9407. // Gets the (mutable) vector of TestInfos in this TestSuite.
  9408. std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
  9409. // Gets the (immutable) vector of TestInfos in this TestSuite.
  9410. const std::vector<TestInfo*>& test_info_list() const {
  9411. return test_info_list_;
  9412. }
  9413. // Returns the i-th test among all the tests. i can range from 0 to
  9414. // total_test_count() - 1. If i is not in that range, returns NULL.
  9415. TestInfo* GetMutableTestInfo(int i);
  9416. // Sets the should_run member.
  9417. void set_should_run(bool should) { should_run_ = should; }
  9418. // Adds a TestInfo to this test suite. Will delete the TestInfo upon
  9419. // destruction of the TestSuite object.
  9420. void AddTestInfo(TestInfo * test_info);
  9421. // Clears the results of all tests in this test suite.
  9422. void ClearResult();
  9423. // Clears the results of all tests in the given test suite.
  9424. static void ClearTestSuiteResult(TestSuite* test_suite) {
  9425. test_suite->ClearResult();
  9426. }
  9427. // Runs every test in this TestSuite.
  9428. void Run();
  9429. // Skips the execution of tests under this TestSuite
  9430. void Skip();
  9431. // Runs SetUpTestSuite() for this TestSuite. This wrapper is needed
  9432. // for catching exceptions thrown from SetUpTestSuite().
  9433. void RunSetUpTestSuite() {
  9434. if (set_up_tc_ != nullptr) {
  9435. (*set_up_tc_)();
  9436. }
  9437. }
  9438. // Runs TearDownTestSuite() for this TestSuite. This wrapper is
  9439. // needed for catching exceptions thrown from TearDownTestSuite().
  9440. void RunTearDownTestSuite() {
  9441. if (tear_down_tc_ != nullptr) {
  9442. (*tear_down_tc_)();
  9443. }
  9444. }
  9445. // Returns true if and only if test passed.
  9446. static bool TestPassed(const TestInfo* test_info) {
  9447. return test_info->should_run() && test_info->result()->Passed();
  9448. }
  9449. // Returns true if and only if test skipped.
  9450. static bool TestSkipped(const TestInfo* test_info) {
  9451. return test_info->should_run() && test_info->result()->Skipped();
  9452. }
  9453. // Returns true if and only if test failed.
  9454. static bool TestFailed(const TestInfo* test_info) {
  9455. return test_info->should_run() && test_info->result()->Failed();
  9456. }
  9457. // Returns true if and only if the test is disabled and will be reported in
  9458. // the XML report.
  9459. static bool TestReportableDisabled(const TestInfo* test_info) {
  9460. return test_info->is_reportable() && test_info->is_disabled_;
  9461. }
  9462. // Returns true if and only if test is disabled.
  9463. static bool TestDisabled(const TestInfo* test_info) {
  9464. return test_info->is_disabled_;
  9465. }
  9466. // Returns true if and only if this test will appear in the XML report.
  9467. static bool TestReportable(const TestInfo* test_info) {
  9468. return test_info->is_reportable();
  9469. }
  9470. // Returns true if the given test should run.
  9471. static bool ShouldRunTest(const TestInfo* test_info) {
  9472. return test_info->should_run();
  9473. }
  9474. // Shuffles the tests in this test suite.
  9475. void ShuffleTests(internal::Random* random);
  9476. // Restores the test order to before the first shuffle.
  9477. void UnshuffleTests();
  9478. // Name of the test suite.
  9479. std::string name_;
  9480. // Name of the parameter type, or NULL if this is not a typed or a
  9481. // type-parameterized test.
  9482. const std::unique_ptr<const ::std::string> type_param_;
  9483. // The vector of TestInfos in their original order. It owns the
  9484. // elements in the vector.
  9485. std::vector<TestInfo*> test_info_list_;
  9486. // Provides a level of indirection for the test list to allow easy
  9487. // shuffling and restoring the test order. The i-th element in this
  9488. // vector is the index of the i-th test in the shuffled test list.
  9489. std::vector<int> test_indices_;
  9490. // Pointer to the function that sets up the test suite.
  9491. internal::SetUpTestSuiteFunc set_up_tc_;
  9492. // Pointer to the function that tears down the test suite.
  9493. internal::TearDownTestSuiteFunc tear_down_tc_;
  9494. // True if and only if any test in this test suite should run.
  9495. bool should_run_;
  9496. // The start time, in milliseconds since UNIX Epoch.
  9497. TimeInMillis start_timestamp_;
  9498. // Elapsed time, in milliseconds.
  9499. TimeInMillis elapsed_time_;
  9500. // Holds test properties recorded during execution of SetUpTestSuite and
  9501. // TearDownTestSuite.
  9502. TestResult ad_hoc_test_result_;
  9503. // We disallow copying TestSuites.
  9504. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestSuite);
  9505. };
  9506. // An Environment object is capable of setting up and tearing down an
  9507. // environment. You should subclass this to define your own
  9508. // environment(s).
  9509. //
  9510. // An Environment object does the set-up and tear-down in virtual
  9511. // methods SetUp() and TearDown() instead of the constructor and the
  9512. // destructor, as:
  9513. //
  9514. // 1. You cannot safely throw from a destructor. This is a problem
  9515. // as in some cases Google Test is used where exceptions are enabled, and
  9516. // we may want to implement ASSERT_* using exceptions where they are
  9517. // available.
  9518. // 2. You cannot use ASSERT_* directly in a constructor or
  9519. // destructor.
  9520. class Environment {
  9521. public:
  9522. // The d'tor is virtual as we need to subclass Environment.
  9523. virtual ~Environment() {}
  9524. // Override this to define how to set up the environment.
  9525. virtual void SetUp() {}
  9526. // Override this to define how to tear down the environment.
  9527. virtual void TearDown() {}
  9528. private:
  9529. // If you see an error about overriding the following function or
  9530. // about it being private, you have mis-spelled SetUp() as Setup().
  9531. struct Setup_should_be_spelled_SetUp {};
  9532. virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
  9533. };
  9534. #if GTEST_HAS_EXCEPTIONS
  9535. // Exception which can be thrown from TestEventListener::OnTestPartResult.
  9536. class GTEST_API_ AssertionException
  9537. : public internal::GoogleTestFailureException {
  9538. public:
  9539. explicit AssertionException(const TestPartResult& result)
  9540. : GoogleTestFailureException(result) {}
  9541. };
  9542. #endif // GTEST_HAS_EXCEPTIONS
  9543. // The interface for tracing execution of tests. The methods are organized in
  9544. // the order the corresponding events are fired.
  9545. class TestEventListener {
  9546. public:
  9547. virtual ~TestEventListener() {}
  9548. // Fired before any test activity starts.
  9549. virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
  9550. // Fired before each iteration of tests starts. There may be more than
  9551. // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
  9552. // index, starting from 0.
  9553. virtual void OnTestIterationStart(const UnitTest& unit_test,
  9554. int iteration) = 0;
  9555. // Fired before environment set-up for each iteration of tests starts.
  9556. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
  9557. // Fired after environment set-up for each iteration of tests ends.
  9558. virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
  9559. // Fired before the test suite starts.
  9560. virtual void OnTestSuiteStart(const TestSuite& /*test_suite*/) {}
  9561. // Legacy API is deprecated but still available
  9562. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9563. virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
  9564. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9565. // Fired before the test starts.
  9566. virtual void OnTestStart(const TestInfo& test_info) = 0;
  9567. // Fired after a failed assertion or a SUCCEED() invocation.
  9568. // If you want to throw an exception from this function to skip to the next
  9569. // TEST, it must be AssertionException defined above, or inherited from it.
  9570. virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
  9571. // Fired after the test ends.
  9572. virtual void OnTestEnd(const TestInfo& test_info) = 0;
  9573. // Fired after the test suite ends.
  9574. virtual void OnTestSuiteEnd(const TestSuite& /*test_suite*/) {}
  9575. // Legacy API is deprecated but still available
  9576. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9577. virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
  9578. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9579. // Fired before environment tear-down for each iteration of tests starts.
  9580. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
  9581. // Fired after environment tear-down for each iteration of tests ends.
  9582. virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
  9583. // Fired after each iteration of tests finishes.
  9584. virtual void OnTestIterationEnd(const UnitTest& unit_test,
  9585. int iteration) = 0;
  9586. // Fired after all test activities have ended.
  9587. virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
  9588. };
  9589. // The convenience class for users who need to override just one or two
  9590. // methods and are not concerned that a possible change to a signature of
  9591. // the methods they override will not be caught during the build. For
  9592. // comments about each method please see the definition of TestEventListener
  9593. // above.
  9594. class EmptyTestEventListener : public TestEventListener {
  9595. public:
  9596. void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
  9597. void OnTestIterationStart(const UnitTest& /*unit_test*/,
  9598. int /*iteration*/) override {}
  9599. void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
  9600. void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
  9601. void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
  9602. // Legacy API is deprecated but still available
  9603. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9604. void OnTestCaseStart(const TestCase& /*test_case*/) override {}
  9605. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9606. void OnTestStart(const TestInfo& /*test_info*/) override {}
  9607. void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {}
  9608. void OnTestEnd(const TestInfo& /*test_info*/) override {}
  9609. void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
  9610. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9611. void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
  9612. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9613. void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
  9614. void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
  9615. void OnTestIterationEnd(const UnitTest& /*unit_test*/,
  9616. int /*iteration*/) override {}
  9617. void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
  9618. };
  9619. // TestEventListeners lets users add listeners to track events in Google Test.
  9620. class GTEST_API_ TestEventListeners {
  9621. public:
  9622. TestEventListeners();
  9623. ~TestEventListeners();
  9624. // Appends an event listener to the end of the list. Google Test assumes
  9625. // the ownership of the listener (i.e. it will delete the listener when
  9626. // the test program finishes).
  9627. void Append(TestEventListener* listener);
  9628. // Removes the given event listener from the list and returns it. It then
  9629. // becomes the caller's responsibility to delete the listener. Returns
  9630. // NULL if the listener is not found in the list.
  9631. TestEventListener* Release(TestEventListener* listener);
  9632. // Returns the standard listener responsible for the default console
  9633. // output. Can be removed from the listeners list to shut down default
  9634. // console output. Note that removing this object from the listener list
  9635. // with Release transfers its ownership to the caller and makes this
  9636. // function return NULL the next time.
  9637. TestEventListener* default_result_printer() const {
  9638. return default_result_printer_;
  9639. }
  9640. // Returns the standard listener responsible for the default XML output
  9641. // controlled by the --gtest_output=xml flag. Can be removed from the
  9642. // listeners list by users who want to shut down the default XML output
  9643. // controlled by this flag and substitute it with custom one. Note that
  9644. // removing this object from the listener list with Release transfers its
  9645. // ownership to the caller and makes this function return NULL the next
  9646. // time.
  9647. TestEventListener* default_xml_generator() const {
  9648. return default_xml_generator_;
  9649. }
  9650. private:
  9651. friend class TestSuite;
  9652. friend class TestInfo;
  9653. friend class internal::DefaultGlobalTestPartResultReporter;
  9654. friend class internal::NoExecDeathTest;
  9655. friend class internal::TestEventListenersAccessor;
  9656. friend class internal::UnitTestImpl;
  9657. // Returns repeater that broadcasts the TestEventListener events to all
  9658. // subscribers.
  9659. TestEventListener* repeater();
  9660. // Sets the default_result_printer attribute to the provided listener.
  9661. // The listener is also added to the listener list and previous
  9662. // default_result_printer is removed from it and deleted. The listener can
  9663. // also be NULL in which case it will not be added to the list. Does
  9664. // nothing if the previous and the current listener objects are the same.
  9665. void SetDefaultResultPrinter(TestEventListener* listener);
  9666. // Sets the default_xml_generator attribute to the provided listener. The
  9667. // listener is also added to the listener list and previous
  9668. // default_xml_generator is removed from it and deleted. The listener can
  9669. // also be NULL in which case it will not be added to the list. Does
  9670. // nothing if the previous and the current listener objects are the same.
  9671. void SetDefaultXmlGenerator(TestEventListener* listener);
  9672. // Controls whether events will be forwarded by the repeater to the
  9673. // listeners in the list.
  9674. bool EventForwardingEnabled() const;
  9675. void SuppressEventForwarding();
  9676. // The actual list of listeners.
  9677. internal::TestEventRepeater* repeater_;
  9678. // Listener responsible for the standard result output.
  9679. TestEventListener* default_result_printer_;
  9680. // Listener responsible for the creation of the XML output file.
  9681. TestEventListener* default_xml_generator_;
  9682. // We disallow copying TestEventListeners.
  9683. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
  9684. };
  9685. // A UnitTest consists of a vector of TestSuites.
  9686. //
  9687. // This is a singleton class. The only instance of UnitTest is
  9688. // created when UnitTest::GetInstance() is first called. This
  9689. // instance is never deleted.
  9690. //
  9691. // UnitTest is not copyable.
  9692. //
  9693. // This class is thread-safe as long as the methods are called
  9694. // according to their specification.
  9695. class GTEST_API_ UnitTest {
  9696. public:
  9697. // Gets the singleton UnitTest object. The first time this method
  9698. // is called, a UnitTest object is constructed and returned.
  9699. // Consecutive calls will return the same object.
  9700. static UnitTest* GetInstance();
  9701. // Runs all tests in this UnitTest object and prints the result.
  9702. // Returns 0 if successful, or 1 otherwise.
  9703. //
  9704. // This method can only be called from the main thread.
  9705. //
  9706. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  9707. int Run() GTEST_MUST_USE_RESULT_;
  9708. // Returns the working directory when the first TEST() or TEST_F()
  9709. // was executed. The UnitTest object owns the string.
  9710. const char* original_working_dir() const;
  9711. // Returns the TestSuite object for the test that's currently running,
  9712. // or NULL if no test is running.
  9713. const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_);
  9714. // Legacy API is still available but deprecated
  9715. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9716. const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_);
  9717. #endif
  9718. // Returns the TestInfo object for the test that's currently running,
  9719. // or NULL if no test is running.
  9720. const TestInfo* current_test_info() const
  9721. GTEST_LOCK_EXCLUDED_(mutex_);
  9722. // Returns the random seed used at the start of the current test run.
  9723. int random_seed() const;
  9724. // Returns the ParameterizedTestSuiteRegistry object used to keep track of
  9725. // value-parameterized tests and instantiate and register them.
  9726. //
  9727. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  9728. internal::ParameterizedTestSuiteRegistry& parameterized_test_registry()
  9729. GTEST_LOCK_EXCLUDED_(mutex_);
  9730. // Gets the number of successful test suites.
  9731. int successful_test_suite_count() const;
  9732. // Gets the number of failed test suites.
  9733. int failed_test_suite_count() const;
  9734. // Gets the number of all test suites.
  9735. int total_test_suite_count() const;
  9736. // Gets the number of all test suites that contain at least one test
  9737. // that should run.
  9738. int test_suite_to_run_count() const;
  9739. // Legacy API is deprecated but still available
  9740. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9741. int successful_test_case_count() const;
  9742. int failed_test_case_count() const;
  9743. int total_test_case_count() const;
  9744. int test_case_to_run_count() const;
  9745. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9746. // Gets the number of successful tests.
  9747. int successful_test_count() const;
  9748. // Gets the number of skipped tests.
  9749. int skipped_test_count() const;
  9750. // Gets the number of failed tests.
  9751. int failed_test_count() const;
  9752. // Gets the number of disabled tests that will be reported in the XML report.
  9753. int reportable_disabled_test_count() const;
  9754. // Gets the number of disabled tests.
  9755. int disabled_test_count() const;
  9756. // Gets the number of tests to be printed in the XML report.
  9757. int reportable_test_count() const;
  9758. // Gets the number of all tests.
  9759. int total_test_count() const;
  9760. // Gets the number of tests that should run.
  9761. int test_to_run_count() const;
  9762. // Gets the time of the test program start, in ms from the start of the
  9763. // UNIX epoch.
  9764. TimeInMillis start_timestamp() const;
  9765. // Gets the elapsed time, in milliseconds.
  9766. TimeInMillis elapsed_time() const;
  9767. // Returns true if and only if the unit test passed (i.e. all test suites
  9768. // passed).
  9769. bool Passed() const;
  9770. // Returns true if and only if the unit test failed (i.e. some test suite
  9771. // failed or something outside of all tests failed).
  9772. bool Failed() const;
  9773. // Gets the i-th test suite among all the test suites. i can range from 0 to
  9774. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  9775. const TestSuite* GetTestSuite(int i) const;
  9776. // Legacy API is deprecated but still available
  9777. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9778. const TestCase* GetTestCase(int i) const;
  9779. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9780. // Returns the TestResult containing information on test failures and
  9781. // properties logged outside of individual test suites.
  9782. const TestResult& ad_hoc_test_result() const;
  9783. // Returns the list of event listeners that can be used to track events
  9784. // inside Google Test.
  9785. TestEventListeners& listeners();
  9786. private:
  9787. // Registers and returns a global test environment. When a test
  9788. // program is run, all global test environments will be set-up in
  9789. // the order they were registered. After all tests in the program
  9790. // have finished, all global test environments will be torn-down in
  9791. // the *reverse* order they were registered.
  9792. //
  9793. // The UnitTest object takes ownership of the given environment.
  9794. //
  9795. // This method can only be called from the main thread.
  9796. Environment* AddEnvironment(Environment* env);
  9797. // Adds a TestPartResult to the current TestResult object. All
  9798. // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
  9799. // eventually call this to report their results. The user code
  9800. // should use the assertion macros instead of calling this directly.
  9801. void AddTestPartResult(TestPartResult::Type result_type,
  9802. const char* file_name,
  9803. int line_number,
  9804. const std::string& message,
  9805. const std::string& os_stack_trace)
  9806. GTEST_LOCK_EXCLUDED_(mutex_);
  9807. // Adds a TestProperty to the current TestResult object when invoked from
  9808. // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
  9809. // from SetUpTestSuite or TearDownTestSuite, or to the global property set
  9810. // when invoked elsewhere. If the result already contains a property with
  9811. // the same key, the value will be updated.
  9812. void RecordProperty(const std::string& key, const std::string& value);
  9813. // Gets the i-th test suite among all the test suites. i can range from 0 to
  9814. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  9815. TestSuite* GetMutableTestSuite(int i);
  9816. // Accessors for the implementation object.
  9817. internal::UnitTestImpl* impl() { return impl_; }
  9818. const internal::UnitTestImpl* impl() const { return impl_; }
  9819. // These classes and functions are friends as they need to access private
  9820. // members of UnitTest.
  9821. friend class ScopedTrace;
  9822. friend class Test;
  9823. friend class internal::AssertHelper;
  9824. friend class internal::StreamingListenerTest;
  9825. friend class internal::UnitTestRecordPropertyTestHelper;
  9826. friend Environment* AddGlobalTestEnvironment(Environment* env);
  9827. friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();
  9828. friend internal::UnitTestImpl* internal::GetUnitTestImpl();
  9829. friend void internal::ReportFailureInUnknownLocation(
  9830. TestPartResult::Type result_type,
  9831. const std::string& message);
  9832. // Creates an empty UnitTest.
  9833. UnitTest();
  9834. // D'tor
  9835. virtual ~UnitTest();
  9836. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  9837. // Google Test trace stack.
  9838. void PushGTestTrace(const internal::TraceInfo& trace)
  9839. GTEST_LOCK_EXCLUDED_(mutex_);
  9840. // Pops a trace from the per-thread Google Test trace stack.
  9841. void PopGTestTrace()
  9842. GTEST_LOCK_EXCLUDED_(mutex_);
  9843. // Protects mutable state in *impl_. This is mutable as some const
  9844. // methods need to lock it too.
  9845. mutable internal::Mutex mutex_;
  9846. // Opaque implementation object. This field is never changed once
  9847. // the object is constructed. We don't mark it as const here, as
  9848. // doing so will cause a warning in the constructor of UnitTest.
  9849. // Mutable state in *impl_ is protected by mutex_.
  9850. internal::UnitTestImpl* impl_;
  9851. // We disallow copying UnitTest.
  9852. GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
  9853. };
  9854. // A convenient wrapper for adding an environment for the test
  9855. // program.
  9856. //
  9857. // You should call this before RUN_ALL_TESTS() is called, probably in
  9858. // main(). If you use gtest_main, you need to call this before main()
  9859. // starts for it to take effect. For example, you can define a global
  9860. // variable like this:
  9861. //
  9862. // testing::Environment* const foo_env =
  9863. // testing::AddGlobalTestEnvironment(new FooEnvironment);
  9864. //
  9865. // However, we strongly recommend you to write your own main() and
  9866. // call AddGlobalTestEnvironment() there, as relying on initialization
  9867. // of global variables makes the code harder to read and may cause
  9868. // problems when you register multiple environments from different
  9869. // translation units and the environments have dependencies among them
  9870. // (remember that the compiler doesn't guarantee the order in which
  9871. // global variables from different translation units are initialized).
  9872. inline Environment* AddGlobalTestEnvironment(Environment* env) {
  9873. return UnitTest::GetInstance()->AddEnvironment(env);
  9874. }
  9875. // Initializes Google Test. This must be called before calling
  9876. // RUN_ALL_TESTS(). In particular, it parses a command line for the
  9877. // flags that Google Test recognizes. Whenever a Google Test flag is
  9878. // seen, it is removed from argv, and *argc is decremented.
  9879. //
  9880. // No value is returned. Instead, the Google Test flag variables are
  9881. // updated.
  9882. //
  9883. // Calling the function for the second time has no user-visible effect.
  9884. GTEST_API_ void InitGoogleTest(int* argc, char** argv);
  9885. // This overloaded version can be used in Windows programs compiled in
  9886. // UNICODE mode.
  9887. GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
  9888. // This overloaded version can be used on Arduino/embedded platforms where
  9889. // there is no argc/argv.
  9890. GTEST_API_ void InitGoogleTest();
  9891. namespace internal {
  9892. // Separate the error generating code from the code path to reduce the stack
  9893. // frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
  9894. // when calling EXPECT_* in a tight loop.
  9895. template <typename T1, typename T2>
  9896. AssertionResult CmpHelperEQFailure(const char* lhs_expression,
  9897. const char* rhs_expression,
  9898. const T1& lhs, const T2& rhs) {
  9899. return EqFailure(lhs_expression,
  9900. rhs_expression,
  9901. FormatForComparisonFailureMessage(lhs, rhs),
  9902. FormatForComparisonFailureMessage(rhs, lhs),
  9903. false);
  9904. }
  9905. // This block of code defines operator==/!=
  9906. // to block lexical scope lookup.
  9907. // It prevents using invalid operator==/!= defined at namespace scope.
  9908. struct faketype {};
  9909. inline bool operator==(faketype, faketype) { return true; }
  9910. inline bool operator!=(faketype, faketype) { return false; }
  9911. // The helper function for {ASSERT|EXPECT}_EQ.
  9912. template <typename T1, typename T2>
  9913. AssertionResult CmpHelperEQ(const char* lhs_expression,
  9914. const char* rhs_expression,
  9915. const T1& lhs,
  9916. const T2& rhs) {
  9917. if (lhs == rhs) {
  9918. return AssertionSuccess();
  9919. }
  9920. return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
  9921. }
  9922. class EqHelper {
  9923. public:
  9924. // This templatized version is for the general case.
  9925. template <
  9926. typename T1, typename T2,
  9927. // Disable this overload for cases where one argument is a pointer
  9928. // and the other is the null pointer constant.
  9929. typename std::enable_if<!std::is_integral<T1>::value ||
  9930. !std::is_pointer<T2>::value>::type* = nullptr>
  9931. static AssertionResult Compare(const char* lhs_expression,
  9932. const char* rhs_expression, const T1& lhs,
  9933. const T2& rhs) {
  9934. return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
  9935. }
  9936. // With this overloaded version, we allow anonymous enums to be used
  9937. // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
  9938. // enums can be implicitly cast to BiggestInt.
  9939. //
  9940. // Even though its body looks the same as the above version, we
  9941. // cannot merge the two, as it will make anonymous enums unhappy.
  9942. static AssertionResult Compare(const char* lhs_expression,
  9943. const char* rhs_expression,
  9944. BiggestInt lhs,
  9945. BiggestInt rhs) {
  9946. return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
  9947. }
  9948. template <typename T>
  9949. static AssertionResult Compare(
  9950. const char* lhs_expression, const char* rhs_expression,
  9951. // Handle cases where '0' is used as a null pointer literal.
  9952. std::nullptr_t /* lhs */, T* rhs) {
  9953. // We already know that 'lhs' is a null pointer.
  9954. return CmpHelperEQ(lhs_expression, rhs_expression, static_cast<T*>(nullptr),
  9955. rhs);
  9956. }
  9957. };
  9958. // Separate the error generating code from the code path to reduce the stack
  9959. // frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
  9960. // when calling EXPECT_OP in a tight loop.
  9961. template <typename T1, typename T2>
  9962. AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
  9963. const T1& val1, const T2& val2,
  9964. const char* op) {
  9965. return AssertionFailure()
  9966. << "Expected: (" << expr1 << ") " << op << " (" << expr2
  9967. << "), actual: " << FormatForComparisonFailureMessage(val1, val2)
  9968. << " vs " << FormatForComparisonFailureMessage(val2, val1);
  9969. }
  9970. // A macro for implementing the helper functions needed to implement
  9971. // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
  9972. // of similar code.
  9973. //
  9974. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  9975. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
  9976. template <typename T1, typename T2>\
  9977. AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
  9978. const T1& val1, const T2& val2) {\
  9979. if (val1 op val2) {\
  9980. return AssertionSuccess();\
  9981. } else {\
  9982. return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
  9983. }\
  9984. }
  9985. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  9986. // Implements the helper function for {ASSERT|EXPECT}_NE
  9987. GTEST_IMPL_CMP_HELPER_(NE, !=)
  9988. // Implements the helper function for {ASSERT|EXPECT}_LE
  9989. GTEST_IMPL_CMP_HELPER_(LE, <=)
  9990. // Implements the helper function for {ASSERT|EXPECT}_LT
  9991. GTEST_IMPL_CMP_HELPER_(LT, <)
  9992. // Implements the helper function for {ASSERT|EXPECT}_GE
  9993. GTEST_IMPL_CMP_HELPER_(GE, >=)
  9994. // Implements the helper function for {ASSERT|EXPECT}_GT
  9995. GTEST_IMPL_CMP_HELPER_(GT, >)
  9996. #undef GTEST_IMPL_CMP_HELPER_
  9997. // The helper function for {ASSERT|EXPECT}_STREQ.
  9998. //
  9999. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  10000. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
  10001. const char* s2_expression,
  10002. const char* s1,
  10003. const char* s2);
  10004. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  10005. //
  10006. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  10007. GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
  10008. const char* s2_expression,
  10009. const char* s1,
  10010. const char* s2);
  10011. // The helper function for {ASSERT|EXPECT}_STRNE.
  10012. //
  10013. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  10014. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
  10015. const char* s2_expression,
  10016. const char* s1,
  10017. const char* s2);
  10018. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  10019. //
  10020. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  10021. GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  10022. const char* s2_expression,
  10023. const char* s1,
  10024. const char* s2);
  10025. // Helper function for *_STREQ on wide strings.
  10026. //
  10027. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  10028. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
  10029. const char* s2_expression,
  10030. const wchar_t* s1,
  10031. const wchar_t* s2);
  10032. // Helper function for *_STRNE on wide strings.
  10033. //
  10034. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  10035. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
  10036. const char* s2_expression,
  10037. const wchar_t* s1,
  10038. const wchar_t* s2);
  10039. } // namespace internal
  10040. // IsSubstring() and IsNotSubstring() are intended to be used as the
  10041. // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
  10042. // themselves. They check whether needle is a substring of haystack
  10043. // (NULL is considered a substring of itself only), and return an
  10044. // appropriate error message when they fail.
  10045. //
  10046. // The {needle,haystack}_expr arguments are the stringified
  10047. // expressions that generated the two real arguments.
  10048. GTEST_API_ AssertionResult IsSubstring(
  10049. const char* needle_expr, const char* haystack_expr,
  10050. const char* needle, const char* haystack);
  10051. GTEST_API_ AssertionResult IsSubstring(
  10052. const char* needle_expr, const char* haystack_expr,
  10053. const wchar_t* needle, const wchar_t* haystack);
  10054. GTEST_API_ AssertionResult IsNotSubstring(
  10055. const char* needle_expr, const char* haystack_expr,
  10056. const char* needle, const char* haystack);
  10057. GTEST_API_ AssertionResult IsNotSubstring(
  10058. const char* needle_expr, const char* haystack_expr,
  10059. const wchar_t* needle, const wchar_t* haystack);
  10060. GTEST_API_ AssertionResult IsSubstring(
  10061. const char* needle_expr, const char* haystack_expr,
  10062. const ::std::string& needle, const ::std::string& haystack);
  10063. GTEST_API_ AssertionResult IsNotSubstring(
  10064. const char* needle_expr, const char* haystack_expr,
  10065. const ::std::string& needle, const ::std::string& haystack);
  10066. #if GTEST_HAS_STD_WSTRING
  10067. GTEST_API_ AssertionResult IsSubstring(
  10068. const char* needle_expr, const char* haystack_expr,
  10069. const ::std::wstring& needle, const ::std::wstring& haystack);
  10070. GTEST_API_ AssertionResult IsNotSubstring(
  10071. const char* needle_expr, const char* haystack_expr,
  10072. const ::std::wstring& needle, const ::std::wstring& haystack);
  10073. #endif // GTEST_HAS_STD_WSTRING
  10074. namespace internal {
  10075. // Helper template function for comparing floating-points.
  10076. //
  10077. // Template parameter:
  10078. //
  10079. // RawType: the raw floating-point type (either float or double)
  10080. //
  10081. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  10082. template <typename RawType>
  10083. AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
  10084. const char* rhs_expression,
  10085. RawType lhs_value,
  10086. RawType rhs_value) {
  10087. const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
  10088. if (lhs.AlmostEquals(rhs)) {
  10089. return AssertionSuccess();
  10090. }
  10091. ::std::stringstream lhs_ss;
  10092. lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  10093. << lhs_value;
  10094. ::std::stringstream rhs_ss;
  10095. rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  10096. << rhs_value;
  10097. return EqFailure(lhs_expression,
  10098. rhs_expression,
  10099. StringStreamToString(&lhs_ss),
  10100. StringStreamToString(&rhs_ss),
  10101. false);
  10102. }
  10103. // Helper function for implementing ASSERT_NEAR.
  10104. //
  10105. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  10106. GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
  10107. const char* expr2,
  10108. const char* abs_error_expr,
  10109. double val1,
  10110. double val2,
  10111. double abs_error);
  10112. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  10113. // A class that enables one to stream messages to assertion macros
  10114. class GTEST_API_ AssertHelper {
  10115. public:
  10116. // Constructor.
  10117. AssertHelper(TestPartResult::Type type,
  10118. const char* file,
  10119. int line,
  10120. const char* message);
  10121. ~AssertHelper();
  10122. // Message assignment is a semantic trick to enable assertion
  10123. // streaming; see the GTEST_MESSAGE_ macro below.
  10124. void operator=(const Message& message) const;
  10125. private:
  10126. // We put our data in a struct so that the size of the AssertHelper class can
  10127. // be as small as possible. This is important because gcc is incapable of
  10128. // re-using stack space even for temporary variables, so every EXPECT_EQ
  10129. // reserves stack space for another AssertHelper.
  10130. struct AssertHelperData {
  10131. AssertHelperData(TestPartResult::Type t,
  10132. const char* srcfile,
  10133. int line_num,
  10134. const char* msg)
  10135. : type(t), file(srcfile), line(line_num), message(msg) { }
  10136. TestPartResult::Type const type;
  10137. const char* const file;
  10138. int const line;
  10139. std::string const message;
  10140. private:
  10141. GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
  10142. };
  10143. AssertHelperData* const data_;
  10144. GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
  10145. };
  10146. } // namespace internal
  10147. // The pure interface class that all value-parameterized tests inherit from.
  10148. // A value-parameterized class must inherit from both ::testing::Test and
  10149. // ::testing::WithParamInterface. In most cases that just means inheriting
  10150. // from ::testing::TestWithParam, but more complicated test hierarchies
  10151. // may need to inherit from Test and WithParamInterface at different levels.
  10152. //
  10153. // This interface has support for accessing the test parameter value via
  10154. // the GetParam() method.
  10155. //
  10156. // Use it with one of the parameter generator defining functions, like Range(),
  10157. // Values(), ValuesIn(), Bool(), and Combine().
  10158. //
  10159. // class FooTest : public ::testing::TestWithParam<int> {
  10160. // protected:
  10161. // FooTest() {
  10162. // // Can use GetParam() here.
  10163. // }
  10164. // ~FooTest() override {
  10165. // // Can use GetParam() here.
  10166. // }
  10167. // void SetUp() override {
  10168. // // Can use GetParam() here.
  10169. // }
  10170. // void TearDown override {
  10171. // // Can use GetParam() here.
  10172. // }
  10173. // };
  10174. // TEST_P(FooTest, DoesBar) {
  10175. // // Can use GetParam() method here.
  10176. // Foo foo;
  10177. // ASSERT_TRUE(foo.DoesBar(GetParam()));
  10178. // }
  10179. // INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
  10180. template <typename T>
  10181. class WithParamInterface {
  10182. public:
  10183. typedef T ParamType;
  10184. virtual ~WithParamInterface() {}
  10185. // The current parameter value. Is also available in the test fixture's
  10186. // constructor.
  10187. static const ParamType& GetParam() {
  10188. GTEST_CHECK_(parameter_ != nullptr)
  10189. << "GetParam() can only be called inside a value-parameterized test "
  10190. << "-- did you intend to write TEST_P instead of TEST_F?";
  10191. return *parameter_;
  10192. }
  10193. private:
  10194. // Sets parameter value. The caller is responsible for making sure the value
  10195. // remains alive and unchanged throughout the current test.
  10196. static void SetParam(const ParamType* parameter) {
  10197. parameter_ = parameter;
  10198. }
  10199. // Static value used for accessing parameter during a test lifetime.
  10200. static const ParamType* parameter_;
  10201. // TestClass must be a subclass of WithParamInterface<T> and Test.
  10202. template <class TestClass> friend class internal::ParameterizedTestFactory;
  10203. };
  10204. template <typename T>
  10205. const T* WithParamInterface<T>::parameter_ = nullptr;
  10206. // Most value-parameterized classes can ignore the existence of
  10207. // WithParamInterface, and can just inherit from ::testing::TestWithParam.
  10208. template <typename T>
  10209. class TestWithParam : public Test, public WithParamInterface<T> {
  10210. };
  10211. // Macros for indicating success/failure in test code.
  10212. // Skips test in runtime.
  10213. // Skipping test aborts current function.
  10214. // Skipped tests are neither successful nor failed.
  10215. #define GTEST_SKIP() GTEST_SKIP_("")
  10216. // ADD_FAILURE unconditionally adds a failure to the current test.
  10217. // SUCCEED generates a success - it doesn't automatically make the
  10218. // current test successful, as a test is only successful when it has
  10219. // no failure.
  10220. //
  10221. // EXPECT_* verifies that a certain condition is satisfied. If not,
  10222. // it behaves like ADD_FAILURE. In particular:
  10223. //
  10224. // EXPECT_TRUE verifies that a Boolean condition is true.
  10225. // EXPECT_FALSE verifies that a Boolean condition is false.
  10226. //
  10227. // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
  10228. // that they will also abort the current function on failure. People
  10229. // usually want the fail-fast behavior of FAIL and ASSERT_*, but those
  10230. // writing data-driven tests often find themselves using ADD_FAILURE
  10231. // and EXPECT_* more.
  10232. // Generates a nonfatal failure with a generic message.
  10233. #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
  10234. // Generates a nonfatal failure at the given source file location with
  10235. // a generic message.
  10236. #define ADD_FAILURE_AT(file, line) \
  10237. GTEST_MESSAGE_AT_(file, line, "Failed", \
  10238. ::testing::TestPartResult::kNonFatalFailure)
  10239. // Generates a fatal failure with a generic message.
  10240. #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
  10241. // Like GTEST_FAIL(), but at the given source file location.
  10242. #define GTEST_FAIL_AT(file, line) \
  10243. GTEST_MESSAGE_AT_(file, line, "Failed", \
  10244. ::testing::TestPartResult::kFatalFailure)
  10245. // Define this macro to 1 to omit the definition of FAIL(), which is a
  10246. // generic name and clashes with some other libraries.
  10247. #if !GTEST_DONT_DEFINE_FAIL
  10248. # define FAIL() GTEST_FAIL()
  10249. #endif
  10250. // Generates a success with a generic message.
  10251. #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
  10252. // Define this macro to 1 to omit the definition of SUCCEED(), which
  10253. // is a generic name and clashes with some other libraries.
  10254. #if !GTEST_DONT_DEFINE_SUCCEED
  10255. # define SUCCEED() GTEST_SUCCEED()
  10256. #endif
  10257. // Macros for testing exceptions.
  10258. //
  10259. // * {ASSERT|EXPECT}_THROW(statement, expected_exception):
  10260. // Tests that the statement throws the expected exception.
  10261. // * {ASSERT|EXPECT}_NO_THROW(statement):
  10262. // Tests that the statement doesn't throw any exception.
  10263. // * {ASSERT|EXPECT}_ANY_THROW(statement):
  10264. // Tests that the statement throws an exception.
  10265. #define EXPECT_THROW(statement, expected_exception) \
  10266. GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
  10267. #define EXPECT_NO_THROW(statement) \
  10268. GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
  10269. #define EXPECT_ANY_THROW(statement) \
  10270. GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
  10271. #define ASSERT_THROW(statement, expected_exception) \
  10272. GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
  10273. #define ASSERT_NO_THROW(statement) \
  10274. GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
  10275. #define ASSERT_ANY_THROW(statement) \
  10276. GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
  10277. // Boolean assertions. Condition can be either a Boolean expression or an
  10278. // AssertionResult. For more information on how to use AssertionResult with
  10279. // these macros see comments on that class.
  10280. #define GTEST_EXPECT_TRUE(condition) \
  10281. GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
  10282. GTEST_NONFATAL_FAILURE_)
  10283. #define GTEST_EXPECT_FALSE(condition) \
  10284. GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
  10285. GTEST_NONFATAL_FAILURE_)
  10286. #define GTEST_ASSERT_TRUE(condition) \
  10287. GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
  10288. GTEST_FATAL_FAILURE_)
  10289. #define GTEST_ASSERT_FALSE(condition) \
  10290. GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
  10291. GTEST_FATAL_FAILURE_)
  10292. // Define these macros to 1 to omit the definition of the corresponding
  10293. // EXPECT or ASSERT, which clashes with some users' own code.
  10294. #if !GTEST_DONT_DEFINE_EXPECT_TRUE
  10295. #define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)
  10296. #endif
  10297. #if !GTEST_DONT_DEFINE_EXPECT_FALSE
  10298. #define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)
  10299. #endif
  10300. #if !GTEST_DONT_DEFINE_ASSERT_TRUE
  10301. #define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)
  10302. #endif
  10303. #if !GTEST_DONT_DEFINE_ASSERT_FALSE
  10304. #define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)
  10305. #endif
  10306. // Macros for testing equalities and inequalities.
  10307. //
  10308. // * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
  10309. // * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
  10310. // * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
  10311. // * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
  10312. // * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
  10313. // * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
  10314. //
  10315. // When they are not, Google Test prints both the tested expressions and
  10316. // their actual values. The values must be compatible built-in types,
  10317. // or you will get a compiler error. By "compatible" we mean that the
  10318. // values can be compared by the respective operator.
  10319. //
  10320. // Note:
  10321. //
  10322. // 1. It is possible to make a user-defined type work with
  10323. // {ASSERT|EXPECT}_??(), but that requires overloading the
  10324. // comparison operators and is thus discouraged by the Google C++
  10325. // Usage Guide. Therefore, you are advised to use the
  10326. // {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
  10327. // equal.
  10328. //
  10329. // 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
  10330. // pointers (in particular, C strings). Therefore, if you use it
  10331. // with two C strings, you are testing how their locations in memory
  10332. // are related, not how their content is related. To compare two C
  10333. // strings by content, use {ASSERT|EXPECT}_STR*().
  10334. //
  10335. // 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to
  10336. // {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you
  10337. // what the actual value is when it fails, and similarly for the
  10338. // other comparisons.
  10339. //
  10340. // 4. Do not depend on the order in which {ASSERT|EXPECT}_??()
  10341. // evaluate their arguments, which is undefined.
  10342. //
  10343. // 5. These macros evaluate their arguments exactly once.
  10344. //
  10345. // Examples:
  10346. //
  10347. // EXPECT_NE(Foo(), 5);
  10348. // EXPECT_EQ(a_pointer, NULL);
  10349. // ASSERT_LT(i, array_size);
  10350. // ASSERT_GT(records.size(), 0) << "There is no record left.";
  10351. #define EXPECT_EQ(val1, val2) \
  10352. EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
  10353. #define EXPECT_NE(val1, val2) \
  10354. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
  10355. #define EXPECT_LE(val1, val2) \
  10356. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
  10357. #define EXPECT_LT(val1, val2) \
  10358. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
  10359. #define EXPECT_GE(val1, val2) \
  10360. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
  10361. #define EXPECT_GT(val1, val2) \
  10362. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
  10363. #define GTEST_ASSERT_EQ(val1, val2) \
  10364. ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
  10365. #define GTEST_ASSERT_NE(val1, val2) \
  10366. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
  10367. #define GTEST_ASSERT_LE(val1, val2) \
  10368. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
  10369. #define GTEST_ASSERT_LT(val1, val2) \
  10370. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
  10371. #define GTEST_ASSERT_GE(val1, val2) \
  10372. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
  10373. #define GTEST_ASSERT_GT(val1, val2) \
  10374. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
  10375. // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
  10376. // ASSERT_XY(), which clashes with some users' own code.
  10377. #if !GTEST_DONT_DEFINE_ASSERT_EQ
  10378. # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
  10379. #endif
  10380. #if !GTEST_DONT_DEFINE_ASSERT_NE
  10381. # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
  10382. #endif
  10383. #if !GTEST_DONT_DEFINE_ASSERT_LE
  10384. # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
  10385. #endif
  10386. #if !GTEST_DONT_DEFINE_ASSERT_LT
  10387. # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
  10388. #endif
  10389. #if !GTEST_DONT_DEFINE_ASSERT_GE
  10390. # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
  10391. #endif
  10392. #if !GTEST_DONT_DEFINE_ASSERT_GT
  10393. # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
  10394. #endif
  10395. // C-string Comparisons. All tests treat NULL and any non-NULL string
  10396. // as different. Two NULLs are equal.
  10397. //
  10398. // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
  10399. // * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2
  10400. // * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
  10401. // * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
  10402. //
  10403. // For wide or narrow string objects, you can use the
  10404. // {ASSERT|EXPECT}_??() macros.
  10405. //
  10406. // Don't depend on the order in which the arguments are evaluated,
  10407. // which is undefined.
  10408. //
  10409. // These macros evaluate their arguments exactly once.
  10410. #define EXPECT_STREQ(s1, s2) \
  10411. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
  10412. #define EXPECT_STRNE(s1, s2) \
  10413. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
  10414. #define EXPECT_STRCASEEQ(s1, s2) \
  10415. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
  10416. #define EXPECT_STRCASENE(s1, s2)\
  10417. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
  10418. #define ASSERT_STREQ(s1, s2) \
  10419. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
  10420. #define ASSERT_STRNE(s1, s2) \
  10421. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
  10422. #define ASSERT_STRCASEEQ(s1, s2) \
  10423. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
  10424. #define ASSERT_STRCASENE(s1, s2)\
  10425. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
  10426. // Macros for comparing floating-point numbers.
  10427. //
  10428. // * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):
  10429. // Tests that two float values are almost equal.
  10430. // * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):
  10431. // Tests that two double values are almost equal.
  10432. // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
  10433. // Tests that v1 and v2 are within the given distance to each other.
  10434. //
  10435. // Google Test uses ULP-based comparison to automatically pick a default
  10436. // error bound that is appropriate for the operands. See the
  10437. // FloatingPoint template class in gtest-internal.h if you are
  10438. // interested in the implementation details.
  10439. #define EXPECT_FLOAT_EQ(val1, val2)\
  10440. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
  10441. val1, val2)
  10442. #define EXPECT_DOUBLE_EQ(val1, val2)\
  10443. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
  10444. val1, val2)
  10445. #define ASSERT_FLOAT_EQ(val1, val2)\
  10446. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
  10447. val1, val2)
  10448. #define ASSERT_DOUBLE_EQ(val1, val2)\
  10449. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
  10450. val1, val2)
  10451. #define EXPECT_NEAR(val1, val2, abs_error)\
  10452. EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
  10453. val1, val2, abs_error)
  10454. #define ASSERT_NEAR(val1, val2, abs_error)\
  10455. ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
  10456. val1, val2, abs_error)
  10457. // These predicate format functions work on floating-point values, and
  10458. // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
  10459. //
  10460. // EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
  10461. // Asserts that val1 is less than, or almost equal to, val2. Fails
  10462. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  10463. GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
  10464. float val1, float val2);
  10465. GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
  10466. double val1, double val2);
  10467. #if GTEST_OS_WINDOWS
  10468. // Macros that test for HRESULT failure and success, these are only useful
  10469. // on Windows, and rely on Windows SDK macros and APIs to compile.
  10470. //
  10471. // * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
  10472. //
  10473. // When expr unexpectedly fails or succeeds, Google Test prints the
  10474. // expected result and the actual result with both a human-readable
  10475. // string representation of the error, if available, as well as the
  10476. // hex result code.
  10477. # define EXPECT_HRESULT_SUCCEEDED(expr) \
  10478. EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
  10479. # define ASSERT_HRESULT_SUCCEEDED(expr) \
  10480. ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
  10481. # define EXPECT_HRESULT_FAILED(expr) \
  10482. EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
  10483. # define ASSERT_HRESULT_FAILED(expr) \
  10484. ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
  10485. #endif // GTEST_OS_WINDOWS
  10486. // Macros that execute statement and check that it doesn't generate new fatal
  10487. // failures in the current thread.
  10488. //
  10489. // * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
  10490. //
  10491. // Examples:
  10492. //
  10493. // EXPECT_NO_FATAL_FAILURE(Process());
  10494. // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
  10495. //
  10496. #define ASSERT_NO_FATAL_FAILURE(statement) \
  10497. GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
  10498. #define EXPECT_NO_FATAL_FAILURE(statement) \
  10499. GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
  10500. // Causes a trace (including the given source file path and line number,
  10501. // and the given message) to be included in every test failure message generated
  10502. // by code in the scope of the lifetime of an instance of this class. The effect
  10503. // is undone with the destruction of the instance.
  10504. //
  10505. // The message argument can be anything streamable to std::ostream.
  10506. //
  10507. // Example:
  10508. // testing::ScopedTrace trace("file.cc", 123, "message");
  10509. //
  10510. class GTEST_API_ ScopedTrace {
  10511. public:
  10512. // The c'tor pushes the given source file location and message onto
  10513. // a trace stack maintained by Google Test.
  10514. // Template version. Uses Message() to convert the values into strings.
  10515. // Slow, but flexible.
  10516. template <typename T>
  10517. ScopedTrace(const char* file, int line, const T& message) {
  10518. PushTrace(file, line, (Message() << message).GetString());
  10519. }
  10520. // Optimize for some known types.
  10521. ScopedTrace(const char* file, int line, const char* message) {
  10522. PushTrace(file, line, message ? message : "(null)");
  10523. }
  10524. ScopedTrace(const char* file, int line, const std::string& message) {
  10525. PushTrace(file, line, message);
  10526. }
  10527. // The d'tor pops the info pushed by the c'tor.
  10528. //
  10529. // Note that the d'tor is not virtual in order to be efficient.
  10530. // Don't inherit from ScopedTrace!
  10531. ~ScopedTrace();
  10532. private:
  10533. void PushTrace(const char* file, int line, std::string message);
  10534. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
  10535. } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
  10536. // c'tor and d'tor. Therefore it doesn't
  10537. // need to be used otherwise.
  10538. // Causes a trace (including the source file path, the current line
  10539. // number, and the given message) to be included in every test failure
  10540. // message generated by code in the current scope. The effect is
  10541. // undone when the control leaves the current scope.
  10542. //
  10543. // The message argument can be anything streamable to std::ostream.
  10544. //
  10545. // In the implementation, we include the current line number as part
  10546. // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
  10547. // to appear in the same block - as long as they are on different
  10548. // lines.
  10549. //
  10550. // Assuming that each thread maintains its own stack of traces.
  10551. // Therefore, a SCOPED_TRACE() would (correctly) only affect the
  10552. // assertions in its own thread.
  10553. #define SCOPED_TRACE(message) \
  10554. ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
  10555. __FILE__, __LINE__, (message))
  10556. // Compile-time assertion for type equality.
  10557. // StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2
  10558. // are the same type. The value it returns is not interesting.
  10559. //
  10560. // Instead of making StaticAssertTypeEq a class template, we make it a
  10561. // function template that invokes a helper class template. This
  10562. // prevents a user from misusing StaticAssertTypeEq<T1, T2> by
  10563. // defining objects of that type.
  10564. //
  10565. // CAVEAT:
  10566. //
  10567. // When used inside a method of a class template,
  10568. // StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
  10569. // instantiated. For example, given:
  10570. //
  10571. // template <typename T> class Foo {
  10572. // public:
  10573. // void Bar() { testing::StaticAssertTypeEq<int, T>(); }
  10574. // };
  10575. //
  10576. // the code:
  10577. //
  10578. // void Test1() { Foo<bool> foo; }
  10579. //
  10580. // will NOT generate a compiler error, as Foo<bool>::Bar() is never
  10581. // actually instantiated. Instead, you need:
  10582. //
  10583. // void Test2() { Foo<bool> foo; foo.Bar(); }
  10584. //
  10585. // to cause a compiler error.
  10586. template <typename T1, typename T2>
  10587. constexpr bool StaticAssertTypeEq() noexcept {
  10588. static_assert(std::is_same<T1, T2>::value, "T1 and T2 are not the same type");
  10589. return true;
  10590. }
  10591. // Defines a test.
  10592. //
  10593. // The first parameter is the name of the test suite, and the second
  10594. // parameter is the name of the test within the test suite.
  10595. //
  10596. // The convention is to end the test suite name with "Test". For
  10597. // example, a test suite for the Foo class can be named FooTest.
  10598. //
  10599. // Test code should appear between braces after an invocation of
  10600. // this macro. Example:
  10601. //
  10602. // TEST(FooTest, InitializesCorrectly) {
  10603. // Foo foo;
  10604. // EXPECT_TRUE(foo.StatusIsOK());
  10605. // }
  10606. // Note that we call GetTestTypeId() instead of GetTypeId<
  10607. // ::testing::Test>() here to get the type ID of testing::Test. This
  10608. // is to work around a suspected linker bug when using Google Test as
  10609. // a framework on Mac OS X. The bug causes GetTypeId<
  10610. // ::testing::Test>() to return different values depending on whether
  10611. // the call is from the Google Test framework itself or from user test
  10612. // code. GetTestTypeId() is guaranteed to always return the same
  10613. // value, as it always calls GetTypeId<>() from the Google Test
  10614. // framework.
  10615. #define GTEST_TEST(test_suite_name, test_name) \
  10616. GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \
  10617. ::testing::internal::GetTestTypeId())
  10618. // Define this macro to 1 to omit the definition of TEST(), which
  10619. // is a generic name and clashes with some other libraries.
  10620. #if !GTEST_DONT_DEFINE_TEST
  10621. #define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
  10622. #endif
  10623. // Defines a test that uses a test fixture.
  10624. //
  10625. // The first parameter is the name of the test fixture class, which
  10626. // also doubles as the test suite name. The second parameter is the
  10627. // name of the test within the test suite.
  10628. //
  10629. // A test fixture class must be declared earlier. The user should put
  10630. // the test code between braces after using this macro. Example:
  10631. //
  10632. // class FooTest : public testing::Test {
  10633. // protected:
  10634. // void SetUp() override { b_.AddElement(3); }
  10635. //
  10636. // Foo a_;
  10637. // Foo b_;
  10638. // };
  10639. //
  10640. // TEST_F(FooTest, InitializesCorrectly) {
  10641. // EXPECT_TRUE(a_.StatusIsOK());
  10642. // }
  10643. //
  10644. // TEST_F(FooTest, ReturnsElementCountCorrectly) {
  10645. // EXPECT_EQ(a_.size(), 0);
  10646. // EXPECT_EQ(b_.size(), 1);
  10647. // }
  10648. //
  10649. // GOOGLETEST_CM0011 DO NOT DELETE
  10650. #if !GTEST_DONT_DEFINE_TEST
  10651. #define TEST_F(test_fixture, test_name)\
  10652. GTEST_TEST_(test_fixture, test_name, test_fixture, \
  10653. ::testing::internal::GetTypeId<test_fixture>())
  10654. #endif // !GTEST_DONT_DEFINE_TEST
  10655. // Returns a path to temporary directory.
  10656. // Tries to determine an appropriate directory for the platform.
  10657. GTEST_API_ std::string TempDir();
  10658. #ifdef _MSC_VER
  10659. # pragma warning(pop)
  10660. #endif
  10661. // Dynamically registers a test with the framework.
  10662. //
  10663. // This is an advanced API only to be used when the `TEST` macros are
  10664. // insufficient. The macros should be preferred when possible, as they avoid
  10665. // most of the complexity of calling this function.
  10666. //
  10667. // The `factory` argument is a factory callable (move-constructible) object or
  10668. // function pointer that creates a new instance of the Test object. It
  10669. // handles ownership to the caller. The signature of the callable is
  10670. // `Fixture*()`, where `Fixture` is the test fixture class for the test. All
  10671. // tests registered with the same `test_suite_name` must return the same
  10672. // fixture type. This is checked at runtime.
  10673. //
  10674. // The framework will infer the fixture class from the factory and will call
  10675. // the `SetUpTestSuite` and `TearDownTestSuite` for it.
  10676. //
  10677. // Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is
  10678. // undefined.
  10679. //
  10680. // Use case example:
  10681. //
  10682. // class MyFixture : public ::testing::Test {
  10683. // public:
  10684. // // All of these optional, just like in regular macro usage.
  10685. // static void SetUpTestSuite() { ... }
  10686. // static void TearDownTestSuite() { ... }
  10687. // void SetUp() override { ... }
  10688. // void TearDown() override { ... }
  10689. // };
  10690. //
  10691. // class MyTest : public MyFixture {
  10692. // public:
  10693. // explicit MyTest(int data) : data_(data) {}
  10694. // void TestBody() override { ... }
  10695. //
  10696. // private:
  10697. // int data_;
  10698. // };
  10699. //
  10700. // void RegisterMyTests(const std::vector<int>& values) {
  10701. // for (int v : values) {
  10702. // ::testing::RegisterTest(
  10703. // "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
  10704. // std::to_string(v).c_str(),
  10705. // __FILE__, __LINE__,
  10706. // // Important to use the fixture type as the return type here.
  10707. // [=]() -> MyFixture* { return new MyTest(v); });
  10708. // }
  10709. // }
  10710. // ...
  10711. // int main(int argc, char** argv) {
  10712. // std::vector<int> values_to_test = LoadValuesFromConfig();
  10713. // RegisterMyTests(values_to_test);
  10714. // ...
  10715. // return RUN_ALL_TESTS();
  10716. // }
  10717. //
  10718. template <int&... ExplicitParameterBarrier, typename Factory>
  10719. TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
  10720. const char* type_param, const char* value_param,
  10721. const char* file, int line, Factory factory) {
  10722. using TestT = typename std::remove_pointer<decltype(factory())>::type;
  10723. class FactoryImpl : public internal::TestFactoryBase {
  10724. public:
  10725. explicit FactoryImpl(Factory f) : factory_(std::move(f)) {}
  10726. Test* CreateTest() override { return factory_(); }
  10727. private:
  10728. Factory factory_;
  10729. };
  10730. return internal::MakeAndRegisterTestInfo(
  10731. test_suite_name, test_name, type_param, value_param,
  10732. internal::CodeLocation(file, line), internal::GetTypeId<TestT>(),
  10733. internal::SuiteApiResolver<TestT>::GetSetUpCaseOrSuite(file, line),
  10734. internal::SuiteApiResolver<TestT>::GetTearDownCaseOrSuite(file, line),
  10735. new FactoryImpl{std::move(factory)});
  10736. }
  10737. } // namespace testing
  10738. // Use this function in main() to run all tests. It returns 0 if all
  10739. // tests are successful, or 1 otherwise.
  10740. //
  10741. // RUN_ALL_TESTS() should be invoked after the command line has been
  10742. // parsed by InitGoogleTest().
  10743. //
  10744. // This function was formerly a macro; thus, it is in the global
  10745. // namespace and has an all-caps name.
  10746. int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
  10747. inline int RUN_ALL_TESTS() {
  10748. return ::testing::UnitTest::GetInstance()->Run();
  10749. }
  10750. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  10751. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_H_