gmock_gtest_all.cc 522 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463
  1. // Copyright 2008, 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. // Google C++ Testing and Mocking Framework (Google Test)
  31. //
  32. // Sometimes it's desirable to build Google Test by compiling a single file.
  33. // This file serves this purpose.
  34. // This line ensures that gtest.h can be compiled on its own, even
  35. // when it's fused.
  36. #include "gtest/gtest.h"
  37. // The following lines pull in the real gtest *.cc files.
  38. // Copyright 2005, Google Inc.
  39. // All rights reserved.
  40. //
  41. // Redistribution and use in source and binary forms, with or without
  42. // modification, are permitted provided that the following conditions are
  43. // met:
  44. //
  45. // * Redistributions of source code must retain the above copyright
  46. // notice, this list of conditions and the following disclaimer.
  47. // * Redistributions in binary form must reproduce the above
  48. // copyright notice, this list of conditions and the following disclaimer
  49. // in the documentation and/or other materials provided with the
  50. // distribution.
  51. // * Neither the name of Google Inc. nor the names of its
  52. // contributors may be used to endorse or promote products derived from
  53. // this software without specific prior written permission.
  54. //
  55. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  56. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  57. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  58. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  59. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  60. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  61. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  62. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  63. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  64. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  65. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  66. //
  67. // The Google C++ Testing and Mocking Framework (Google Test)
  68. // Copyright 2007, Google Inc.
  69. // All rights reserved.
  70. //
  71. // Redistribution and use in source and binary forms, with or without
  72. // modification, are permitted provided that the following conditions are
  73. // met:
  74. //
  75. // * Redistributions of source code must retain the above copyright
  76. // notice, this list of conditions and the following disclaimer.
  77. // * Redistributions in binary form must reproduce the above
  78. // copyright notice, this list of conditions and the following disclaimer
  79. // in the documentation and/or other materials provided with the
  80. // distribution.
  81. // * Neither the name of Google Inc. nor the names of its
  82. // contributors may be used to endorse or promote products derived from
  83. // this software without specific prior written permission.
  84. //
  85. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  86. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  87. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  88. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  89. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  90. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  91. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  92. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  93. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  94. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  95. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  96. //
  97. // Utilities for testing Google Test itself and code that uses Google Test
  98. // (e.g. frameworks built on top of Google Test).
  99. // GOOGLETEST_CM0004 DO NOT DELETE
  100. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
  101. #define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
  102. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  103. /* class A needs to have dll-interface to be used by clients of class B */)
  104. namespace testing {
  105. // This helper class can be used to mock out Google Test failure reporting
  106. // so that we can test Google Test or code that builds on Google Test.
  107. //
  108. // An object of this class appends a TestPartResult object to the
  109. // TestPartResultArray object given in the constructor whenever a Google Test
  110. // failure is reported. It can either intercept only failures that are
  111. // generated in the same thread that created this object or it can intercept
  112. // all generated failures. The scope of this mock object can be controlled with
  113. // the second argument to the two arguments constructor.
  114. class GTEST_API_ ScopedFakeTestPartResultReporter
  115. : public TestPartResultReporterInterface {
  116. public:
  117. // The two possible mocking modes of this object.
  118. enum InterceptMode {
  119. INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
  120. INTERCEPT_ALL_THREADS // Intercepts all failures.
  121. };
  122. // The c'tor sets this object as the test part result reporter used
  123. // by Google Test. The 'result' parameter specifies where to report the
  124. // results. This reporter will only catch failures generated in the current
  125. // thread. DEPRECATED
  126. explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
  127. // Same as above, but you can choose the interception scope of this object.
  128. ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
  129. TestPartResultArray* result);
  130. // The d'tor restores the previous test part result reporter.
  131. ~ScopedFakeTestPartResultReporter() override;
  132. // Appends the TestPartResult object to the TestPartResultArray
  133. // received in the constructor.
  134. //
  135. // This method is from the TestPartResultReporterInterface
  136. // interface.
  137. void ReportTestPartResult(const TestPartResult& result) override;
  138. private:
  139. void Init();
  140. const InterceptMode intercept_mode_;
  141. TestPartResultReporterInterface* old_reporter_;
  142. TestPartResultArray* const result_;
  143. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
  144. };
  145. namespace internal {
  146. // A helper class for implementing EXPECT_FATAL_FAILURE() and
  147. // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
  148. // TestPartResultArray contains exactly one failure that has the given
  149. // type and contains the given substring. If that's not the case, a
  150. // non-fatal failure will be generated.
  151. class GTEST_API_ SingleFailureChecker {
  152. public:
  153. // The constructor remembers the arguments.
  154. SingleFailureChecker(const TestPartResultArray* results,
  155. TestPartResult::Type type, const std::string& substr);
  156. ~SingleFailureChecker();
  157. private:
  158. const TestPartResultArray* const results_;
  159. const TestPartResult::Type type_;
  160. const std::string substr_;
  161. GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
  162. };
  163. } // namespace internal
  164. } // namespace testing
  165. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  166. // A set of macros for testing Google Test assertions or code that's expected
  167. // to generate Google Test fatal failures. It verifies that the given
  168. // statement will cause exactly one fatal Google Test failure with 'substr'
  169. // being part of the failure message.
  170. //
  171. // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
  172. // affects and considers failures generated in the current thread and
  173. // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
  174. //
  175. // The verification of the assertion is done correctly even when the statement
  176. // throws an exception or aborts the current function.
  177. //
  178. // Known restrictions:
  179. // - 'statement' cannot reference local non-static variables or
  180. // non-static members of the current object.
  181. // - 'statement' cannot return a value.
  182. // - You cannot stream a failure message to this macro.
  183. //
  184. // Note that even though the implementations of the following two
  185. // macros are much alike, we cannot refactor them to use a common
  186. // helper macro, due to some peculiarity in how the preprocessor
  187. // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
  188. // gtest_unittest.cc will fail to compile if we do that.
  189. #define EXPECT_FATAL_FAILURE(statement, substr) \
  190. do { \
  191. class GTestExpectFatalFailureHelper {\
  192. public:\
  193. static void Execute() { statement; }\
  194. };\
  195. ::testing::TestPartResultArray gtest_failures;\
  196. ::testing::internal::SingleFailureChecker gtest_checker(\
  197. &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
  198. {\
  199. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  200. ::testing::ScopedFakeTestPartResultReporter:: \
  201. INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
  202. GTestExpectFatalFailureHelper::Execute();\
  203. }\
  204. } while (::testing::internal::AlwaysFalse())
  205. #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
  206. do { \
  207. class GTestExpectFatalFailureHelper {\
  208. public:\
  209. static void Execute() { statement; }\
  210. };\
  211. ::testing::TestPartResultArray gtest_failures;\
  212. ::testing::internal::SingleFailureChecker gtest_checker(\
  213. &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
  214. {\
  215. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  216. ::testing::ScopedFakeTestPartResultReporter:: \
  217. INTERCEPT_ALL_THREADS, &gtest_failures);\
  218. GTestExpectFatalFailureHelper::Execute();\
  219. }\
  220. } while (::testing::internal::AlwaysFalse())
  221. // A macro for testing Google Test assertions or code that's expected to
  222. // generate Google Test non-fatal failures. It asserts that the given
  223. // statement will cause exactly one non-fatal Google Test failure with 'substr'
  224. // being part of the failure message.
  225. //
  226. // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
  227. // affects and considers failures generated in the current thread and
  228. // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
  229. //
  230. // 'statement' is allowed to reference local variables and members of
  231. // the current object.
  232. //
  233. // The verification of the assertion is done correctly even when the statement
  234. // throws an exception or aborts the current function.
  235. //
  236. // Known restrictions:
  237. // - You cannot stream a failure message to this macro.
  238. //
  239. // Note that even though the implementations of the following two
  240. // macros are much alike, we cannot refactor them to use a common
  241. // helper macro, due to some peculiarity in how the preprocessor
  242. // works. If we do that, the code won't compile when the user gives
  243. // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
  244. // expands to code containing an unprotected comma. The
  245. // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
  246. // catches that.
  247. //
  248. // For the same reason, we have to write
  249. // if (::testing::internal::AlwaysTrue()) { statement; }
  250. // instead of
  251. // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
  252. // to avoid an MSVC warning on unreachable code.
  253. #define EXPECT_NONFATAL_FAILURE(statement, substr) \
  254. do {\
  255. ::testing::TestPartResultArray gtest_failures;\
  256. ::testing::internal::SingleFailureChecker gtest_checker(\
  257. &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
  258. (substr));\
  259. {\
  260. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  261. ::testing::ScopedFakeTestPartResultReporter:: \
  262. INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
  263. if (::testing::internal::AlwaysTrue()) { statement; }\
  264. }\
  265. } while (::testing::internal::AlwaysFalse())
  266. #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
  267. do {\
  268. ::testing::TestPartResultArray gtest_failures;\
  269. ::testing::internal::SingleFailureChecker gtest_checker(\
  270. &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
  271. (substr));\
  272. {\
  273. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  274. ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
  275. &gtest_failures);\
  276. if (::testing::internal::AlwaysTrue()) { statement; }\
  277. }\
  278. } while (::testing::internal::AlwaysFalse())
  279. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
  280. #include <ctype.h>
  281. #include <stdarg.h>
  282. #include <stdio.h>
  283. #include <stdlib.h>
  284. #include <time.h>
  285. #include <wchar.h>
  286. #include <wctype.h>
  287. #include <algorithm>
  288. #include <chrono> // NOLINT
  289. #include <cmath>
  290. #include <cstdint>
  291. #include <iomanip>
  292. #include <limits>
  293. #include <list>
  294. #include <map>
  295. #include <ostream> // NOLINT
  296. #include <sstream>
  297. #include <vector>
  298. #if GTEST_OS_LINUX
  299. # include <fcntl.h> // NOLINT
  300. # include <limits.h> // NOLINT
  301. # include <sched.h> // NOLINT
  302. // Declares vsnprintf(). This header is not available on Windows.
  303. # include <strings.h> // NOLINT
  304. # include <sys/mman.h> // NOLINT
  305. # include <sys/time.h> // NOLINT
  306. # include <unistd.h> // NOLINT
  307. # include <string>
  308. #elif GTEST_OS_ZOS
  309. # include <sys/time.h> // NOLINT
  310. // On z/OS we additionally need strings.h for strcasecmp.
  311. # include <strings.h> // NOLINT
  312. #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
  313. # include <windows.h> // NOLINT
  314. # undef min
  315. #elif GTEST_OS_WINDOWS // We are on Windows proper.
  316. # include <windows.h> // NOLINT
  317. # undef min
  318. #ifdef _MSC_VER
  319. # include <crtdbg.h> // NOLINT
  320. #endif
  321. # include <io.h> // NOLINT
  322. # include <sys/timeb.h> // NOLINT
  323. # include <sys/types.h> // NOLINT
  324. # include <sys/stat.h> // NOLINT
  325. # if GTEST_OS_WINDOWS_MINGW
  326. # include <sys/time.h> // NOLINT
  327. # endif // GTEST_OS_WINDOWS_MINGW
  328. #else
  329. // cpplint thinks that the header is already included, so we want to
  330. // silence it.
  331. # include <sys/time.h> // NOLINT
  332. # include <unistd.h> // NOLINT
  333. #endif // GTEST_OS_LINUX
  334. #if GTEST_HAS_EXCEPTIONS
  335. # include <stdexcept>
  336. #endif
  337. #if GTEST_CAN_STREAM_RESULTS_
  338. # include <arpa/inet.h> // NOLINT
  339. # include <netdb.h> // NOLINT
  340. # include <sys/socket.h> // NOLINT
  341. # include <sys/types.h> // NOLINT
  342. #endif
  343. // Copyright 2005, Google Inc.
  344. // All rights reserved.
  345. //
  346. // Redistribution and use in source and binary forms, with or without
  347. // modification, are permitted provided that the following conditions are
  348. // met:
  349. //
  350. // * Redistributions of source code must retain the above copyright
  351. // notice, this list of conditions and the following disclaimer.
  352. // * Redistributions in binary form must reproduce the above
  353. // copyright notice, this list of conditions and the following disclaimer
  354. // in the documentation and/or other materials provided with the
  355. // distribution.
  356. // * Neither the name of Google Inc. nor the names of its
  357. // contributors may be used to endorse or promote products derived from
  358. // this software without specific prior written permission.
  359. //
  360. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  361. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  362. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  363. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  364. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  365. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  366. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  367. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  368. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  369. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  370. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  371. // Utility functions and classes used by the Google C++ testing framework.//
  372. // This file contains purely Google Test's internal implementation. Please
  373. // DO NOT #INCLUDE IT IN A USER PROGRAM.
  374. #ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
  375. #define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
  376. #ifndef _WIN32_WCE
  377. # include <errno.h>
  378. #endif // !_WIN32_WCE
  379. #include <stddef.h>
  380. #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
  381. #include <string.h> // For memmove.
  382. #include <algorithm>
  383. #include <cstdint>
  384. #include <memory>
  385. #include <string>
  386. #include <vector>
  387. #if GTEST_CAN_STREAM_RESULTS_
  388. # include <arpa/inet.h> // NOLINT
  389. # include <netdb.h> // NOLINT
  390. #endif
  391. #if GTEST_OS_WINDOWS
  392. # include <windows.h> // NOLINT
  393. #endif // GTEST_OS_WINDOWS
  394. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  395. /* class A needs to have dll-interface to be used by clients of class B */)
  396. namespace testing {
  397. // Declares the flags.
  398. //
  399. // We don't want the users to modify this flag in the code, but want
  400. // Google Test's own unit tests to be able to access it. Therefore we
  401. // declare it here as opposed to in gtest.h.
  402. GTEST_DECLARE_bool_(death_test_use_fork);
  403. namespace internal {
  404. // The value of GetTestTypeId() as seen from within the Google Test
  405. // library. This is solely for testing GetTestTypeId().
  406. GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
  407. // Names of the flags (needed for parsing Google Test flags).
  408. const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
  409. const char kBreakOnFailureFlag[] = "break_on_failure";
  410. const char kCatchExceptionsFlag[] = "catch_exceptions";
  411. const char kColorFlag[] = "color";
  412. const char kFailFast[] = "fail_fast";
  413. const char kFilterFlag[] = "filter";
  414. const char kListTestsFlag[] = "list_tests";
  415. const char kOutputFlag[] = "output";
  416. const char kBriefFlag[] = "brief";
  417. const char kPrintTimeFlag[] = "print_time";
  418. const char kPrintUTF8Flag[] = "print_utf8";
  419. const char kRandomSeedFlag[] = "random_seed";
  420. const char kRepeatFlag[] = "repeat";
  421. const char kShuffleFlag[] = "shuffle";
  422. const char kStackTraceDepthFlag[] = "stack_trace_depth";
  423. const char kStreamResultToFlag[] = "stream_result_to";
  424. const char kThrowOnFailureFlag[] = "throw_on_failure";
  425. const char kFlagfileFlag[] = "flagfile";
  426. // A valid random seed must be in [1, kMaxRandomSeed].
  427. const int kMaxRandomSeed = 99999;
  428. // g_help_flag is true if and only if the --help flag or an equivalent form
  429. // is specified on the command line.
  430. GTEST_API_ extern bool g_help_flag;
  431. // Returns the current time in milliseconds.
  432. GTEST_API_ TimeInMillis GetTimeInMillis();
  433. // Returns true if and only if Google Test should use colors in the output.
  434. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
  435. // Formats the given time in milliseconds as seconds.
  436. GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
  437. // Converts the given time in milliseconds to a date string in the ISO 8601
  438. // format, without the timezone information. N.B.: due to the use the
  439. // non-reentrant localtime() function, this function is not thread safe. Do
  440. // not use it in any code that can be called from multiple threads.
  441. GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
  442. // Parses a string for an Int32 flag, in the form of "--flag=value".
  443. //
  444. // On success, stores the value of the flag in *value, and returns
  445. // true. On failure, returns false without changing *value.
  446. GTEST_API_ bool ParseInt32Flag(
  447. const char* str, const char* flag, int32_t* value);
  448. // Returns a random seed in range [1, kMaxRandomSeed] based on the
  449. // given --gtest_random_seed flag value.
  450. inline int GetRandomSeedFromFlag(int32_t random_seed_flag) {
  451. const unsigned int raw_seed = (random_seed_flag == 0) ?
  452. static_cast<unsigned int>(GetTimeInMillis()) :
  453. static_cast<unsigned int>(random_seed_flag);
  454. // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
  455. // it's easy to type.
  456. const int normalized_seed =
  457. static_cast<int>((raw_seed - 1U) %
  458. static_cast<unsigned int>(kMaxRandomSeed)) + 1;
  459. return normalized_seed;
  460. }
  461. // Returns the first valid random seed after 'seed'. The behavior is
  462. // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
  463. // considered to be 1.
  464. inline int GetNextRandomSeed(int seed) {
  465. GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
  466. << "Invalid random seed " << seed << " - must be in [1, "
  467. << kMaxRandomSeed << "].";
  468. const int next_seed = seed + 1;
  469. return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
  470. }
  471. // This class saves the values of all Google Test flags in its c'tor, and
  472. // restores them in its d'tor.
  473. class GTestFlagSaver {
  474. public:
  475. // The c'tor.
  476. GTestFlagSaver() {
  477. also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
  478. break_on_failure_ = GTEST_FLAG(break_on_failure);
  479. catch_exceptions_ = GTEST_FLAG(catch_exceptions);
  480. color_ = GTEST_FLAG(color);
  481. death_test_style_ = GTEST_FLAG(death_test_style);
  482. death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
  483. fail_fast_ = GTEST_FLAG(fail_fast);
  484. filter_ = GTEST_FLAG(filter);
  485. internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
  486. list_tests_ = GTEST_FLAG(list_tests);
  487. output_ = GTEST_FLAG(output);
  488. brief_ = GTEST_FLAG(brief);
  489. print_time_ = GTEST_FLAG(print_time);
  490. print_utf8_ = GTEST_FLAG(print_utf8);
  491. random_seed_ = GTEST_FLAG(random_seed);
  492. repeat_ = GTEST_FLAG(repeat);
  493. shuffle_ = GTEST_FLAG(shuffle);
  494. stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
  495. stream_result_to_ = GTEST_FLAG(stream_result_to);
  496. throw_on_failure_ = GTEST_FLAG(throw_on_failure);
  497. }
  498. // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
  499. ~GTestFlagSaver() {
  500. GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
  501. GTEST_FLAG(break_on_failure) = break_on_failure_;
  502. GTEST_FLAG(catch_exceptions) = catch_exceptions_;
  503. GTEST_FLAG(color) = color_;
  504. GTEST_FLAG(death_test_style) = death_test_style_;
  505. GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
  506. GTEST_FLAG(filter) = filter_;
  507. GTEST_FLAG(fail_fast) = fail_fast_;
  508. GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
  509. GTEST_FLAG(list_tests) = list_tests_;
  510. GTEST_FLAG(output) = output_;
  511. GTEST_FLAG(brief) = brief_;
  512. GTEST_FLAG(print_time) = print_time_;
  513. GTEST_FLAG(print_utf8) = print_utf8_;
  514. GTEST_FLAG(random_seed) = random_seed_;
  515. GTEST_FLAG(repeat) = repeat_;
  516. GTEST_FLAG(shuffle) = shuffle_;
  517. GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
  518. GTEST_FLAG(stream_result_to) = stream_result_to_;
  519. GTEST_FLAG(throw_on_failure) = throw_on_failure_;
  520. }
  521. private:
  522. // Fields for saving the original values of flags.
  523. bool also_run_disabled_tests_;
  524. bool break_on_failure_;
  525. bool catch_exceptions_;
  526. std::string color_;
  527. std::string death_test_style_;
  528. bool death_test_use_fork_;
  529. bool fail_fast_;
  530. std::string filter_;
  531. std::string internal_run_death_test_;
  532. bool list_tests_;
  533. std::string output_;
  534. bool brief_;
  535. bool print_time_;
  536. bool print_utf8_;
  537. int32_t random_seed_;
  538. int32_t repeat_;
  539. bool shuffle_;
  540. int32_t stack_trace_depth_;
  541. std::string stream_result_to_;
  542. bool throw_on_failure_;
  543. } GTEST_ATTRIBUTE_UNUSED_;
  544. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  545. // code_point parameter is of type UInt32 because wchar_t may not be
  546. // wide enough to contain a code point.
  547. // If the code_point is not a valid Unicode code point
  548. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  549. // to "(Invalid Unicode 0xXXXXXXXX)".
  550. GTEST_API_ std::string CodePointToUtf8(uint32_t code_point);
  551. // Converts a wide string to a narrow string in UTF-8 encoding.
  552. // The wide string is assumed to have the following encoding:
  553. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
  554. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  555. // Parameter str points to a null-terminated wide string.
  556. // Parameter num_chars may additionally limit the number
  557. // of wchar_t characters processed. -1 is used when the entire string
  558. // should be processed.
  559. // If the string contains code points that are not valid Unicode code points
  560. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  561. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  562. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  563. // will be encoded as individual Unicode characters from Basic Normal Plane.
  564. GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
  565. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  566. // if the variable is present. If a file already exists at this location, this
  567. // function will write over it. If the variable is present, but the file cannot
  568. // be created, prints an error and exits.
  569. void WriteToShardStatusFileIfNeeded();
  570. // Checks whether sharding is enabled by examining the relevant
  571. // environment variable values. If the variables are present,
  572. // but inconsistent (e.g., shard_index >= total_shards), prints
  573. // an error and exits. If in_subprocess_for_death_test, sharding is
  574. // disabled because it must only be applied to the original test
  575. // process. Otherwise, we could filter out death tests we intended to execute.
  576. GTEST_API_ bool ShouldShard(const char* total_shards_str,
  577. const char* shard_index_str,
  578. bool in_subprocess_for_death_test);
  579. // Parses the environment variable var as a 32-bit integer. If it is unset,
  580. // returns default_val. If it is not a 32-bit integer, prints an error and
  581. // and aborts.
  582. GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);
  583. // Given the total number of shards, the shard index, and the test id,
  584. // returns true if and only if the test should be run on this shard. The test id
  585. // is some arbitrary but unique non-negative integer assigned to each test
  586. // method. Assumes that 0 <= shard_index < total_shards.
  587. GTEST_API_ bool ShouldRunTestOnShard(
  588. int total_shards, int shard_index, int test_id);
  589. // STL container utilities.
  590. // Returns the number of elements in the given container that satisfy
  591. // the given predicate.
  592. template <class Container, typename Predicate>
  593. inline int CountIf(const Container& c, Predicate predicate) {
  594. // Implemented as an explicit loop since std::count_if() in libCstd on
  595. // Solaris has a non-standard signature.
  596. int count = 0;
  597. for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
  598. if (predicate(*it))
  599. ++count;
  600. }
  601. return count;
  602. }
  603. // Applies a function/functor to each element in the container.
  604. template <class Container, typename Functor>
  605. void ForEach(const Container& c, Functor functor) {
  606. std::for_each(c.begin(), c.end(), functor);
  607. }
  608. // Returns the i-th element of the vector, or default_value if i is not
  609. // in range [0, v.size()).
  610. template <typename E>
  611. inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
  612. return (i < 0 || i >= static_cast<int>(v.size())) ? default_value
  613. : v[static_cast<size_t>(i)];
  614. }
  615. // Performs an in-place shuffle of a range of the vector's elements.
  616. // 'begin' and 'end' are element indices as an STL-style range;
  617. // i.e. [begin, end) are shuffled, where 'end' == size() means to
  618. // shuffle to the end of the vector.
  619. template <typename E>
  620. void ShuffleRange(internal::Random* random, int begin, int end,
  621. std::vector<E>* v) {
  622. const int size = static_cast<int>(v->size());
  623. GTEST_CHECK_(0 <= begin && begin <= size)
  624. << "Invalid shuffle range start " << begin << ": must be in range [0, "
  625. << size << "].";
  626. GTEST_CHECK_(begin <= end && end <= size)
  627. << "Invalid shuffle range finish " << end << ": must be in range ["
  628. << begin << ", " << size << "].";
  629. // Fisher-Yates shuffle, from
  630. // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  631. for (int range_width = end - begin; range_width >= 2; range_width--) {
  632. const int last_in_range = begin + range_width - 1;
  633. const int selected =
  634. begin +
  635. static_cast<int>(random->Generate(static_cast<uint32_t>(range_width)));
  636. std::swap((*v)[static_cast<size_t>(selected)],
  637. (*v)[static_cast<size_t>(last_in_range)]);
  638. }
  639. }
  640. // Performs an in-place shuffle of the vector's elements.
  641. template <typename E>
  642. inline void Shuffle(internal::Random* random, std::vector<E>* v) {
  643. ShuffleRange(random, 0, static_cast<int>(v->size()), v);
  644. }
  645. // A function for deleting an object. Handy for being used as a
  646. // functor.
  647. template <typename T>
  648. static void Delete(T* x) {
  649. delete x;
  650. }
  651. // A predicate that checks the key of a TestProperty against a known key.
  652. //
  653. // TestPropertyKeyIs is copyable.
  654. class TestPropertyKeyIs {
  655. public:
  656. // Constructor.
  657. //
  658. // TestPropertyKeyIs has NO default constructor.
  659. explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
  660. // Returns true if and only if the test name of test property matches on key_.
  661. bool operator()(const TestProperty& test_property) const {
  662. return test_property.key() == key_;
  663. }
  664. private:
  665. std::string key_;
  666. };
  667. // Class UnitTestOptions.
  668. //
  669. // This class contains functions for processing options the user
  670. // specifies when running the tests. It has only static members.
  671. //
  672. // In most cases, the user can specify an option using either an
  673. // environment variable or a command line flag. E.g. you can set the
  674. // test filter using either GTEST_FILTER or --gtest_filter. If both
  675. // the variable and the flag are present, the latter overrides the
  676. // former.
  677. class GTEST_API_ UnitTestOptions {
  678. public:
  679. // Functions for processing the gtest_output flag.
  680. // Returns the output format, or "" for normal printed output.
  681. static std::string GetOutputFormat();
  682. // Returns the absolute path of the requested output file, or the
  683. // default (test_detail.xml in the original working directory) if
  684. // none was explicitly specified.
  685. static std::string GetAbsolutePathToOutputFile();
  686. // Functions for processing the gtest_filter flag.
  687. // Returns true if and only if the user-specified filter matches the test
  688. // suite name and the test name.
  689. static bool FilterMatchesTest(const std::string& test_suite_name,
  690. const std::string& test_name);
  691. #if GTEST_OS_WINDOWS
  692. // Function for supporting the gtest_catch_exception flag.
  693. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  694. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  695. // This function is useful as an __except condition.
  696. static int GTestShouldProcessSEH(DWORD exception_code);
  697. #endif // GTEST_OS_WINDOWS
  698. // Returns true if "name" matches the ':' separated list of glob-style
  699. // filters in "filter".
  700. static bool MatchesFilter(const std::string& name, const char* filter);
  701. };
  702. // Returns the current application's name, removing directory path if that
  703. // is present. Used by UnitTestOptions::GetOutputFile.
  704. GTEST_API_ FilePath GetCurrentExecutableName();
  705. // The role interface for getting the OS stack trace as a string.
  706. class OsStackTraceGetterInterface {
  707. public:
  708. OsStackTraceGetterInterface() {}
  709. virtual ~OsStackTraceGetterInterface() {}
  710. // Returns the current OS stack trace as an std::string. Parameters:
  711. //
  712. // max_depth - the maximum number of stack frames to be included
  713. // in the trace.
  714. // skip_count - the number of top frames to be skipped; doesn't count
  715. // against max_depth.
  716. virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
  717. // UponLeavingGTest() should be called immediately before Google Test calls
  718. // user code. It saves some information about the current stack that
  719. // CurrentStackTrace() will use to find and hide Google Test stack frames.
  720. virtual void UponLeavingGTest() = 0;
  721. // This string is inserted in place of stack frames that are part of
  722. // Google Test's implementation.
  723. static const char* const kElidedFramesMarker;
  724. private:
  725. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
  726. };
  727. // A working implementation of the OsStackTraceGetterInterface interface.
  728. class OsStackTraceGetter : public OsStackTraceGetterInterface {
  729. public:
  730. OsStackTraceGetter() {}
  731. std::string CurrentStackTrace(int max_depth, int skip_count) override;
  732. void UponLeavingGTest() override;
  733. private:
  734. #if GTEST_HAS_ABSL
  735. Mutex mutex_; // Protects all internal state.
  736. // We save the stack frame below the frame that calls user code.
  737. // We do this because the address of the frame immediately below
  738. // the user code changes between the call to UponLeavingGTest()
  739. // and any calls to the stack trace code from within the user code.
  740. void* caller_frame_ = nullptr;
  741. #endif // GTEST_HAS_ABSL
  742. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
  743. };
  744. // Information about a Google Test trace point.
  745. struct TraceInfo {
  746. const char* file;
  747. int line;
  748. std::string message;
  749. };
  750. // This is the default global test part result reporter used in UnitTestImpl.
  751. // This class should only be used by UnitTestImpl.
  752. class DefaultGlobalTestPartResultReporter
  753. : public TestPartResultReporterInterface {
  754. public:
  755. explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
  756. // Implements the TestPartResultReporterInterface. Reports the test part
  757. // result in the current test.
  758. void ReportTestPartResult(const TestPartResult& result) override;
  759. private:
  760. UnitTestImpl* const unit_test_;
  761. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
  762. };
  763. // This is the default per thread test part result reporter used in
  764. // UnitTestImpl. This class should only be used by UnitTestImpl.
  765. class DefaultPerThreadTestPartResultReporter
  766. : public TestPartResultReporterInterface {
  767. public:
  768. explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
  769. // Implements the TestPartResultReporterInterface. The implementation just
  770. // delegates to the current global test part result reporter of *unit_test_.
  771. void ReportTestPartResult(const TestPartResult& result) override;
  772. private:
  773. UnitTestImpl* const unit_test_;
  774. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
  775. };
  776. // The private implementation of the UnitTest class. We don't protect
  777. // the methods under a mutex, as this class is not accessible by a
  778. // user and the UnitTest class that delegates work to this class does
  779. // proper locking.
  780. class GTEST_API_ UnitTestImpl {
  781. public:
  782. explicit UnitTestImpl(UnitTest* parent);
  783. virtual ~UnitTestImpl();
  784. // There are two different ways to register your own TestPartResultReporter.
  785. // You can register your own repoter to listen either only for test results
  786. // from the current thread or for results from all threads.
  787. // By default, each per-thread test result repoter just passes a new
  788. // TestPartResult to the global test result reporter, which registers the
  789. // test part result for the currently running test.
  790. // Returns the global test part result reporter.
  791. TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
  792. // Sets the global test part result reporter.
  793. void SetGlobalTestPartResultReporter(
  794. TestPartResultReporterInterface* reporter);
  795. // Returns the test part result reporter for the current thread.
  796. TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
  797. // Sets the test part result reporter for the current thread.
  798. void SetTestPartResultReporterForCurrentThread(
  799. TestPartResultReporterInterface* reporter);
  800. // Gets the number of successful test suites.
  801. int successful_test_suite_count() const;
  802. // Gets the number of failed test suites.
  803. int failed_test_suite_count() const;
  804. // Gets the number of all test suites.
  805. int total_test_suite_count() const;
  806. // Gets the number of all test suites that contain at least one test
  807. // that should run.
  808. int test_suite_to_run_count() const;
  809. // Gets the number of successful tests.
  810. int successful_test_count() const;
  811. // Gets the number of skipped tests.
  812. int skipped_test_count() const;
  813. // Gets the number of failed tests.
  814. int failed_test_count() const;
  815. // Gets the number of disabled tests that will be reported in the XML report.
  816. int reportable_disabled_test_count() const;
  817. // Gets the number of disabled tests.
  818. int disabled_test_count() const;
  819. // Gets the number of tests to be printed in the XML report.
  820. int reportable_test_count() const;
  821. // Gets the number of all tests.
  822. int total_test_count() const;
  823. // Gets the number of tests that should run.
  824. int test_to_run_count() const;
  825. // Gets the time of the test program start, in ms from the start of the
  826. // UNIX epoch.
  827. TimeInMillis start_timestamp() const { return start_timestamp_; }
  828. // Gets the elapsed time, in milliseconds.
  829. TimeInMillis elapsed_time() const { return elapsed_time_; }
  830. // Returns true if and only if the unit test passed (i.e. all test suites
  831. // passed).
  832. bool Passed() const { return !Failed(); }
  833. // Returns true if and only if the unit test failed (i.e. some test suite
  834. // failed or something outside of all tests failed).
  835. bool Failed() const {
  836. return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();
  837. }
  838. // Gets the i-th test suite among all the test suites. i can range from 0 to
  839. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  840. const TestSuite* GetTestSuite(int i) const {
  841. const int index = GetElementOr(test_suite_indices_, i, -1);
  842. return index < 0 ? nullptr : test_suites_[static_cast<size_t>(i)];
  843. }
  844. // Legacy API is deprecated but still available
  845. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  846. const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }
  847. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  848. // Gets the i-th test suite among all the test suites. i can range from 0 to
  849. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  850. TestSuite* GetMutableSuiteCase(int i) {
  851. const int index = GetElementOr(test_suite_indices_, i, -1);
  852. return index < 0 ? nullptr : test_suites_[static_cast<size_t>(index)];
  853. }
  854. // Provides access to the event listener list.
  855. TestEventListeners* listeners() { return &listeners_; }
  856. // Returns the TestResult for the test that's currently running, or
  857. // the TestResult for the ad hoc test if no test is running.
  858. TestResult* current_test_result();
  859. // Returns the TestResult for the ad hoc test.
  860. const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
  861. // Sets the OS stack trace getter.
  862. //
  863. // Does nothing if the input and the current OS stack trace getter
  864. // are the same; otherwise, deletes the old getter and makes the
  865. // input the current getter.
  866. void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
  867. // Returns the current OS stack trace getter if it is not NULL;
  868. // otherwise, creates an OsStackTraceGetter, makes it the current
  869. // getter, and returns it.
  870. OsStackTraceGetterInterface* os_stack_trace_getter();
  871. // Returns the current OS stack trace as an std::string.
  872. //
  873. // The maximum number of stack frames to be included is specified by
  874. // the gtest_stack_trace_depth flag. The skip_count parameter
  875. // specifies the number of top frames to be skipped, which doesn't
  876. // count against the number of frames to be included.
  877. //
  878. // For example, if Foo() calls Bar(), which in turn calls
  879. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  880. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  881. std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
  882. // Finds and returns a TestSuite with the given name. If one doesn't
  883. // exist, creates one and returns it.
  884. //
  885. // Arguments:
  886. //
  887. // test_suite_name: name of the test suite
  888. // type_param: the name of the test's type parameter, or NULL if
  889. // this is not a typed or a type-parameterized test.
  890. // set_up_tc: pointer to the function that sets up the test suite
  891. // tear_down_tc: pointer to the function that tears down the test suite
  892. TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,
  893. internal::SetUpTestSuiteFunc set_up_tc,
  894. internal::TearDownTestSuiteFunc tear_down_tc);
  895. // Legacy API is deprecated but still available
  896. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  897. TestCase* GetTestCase(const char* test_case_name, const char* type_param,
  898. internal::SetUpTestSuiteFunc set_up_tc,
  899. internal::TearDownTestSuiteFunc tear_down_tc) {
  900. return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);
  901. }
  902. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  903. // Adds a TestInfo to the unit test.
  904. //
  905. // Arguments:
  906. //
  907. // set_up_tc: pointer to the function that sets up the test suite
  908. // tear_down_tc: pointer to the function that tears down the test suite
  909. // test_info: the TestInfo object
  910. void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
  911. internal::TearDownTestSuiteFunc tear_down_tc,
  912. TestInfo* test_info) {
  913. #if GTEST_HAS_DEATH_TEST
  914. // In order to support thread-safe death tests, we need to
  915. // remember the original working directory when the test program
  916. // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
  917. // the user may have changed the current directory before calling
  918. // RUN_ALL_TESTS(). Therefore we capture the current directory in
  919. // AddTestInfo(), which is called to register a TEST or TEST_F
  920. // before main() is reached.
  921. if (original_working_dir_.IsEmpty()) {
  922. original_working_dir_.Set(FilePath::GetCurrentDir());
  923. GTEST_CHECK_(!original_working_dir_.IsEmpty())
  924. << "Failed to get the current working directory.";
  925. }
  926. #endif // GTEST_HAS_DEATH_TEST
  927. GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
  928. set_up_tc, tear_down_tc)
  929. ->AddTestInfo(test_info);
  930. }
  931. // Returns ParameterizedTestSuiteRegistry object used to keep track of
  932. // value-parameterized tests and instantiate and register them.
  933. internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {
  934. return parameterized_test_registry_;
  935. }
  936. std::set<std::string>* ignored_parameterized_test_suites() {
  937. return &ignored_parameterized_test_suites_;
  938. }
  939. // Returns TypeParameterizedTestSuiteRegistry object used to keep track of
  940. // type-parameterized tests and instantiations of them.
  941. internal::TypeParameterizedTestSuiteRegistry&
  942. type_parameterized_test_registry() {
  943. return type_parameterized_test_registry_;
  944. }
  945. // Sets the TestSuite object for the test that's currently running.
  946. void set_current_test_suite(TestSuite* a_current_test_suite) {
  947. current_test_suite_ = a_current_test_suite;
  948. }
  949. // Sets the TestInfo object for the test that's currently running. If
  950. // current_test_info is NULL, the assertion results will be stored in
  951. // ad_hoc_test_result_.
  952. void set_current_test_info(TestInfo* a_current_test_info) {
  953. current_test_info_ = a_current_test_info;
  954. }
  955. // Registers all parameterized tests defined using TEST_P and
  956. // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter
  957. // combination. This method can be called more then once; it has guards
  958. // protecting from registering the tests more then once. If
  959. // value-parameterized tests are disabled, RegisterParameterizedTests is
  960. // present but does nothing.
  961. void RegisterParameterizedTests();
  962. // Runs all tests in this UnitTest object, prints the result, and
  963. // returns true if all tests are successful. If any exception is
  964. // thrown during a test, this test is considered to be failed, but
  965. // the rest of the tests will still be run.
  966. bool RunAllTests();
  967. // Clears the results of all tests, except the ad hoc tests.
  968. void ClearNonAdHocTestResult() {
  969. ForEach(test_suites_, TestSuite::ClearTestSuiteResult);
  970. }
  971. // Clears the results of ad-hoc test assertions.
  972. void ClearAdHocTestResult() {
  973. ad_hoc_test_result_.Clear();
  974. }
  975. // Adds a TestProperty to the current TestResult object when invoked in a
  976. // context of a test or a test suite, or to the global property set. If the
  977. // result already contains a property with the same key, the value will be
  978. // updated.
  979. void RecordProperty(const TestProperty& test_property);
  980. enum ReactionToSharding {
  981. HONOR_SHARDING_PROTOCOL,
  982. IGNORE_SHARDING_PROTOCOL
  983. };
  984. // Matches the full name of each test against the user-specified
  985. // filter to decide whether the test should run, then records the
  986. // result in each TestSuite and TestInfo object.
  987. // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
  988. // based on sharding variables in the environment.
  989. // Returns the number of tests that should run.
  990. int FilterTests(ReactionToSharding shard_tests);
  991. // Prints the names of the tests matching the user-specified filter flag.
  992. void ListTestsMatchingFilter();
  993. const TestSuite* current_test_suite() const { return current_test_suite_; }
  994. TestInfo* current_test_info() { return current_test_info_; }
  995. const TestInfo* current_test_info() const { return current_test_info_; }
  996. // Returns the vector of environments that need to be set-up/torn-down
  997. // before/after the tests are run.
  998. std::vector<Environment*>& environments() { return environments_; }
  999. // Getters for the per-thread Google Test trace stack.
  1000. std::vector<TraceInfo>& gtest_trace_stack() {
  1001. return *(gtest_trace_stack_.pointer());
  1002. }
  1003. const std::vector<TraceInfo>& gtest_trace_stack() const {
  1004. return gtest_trace_stack_.get();
  1005. }
  1006. #if GTEST_HAS_DEATH_TEST
  1007. void InitDeathTestSubprocessControlInfo() {
  1008. internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
  1009. }
  1010. // Returns a pointer to the parsed --gtest_internal_run_death_test
  1011. // flag, or NULL if that flag was not specified.
  1012. // This information is useful only in a death test child process.
  1013. // Must not be called before a call to InitGoogleTest.
  1014. const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
  1015. return internal_run_death_test_flag_.get();
  1016. }
  1017. // Returns a pointer to the current death test factory.
  1018. internal::DeathTestFactory* death_test_factory() {
  1019. return death_test_factory_.get();
  1020. }
  1021. void SuppressTestEventsIfInSubprocess();
  1022. friend class ReplaceDeathTestFactory;
  1023. #endif // GTEST_HAS_DEATH_TEST
  1024. // Initializes the event listener performing XML output as specified by
  1025. // UnitTestOptions. Must not be called before InitGoogleTest.
  1026. void ConfigureXmlOutput();
  1027. #if GTEST_CAN_STREAM_RESULTS_
  1028. // Initializes the event listener for streaming test results to a socket.
  1029. // Must not be called before InitGoogleTest.
  1030. void ConfigureStreamingOutput();
  1031. #endif
  1032. // Performs initialization dependent upon flag values obtained in
  1033. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  1034. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  1035. // this function is also called from RunAllTests. Since this function can be
  1036. // called more than once, it has to be idempotent.
  1037. void PostFlagParsingInit();
  1038. // Gets the random seed used at the start of the current test iteration.
  1039. int random_seed() const { return random_seed_; }
  1040. // Gets the random number generator.
  1041. internal::Random* random() { return &random_; }
  1042. // Shuffles all test suites, and the tests within each test suite,
  1043. // making sure that death tests are still run first.
  1044. void ShuffleTests();
  1045. // Restores the test suites and tests to their order before the first shuffle.
  1046. void UnshuffleTests();
  1047. // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
  1048. // UnitTest::Run() starts.
  1049. bool catch_exceptions() const { return catch_exceptions_; }
  1050. private:
  1051. friend class ::testing::UnitTest;
  1052. // Used by UnitTest::Run() to capture the state of
  1053. // GTEST_FLAG(catch_exceptions) at the moment it starts.
  1054. void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
  1055. // The UnitTest object that owns this implementation object.
  1056. UnitTest* const parent_;
  1057. // The working directory when the first TEST() or TEST_F() was
  1058. // executed.
  1059. internal::FilePath original_working_dir_;
  1060. // The default test part result reporters.
  1061. DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
  1062. DefaultPerThreadTestPartResultReporter
  1063. default_per_thread_test_part_result_reporter_;
  1064. // Points to (but doesn't own) the global test part result reporter.
  1065. TestPartResultReporterInterface* global_test_part_result_repoter_;
  1066. // Protects read and write access to global_test_part_result_reporter_.
  1067. internal::Mutex global_test_part_result_reporter_mutex_;
  1068. // Points to (but doesn't own) the per-thread test part result reporter.
  1069. internal::ThreadLocal<TestPartResultReporterInterface*>
  1070. per_thread_test_part_result_reporter_;
  1071. // The vector of environments that need to be set-up/torn-down
  1072. // before/after the tests are run.
  1073. std::vector<Environment*> environments_;
  1074. // The vector of TestSuites in their original order. It owns the
  1075. // elements in the vector.
  1076. std::vector<TestSuite*> test_suites_;
  1077. // Provides a level of indirection for the test suite list to allow
  1078. // easy shuffling and restoring the test suite order. The i-th
  1079. // element of this vector is the index of the i-th test suite in the
  1080. // shuffled order.
  1081. std::vector<int> test_suite_indices_;
  1082. // ParameterizedTestRegistry object used to register value-parameterized
  1083. // tests.
  1084. internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
  1085. internal::TypeParameterizedTestSuiteRegistry
  1086. type_parameterized_test_registry_;
  1087. // The set holding the name of parameterized
  1088. // test suites that may go uninstantiated.
  1089. std::set<std::string> ignored_parameterized_test_suites_;
  1090. // Indicates whether RegisterParameterizedTests() has been called already.
  1091. bool parameterized_tests_registered_;
  1092. // Index of the last death test suite registered. Initially -1.
  1093. int last_death_test_suite_;
  1094. // This points to the TestSuite for the currently running test. It
  1095. // changes as Google Test goes through one test suite after another.
  1096. // When no test is running, this is set to NULL and Google Test
  1097. // stores assertion results in ad_hoc_test_result_. Initially NULL.
  1098. TestSuite* current_test_suite_;
  1099. // This points to the TestInfo for the currently running test. It
  1100. // changes as Google Test goes through one test after another. When
  1101. // no test is running, this is set to NULL and Google Test stores
  1102. // assertion results in ad_hoc_test_result_. Initially NULL.
  1103. TestInfo* current_test_info_;
  1104. // Normally, a user only writes assertions inside a TEST or TEST_F,
  1105. // or inside a function called by a TEST or TEST_F. Since Google
  1106. // Test keeps track of which test is current running, it can
  1107. // associate such an assertion with the test it belongs to.
  1108. //
  1109. // If an assertion is encountered when no TEST or TEST_F is running,
  1110. // Google Test attributes the assertion result to an imaginary "ad hoc"
  1111. // test, and records the result in ad_hoc_test_result_.
  1112. TestResult ad_hoc_test_result_;
  1113. // The list of event listeners that can be used to track events inside
  1114. // Google Test.
  1115. TestEventListeners listeners_;
  1116. // The OS stack trace getter. Will be deleted when the UnitTest
  1117. // object is destructed. By default, an OsStackTraceGetter is used,
  1118. // but the user can set this field to use a custom getter if that is
  1119. // desired.
  1120. OsStackTraceGetterInterface* os_stack_trace_getter_;
  1121. // True if and only if PostFlagParsingInit() has been called.
  1122. bool post_flag_parse_init_performed_;
  1123. // The random number seed used at the beginning of the test run.
  1124. int random_seed_;
  1125. // Our random number generator.
  1126. internal::Random random_;
  1127. // The time of the test program start, in ms from the start of the
  1128. // UNIX epoch.
  1129. TimeInMillis start_timestamp_;
  1130. // How long the test took to run, in milliseconds.
  1131. TimeInMillis elapsed_time_;
  1132. #if GTEST_HAS_DEATH_TEST
  1133. // The decomposed components of the gtest_internal_run_death_test flag,
  1134. // parsed when RUN_ALL_TESTS is called.
  1135. std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
  1136. std::unique_ptr<internal::DeathTestFactory> death_test_factory_;
  1137. #endif // GTEST_HAS_DEATH_TEST
  1138. // A per-thread stack of traces created by the SCOPED_TRACE() macro.
  1139. internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
  1140. // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
  1141. // starts.
  1142. bool catch_exceptions_;
  1143. GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
  1144. }; // class UnitTestImpl
  1145. // Convenience function for accessing the global UnitTest
  1146. // implementation object.
  1147. inline UnitTestImpl* GetUnitTestImpl() {
  1148. return UnitTest::GetInstance()->impl();
  1149. }
  1150. #if GTEST_USES_SIMPLE_RE
  1151. // Internal helper functions for implementing the simple regular
  1152. // expression matcher.
  1153. GTEST_API_ bool IsInSet(char ch, const char* str);
  1154. GTEST_API_ bool IsAsciiDigit(char ch);
  1155. GTEST_API_ bool IsAsciiPunct(char ch);
  1156. GTEST_API_ bool IsRepeat(char ch);
  1157. GTEST_API_ bool IsAsciiWhiteSpace(char ch);
  1158. GTEST_API_ bool IsAsciiWordChar(char ch);
  1159. GTEST_API_ bool IsValidEscape(char ch);
  1160. GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
  1161. GTEST_API_ bool ValidateRegex(const char* regex);
  1162. GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
  1163. GTEST_API_ bool MatchRepetitionAndRegexAtHead(
  1164. bool escaped, char ch, char repeat, const char* regex, const char* str);
  1165. GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
  1166. #endif // GTEST_USES_SIMPLE_RE
  1167. // Parses the command line for Google Test flags, without initializing
  1168. // other parts of Google Test.
  1169. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
  1170. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
  1171. #if GTEST_HAS_DEATH_TEST
  1172. // Returns the message describing the last system error, regardless of the
  1173. // platform.
  1174. GTEST_API_ std::string GetLastErrnoDescription();
  1175. // Attempts to parse a string into a positive integer pointed to by the
  1176. // number parameter. Returns true if that is possible.
  1177. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
  1178. // it here.
  1179. template <typename Integer>
  1180. bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
  1181. // Fail fast if the given string does not begin with a digit;
  1182. // this bypasses strtoXXX's "optional leading whitespace and plus
  1183. // or minus sign" semantics, which are undesirable here.
  1184. if (str.empty() || !IsDigit(str[0])) {
  1185. return false;
  1186. }
  1187. errno = 0;
  1188. char* end;
  1189. // BiggestConvertible is the largest integer type that system-provided
  1190. // string-to-number conversion routines can return.
  1191. using BiggestConvertible = unsigned long long; // NOLINT
  1192. const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); // NOLINT
  1193. const bool parse_success = *end == '\0' && errno == 0;
  1194. GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
  1195. const Integer result = static_cast<Integer>(parsed);
  1196. if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
  1197. *number = result;
  1198. return true;
  1199. }
  1200. return false;
  1201. }
  1202. #endif // GTEST_HAS_DEATH_TEST
  1203. // TestResult contains some private methods that should be hidden from
  1204. // Google Test user but are required for testing. This class allow our tests
  1205. // to access them.
  1206. //
  1207. // This class is supplied only for the purpose of testing Google Test's own
  1208. // constructs. Do not use it in user tests, either directly or indirectly.
  1209. class TestResultAccessor {
  1210. public:
  1211. static void RecordProperty(TestResult* test_result,
  1212. const std::string& xml_element,
  1213. const TestProperty& property) {
  1214. test_result->RecordProperty(xml_element, property);
  1215. }
  1216. static void ClearTestPartResults(TestResult* test_result) {
  1217. test_result->ClearTestPartResults();
  1218. }
  1219. static const std::vector<testing::TestPartResult>& test_part_results(
  1220. const TestResult& test_result) {
  1221. return test_result.test_part_results();
  1222. }
  1223. };
  1224. #if GTEST_CAN_STREAM_RESULTS_
  1225. // Streams test results to the given port on the given host machine.
  1226. class StreamingListener : public EmptyTestEventListener {
  1227. public:
  1228. // Abstract base class for writing strings to a socket.
  1229. class AbstractSocketWriter {
  1230. public:
  1231. virtual ~AbstractSocketWriter() {}
  1232. // Sends a string to the socket.
  1233. virtual void Send(const std::string& message) = 0;
  1234. // Closes the socket.
  1235. virtual void CloseConnection() {}
  1236. // Sends a string and a newline to the socket.
  1237. void SendLn(const std::string& message) { Send(message + "\n"); }
  1238. };
  1239. // Concrete class for actually writing strings to a socket.
  1240. class SocketWriter : public AbstractSocketWriter {
  1241. public:
  1242. SocketWriter(const std::string& host, const std::string& port)
  1243. : sockfd_(-1), host_name_(host), port_num_(port) {
  1244. MakeConnection();
  1245. }
  1246. ~SocketWriter() override {
  1247. if (sockfd_ != -1)
  1248. CloseConnection();
  1249. }
  1250. // Sends a string to the socket.
  1251. void Send(const std::string& message) override {
  1252. GTEST_CHECK_(sockfd_ != -1)
  1253. << "Send() can be called only when there is a connection.";
  1254. const auto len = static_cast<size_t>(message.length());
  1255. if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {
  1256. GTEST_LOG_(WARNING)
  1257. << "stream_result_to: failed to stream to "
  1258. << host_name_ << ":" << port_num_;
  1259. }
  1260. }
  1261. private:
  1262. // Creates a client socket and connects to the server.
  1263. void MakeConnection();
  1264. // Closes the socket.
  1265. void CloseConnection() override {
  1266. GTEST_CHECK_(sockfd_ != -1)
  1267. << "CloseConnection() can be called only when there is a connection.";
  1268. close(sockfd_);
  1269. sockfd_ = -1;
  1270. }
  1271. int sockfd_; // socket file descriptor
  1272. const std::string host_name_;
  1273. const std::string port_num_;
  1274. GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
  1275. }; // class SocketWriter
  1276. // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
  1277. static std::string UrlEncode(const char* str);
  1278. StreamingListener(const std::string& host, const std::string& port)
  1279. : socket_writer_(new SocketWriter(host, port)) {
  1280. Start();
  1281. }
  1282. explicit StreamingListener(AbstractSocketWriter* socket_writer)
  1283. : socket_writer_(socket_writer) { Start(); }
  1284. void OnTestProgramStart(const UnitTest& /* unit_test */) override {
  1285. SendLn("event=TestProgramStart");
  1286. }
  1287. void OnTestProgramEnd(const UnitTest& unit_test) override {
  1288. // Note that Google Test current only report elapsed time for each
  1289. // test iteration, not for the entire test program.
  1290. SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
  1291. // Notify the streaming server to stop.
  1292. socket_writer_->CloseConnection();
  1293. }
  1294. void OnTestIterationStart(const UnitTest& /* unit_test */,
  1295. int iteration) override {
  1296. SendLn("event=TestIterationStart&iteration=" +
  1297. StreamableToString(iteration));
  1298. }
  1299. void OnTestIterationEnd(const UnitTest& unit_test,
  1300. int /* iteration */) override {
  1301. SendLn("event=TestIterationEnd&passed=" +
  1302. FormatBool(unit_test.Passed()) + "&elapsed_time=" +
  1303. StreamableToString(unit_test.elapsed_time()) + "ms");
  1304. }
  1305. // Note that "event=TestCaseStart" is a wire format and has to remain
  1306. // "case" for compatibility
  1307. void OnTestCaseStart(const TestCase& test_case) override {
  1308. SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
  1309. }
  1310. // Note that "event=TestCaseEnd" is a wire format and has to remain
  1311. // "case" for compatibility
  1312. void OnTestCaseEnd(const TestCase& test_case) override {
  1313. SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
  1314. "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
  1315. "ms");
  1316. }
  1317. void OnTestStart(const TestInfo& test_info) override {
  1318. SendLn(std::string("event=TestStart&name=") + test_info.name());
  1319. }
  1320. void OnTestEnd(const TestInfo& test_info) override {
  1321. SendLn("event=TestEnd&passed=" +
  1322. FormatBool((test_info.result())->Passed()) +
  1323. "&elapsed_time=" +
  1324. StreamableToString((test_info.result())->elapsed_time()) + "ms");
  1325. }
  1326. void OnTestPartResult(const TestPartResult& test_part_result) override {
  1327. const char* file_name = test_part_result.file_name();
  1328. if (file_name == nullptr) file_name = "";
  1329. SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
  1330. "&line=" + StreamableToString(test_part_result.line_number()) +
  1331. "&message=" + UrlEncode(test_part_result.message()));
  1332. }
  1333. private:
  1334. // Sends the given message and a newline to the socket.
  1335. void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
  1336. // Called at the start of streaming to notify the receiver what
  1337. // protocol we are using.
  1338. void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
  1339. std::string FormatBool(bool value) { return value ? "1" : "0"; }
  1340. const std::unique_ptr<AbstractSocketWriter> socket_writer_;
  1341. GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
  1342. }; // class StreamingListener
  1343. #endif // GTEST_CAN_STREAM_RESULTS_
  1344. } // namespace internal
  1345. } // namespace testing
  1346. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  1347. #endif // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
  1348. #if GTEST_OS_WINDOWS
  1349. # define vsnprintf _vsnprintf
  1350. #endif // GTEST_OS_WINDOWS
  1351. #if GTEST_OS_MAC
  1352. #ifndef GTEST_OS_IOS
  1353. #include <crt_externs.h>
  1354. #endif
  1355. #endif
  1356. #if GTEST_HAS_ABSL
  1357. #include "absl/debugging/failure_signal_handler.h"
  1358. #include "absl/debugging/stacktrace.h"
  1359. #include "absl/debugging/symbolize.h"
  1360. #include "absl/strings/str_cat.h"
  1361. #endif // GTEST_HAS_ABSL
  1362. namespace testing {
  1363. using internal::CountIf;
  1364. using internal::ForEach;
  1365. using internal::GetElementOr;
  1366. using internal::Shuffle;
  1367. // Constants.
  1368. // A test whose test suite name or test name matches this filter is
  1369. // disabled and not run.
  1370. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
  1371. // A test suite whose name matches this filter is considered a death
  1372. // test suite and will be run before test suites whose name doesn't
  1373. // match this filter.
  1374. static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
  1375. // A test filter that matches everything.
  1376. static const char kUniversalFilter[] = "*";
  1377. // The default output format.
  1378. static const char kDefaultOutputFormat[] = "xml";
  1379. // The default output file.
  1380. static const char kDefaultOutputFile[] = "test_detail";
  1381. // The environment variable name for the test shard index.
  1382. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
  1383. // The environment variable name for the total number of test shards.
  1384. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
  1385. // The environment variable name for the test shard status file.
  1386. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
  1387. namespace internal {
  1388. // The text used in failure messages to indicate the start of the
  1389. // stack trace.
  1390. const char kStackTraceMarker[] = "\nStack trace:\n";
  1391. // g_help_flag is true if and only if the --help flag or an equivalent form
  1392. // is specified on the command line.
  1393. bool g_help_flag = false;
  1394. // Utilty function to Open File for Writing
  1395. static FILE* OpenFileForWriting(const std::string& output_file) {
  1396. FILE* fileout = nullptr;
  1397. FilePath output_file_path(output_file);
  1398. FilePath output_dir(output_file_path.RemoveFileName());
  1399. if (output_dir.CreateDirectoriesRecursively()) {
  1400. fileout = posix::FOpen(output_file.c_str(), "w");
  1401. }
  1402. if (fileout == nullptr) {
  1403. GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
  1404. }
  1405. return fileout;
  1406. }
  1407. } // namespace internal
  1408. // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
  1409. // environment variable.
  1410. static const char* GetDefaultFilter() {
  1411. const char* const testbridge_test_only =
  1412. internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
  1413. if (testbridge_test_only != nullptr) {
  1414. return testbridge_test_only;
  1415. }
  1416. return kUniversalFilter;
  1417. }
  1418. // Bazel passes in the argument to '--test_runner_fail_fast' via the
  1419. // TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.
  1420. static bool GetDefaultFailFast() {
  1421. const char* const testbridge_test_runner_fail_fast =
  1422. internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
  1423. if (testbridge_test_runner_fail_fast != nullptr) {
  1424. return strcmp(testbridge_test_runner_fail_fast, "1") == 0;
  1425. }
  1426. return false;
  1427. }
  1428. GTEST_DEFINE_bool_(
  1429. fail_fast, internal::BoolFromGTestEnv("fail_fast", GetDefaultFailFast()),
  1430. "True if and only if a test failure should stop further test execution.");
  1431. GTEST_DEFINE_bool_(
  1432. also_run_disabled_tests,
  1433. internal::BoolFromGTestEnv("also_run_disabled_tests", false),
  1434. "Run disabled tests too, in addition to the tests normally being run.");
  1435. GTEST_DEFINE_bool_(
  1436. break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false),
  1437. "True if and only if a failed assertion should be a debugger "
  1438. "break-point.");
  1439. GTEST_DEFINE_bool_(catch_exceptions,
  1440. internal::BoolFromGTestEnv("catch_exceptions", true),
  1441. "True if and only if " GTEST_NAME_
  1442. " should catch exceptions and treat them as test failures.");
  1443. GTEST_DEFINE_string_(
  1444. color,
  1445. internal::StringFromGTestEnv("color", "auto"),
  1446. "Whether to use colors in the output. Valid values: yes, no, "
  1447. "and auto. 'auto' means to use colors if the output is "
  1448. "being sent to a terminal and the TERM environment variable "
  1449. "is set to a terminal type that supports colors.");
  1450. GTEST_DEFINE_string_(
  1451. filter,
  1452. internal::StringFromGTestEnv("filter", GetDefaultFilter()),
  1453. "A colon-separated list of glob (not regex) patterns "
  1454. "for filtering the tests to run, optionally followed by a "
  1455. "'-' and a : separated list of negative patterns (tests to "
  1456. "exclude). A test is run if it matches one of the positive "
  1457. "patterns and does not match any of the negative patterns.");
  1458. GTEST_DEFINE_bool_(
  1459. install_failure_signal_handler,
  1460. internal::BoolFromGTestEnv("install_failure_signal_handler", false),
  1461. "If true and supported on the current platform, " GTEST_NAME_ " should "
  1462. "install a signal handler that dumps debugging information when fatal "
  1463. "signals are raised.");
  1464. GTEST_DEFINE_bool_(list_tests, false,
  1465. "List all tests without running them.");
  1466. // The net priority order after flag processing is thus:
  1467. // --gtest_output command line flag
  1468. // GTEST_OUTPUT environment variable
  1469. // XML_OUTPUT_FILE environment variable
  1470. // ''
  1471. GTEST_DEFINE_string_(
  1472. output,
  1473. internal::StringFromGTestEnv("output",
  1474. internal::OutputFlagAlsoCheckEnvVar().c_str()),
  1475. "A format (defaults to \"xml\" but can be specified to be \"json\"), "
  1476. "optionally followed by a colon and an output file name or directory. "
  1477. "A directory is indicated by a trailing pathname separator. "
  1478. "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
  1479. "If a directory is specified, output files will be created "
  1480. "within that directory, with file-names based on the test "
  1481. "executable's name and, if necessary, made unique by adding "
  1482. "digits.");
  1483. GTEST_DEFINE_bool_(
  1484. brief, internal::BoolFromGTestEnv("brief", false),
  1485. "True if only test failures should be displayed in text output.");
  1486. GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true),
  1487. "True if and only if " GTEST_NAME_
  1488. " should display elapsed time in text output.");
  1489. GTEST_DEFINE_bool_(print_utf8, internal::BoolFromGTestEnv("print_utf8", true),
  1490. "True if and only if " GTEST_NAME_
  1491. " prints UTF8 characters as text.");
  1492. GTEST_DEFINE_int32_(
  1493. random_seed,
  1494. internal::Int32FromGTestEnv("random_seed", 0),
  1495. "Random number seed to use when shuffling test orders. Must be in range "
  1496. "[1, 99999], or 0 to use a seed based on the current time.");
  1497. GTEST_DEFINE_int32_(
  1498. repeat,
  1499. internal::Int32FromGTestEnv("repeat", 1),
  1500. "How many times to repeat each test. Specify a negative number "
  1501. "for repeating forever. Useful for shaking out flaky tests.");
  1502. GTEST_DEFINE_bool_(show_internal_stack_frames, false,
  1503. "True if and only if " GTEST_NAME_
  1504. " should include internal stack frames when "
  1505. "printing test failure stack traces.");
  1506. GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false),
  1507. "True if and only if " GTEST_NAME_
  1508. " should randomize tests' order on every run.");
  1509. GTEST_DEFINE_int32_(
  1510. stack_trace_depth,
  1511. internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
  1512. "The maximum number of stack frames to print when an "
  1513. "assertion fails. The valid range is 0 through 100, inclusive.");
  1514. GTEST_DEFINE_string_(
  1515. stream_result_to,
  1516. internal::StringFromGTestEnv("stream_result_to", ""),
  1517. "This flag specifies the host name and the port number on which to stream "
  1518. "test results. Example: \"localhost:555\". The flag is effective only on "
  1519. "Linux.");
  1520. GTEST_DEFINE_bool_(
  1521. throw_on_failure,
  1522. internal::BoolFromGTestEnv("throw_on_failure", false),
  1523. "When this flag is specified, a failed assertion will throw an exception "
  1524. "if exceptions are enabled or exit the program with a non-zero code "
  1525. "otherwise. For use with an external test framework.");
  1526. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  1527. GTEST_DEFINE_string_(
  1528. flagfile,
  1529. internal::StringFromGTestEnv("flagfile", ""),
  1530. "This flag specifies the flagfile to read command-line flags from.");
  1531. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  1532. namespace internal {
  1533. // Generates a random number from [0, range), using a Linear
  1534. // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
  1535. // than kMaxRange.
  1536. uint32_t Random::Generate(uint32_t range) {
  1537. // These constants are the same as are used in glibc's rand(3).
  1538. // Use wider types than necessary to prevent unsigned overflow diagnostics.
  1539. state_ = static_cast<uint32_t>(1103515245ULL*state_ + 12345U) % kMaxRange;
  1540. GTEST_CHECK_(range > 0)
  1541. << "Cannot generate a number in the range [0, 0).";
  1542. GTEST_CHECK_(range <= kMaxRange)
  1543. << "Generation of a number in [0, " << range << ") was requested, "
  1544. << "but this can only generate numbers in [0, " << kMaxRange << ").";
  1545. // Converting via modulus introduces a bit of downward bias, but
  1546. // it's simple, and a linear congruential generator isn't too good
  1547. // to begin with.
  1548. return state_ % range;
  1549. }
  1550. // GTestIsInitialized() returns true if and only if the user has initialized
  1551. // Google Test. Useful for catching the user mistake of not initializing
  1552. // Google Test before calling RUN_ALL_TESTS().
  1553. static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
  1554. // Iterates over a vector of TestSuites, keeping a running sum of the
  1555. // results of calling a given int-returning method on each.
  1556. // Returns the sum.
  1557. static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
  1558. int (TestSuite::*method)() const) {
  1559. int sum = 0;
  1560. for (size_t i = 0; i < case_list.size(); i++) {
  1561. sum += (case_list[i]->*method)();
  1562. }
  1563. return sum;
  1564. }
  1565. // Returns true if and only if the test suite passed.
  1566. static bool TestSuitePassed(const TestSuite* test_suite) {
  1567. return test_suite->should_run() && test_suite->Passed();
  1568. }
  1569. // Returns true if and only if the test suite failed.
  1570. static bool TestSuiteFailed(const TestSuite* test_suite) {
  1571. return test_suite->should_run() && test_suite->Failed();
  1572. }
  1573. // Returns true if and only if test_suite contains at least one test that
  1574. // should run.
  1575. static bool ShouldRunTestSuite(const TestSuite* test_suite) {
  1576. return test_suite->should_run();
  1577. }
  1578. // AssertHelper constructor.
  1579. AssertHelper::AssertHelper(TestPartResult::Type type,
  1580. const char* file,
  1581. int line,
  1582. const char* message)
  1583. : data_(new AssertHelperData(type, file, line, message)) {
  1584. }
  1585. AssertHelper::~AssertHelper() {
  1586. delete data_;
  1587. }
  1588. // Message assignment, for assertion streaming support.
  1589. void AssertHelper::operator=(const Message& message) const {
  1590. UnitTest::GetInstance()->
  1591. AddTestPartResult(data_->type, data_->file, data_->line,
  1592. AppendUserMessage(data_->message, message),
  1593. UnitTest::GetInstance()->impl()
  1594. ->CurrentOsStackTraceExceptTop(1)
  1595. // Skips the stack frame for this function itself.
  1596. ); // NOLINT
  1597. }
  1598. namespace {
  1599. // When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P
  1600. // to creates test cases for it, a syntetic test case is
  1601. // inserted to report ether an error or a log message.
  1602. //
  1603. // This configuration bit will likely be removed at some point.
  1604. constexpr bool kErrorOnUninstantiatedParameterizedTest = true;
  1605. constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true;
  1606. // A test that fails at a given file/line location with a given message.
  1607. class FailureTest : public Test {
  1608. public:
  1609. explicit FailureTest(const CodeLocation& loc, std::string error_message,
  1610. bool as_error)
  1611. : loc_(loc),
  1612. error_message_(std::move(error_message)),
  1613. as_error_(as_error) {}
  1614. void TestBody() override {
  1615. if (as_error_) {
  1616. AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),
  1617. loc_.line, "") = Message() << error_message_;
  1618. } else {
  1619. std::cout << error_message_ << std::endl;
  1620. }
  1621. }
  1622. private:
  1623. const CodeLocation loc_;
  1624. const std::string error_message_;
  1625. const bool as_error_;
  1626. };
  1627. } // namespace
  1628. std::set<std::string>* GetIgnoredParameterizedTestSuites() {
  1629. return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
  1630. }
  1631. // Add a given test_suit to the list of them allow to go un-instantiated.
  1632. MarkAsIgnored::MarkAsIgnored(const char* test_suite) {
  1633. GetIgnoredParameterizedTestSuites()->insert(test_suite);
  1634. }
  1635. // If this parameterized test suite has no instantiations (and that
  1636. // has not been marked as okay), emit a test case reporting that.
  1637. void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
  1638. bool has_test_p) {
  1639. const auto& ignored = *GetIgnoredParameterizedTestSuites();
  1640. if (ignored.find(name) != ignored.end()) return;
  1641. const char kMissingInstantiation[] = //
  1642. " is defined via TEST_P, but never instantiated. None of the test cases "
  1643. "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
  1644. "ones provided expand to nothing."
  1645. "\n\n"
  1646. "Ideally, TEST_P definitions should only ever be included as part of "
  1647. "binaries that intend to use them. (As opposed to, for example, being "
  1648. "placed in a library that may be linked in to get other utilities.)";
  1649. const char kMissingTestCase[] = //
  1650. " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
  1651. "defined via TEST_P . No test cases will run."
  1652. "\n\n"
  1653. "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
  1654. "code that always depend on code that provides TEST_P. Failing to do "
  1655. "so is often an indication of dead code, e.g. the last TEST_P was "
  1656. "removed but the rest got left behind.";
  1657. std::string message =
  1658. "Parameterized test suite " + name +
  1659. (has_test_p ? kMissingInstantiation : kMissingTestCase) +
  1660. "\n\n"
  1661. "To suppress this error for this test suite, insert the following line "
  1662. "(in a non-header) in the namespace it is defined in:"
  1663. "\n\n"
  1664. "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");";
  1665. std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
  1666. RegisterTest( //
  1667. "GoogleTestVerification", full_name.c_str(),
  1668. nullptr, // No type parameter.
  1669. nullptr, // No value parameter.
  1670. location.file.c_str(), location.line, [message, location] {
  1671. return new FailureTest(location, message,
  1672. kErrorOnUninstantiatedParameterizedTest);
  1673. });
  1674. }
  1675. void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
  1676. CodeLocation code_location) {
  1677. GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(
  1678. test_suite_name, code_location);
  1679. }
  1680. void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) {
  1681. GetUnitTestImpl()
  1682. ->type_parameterized_test_registry()
  1683. .RegisterInstantiation(case_name);
  1684. }
  1685. void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
  1686. const char* test_suite_name, CodeLocation code_location) {
  1687. suites_.emplace(std::string(test_suite_name),
  1688. TypeParameterizedTestSuiteInfo(code_location));
  1689. }
  1690. void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
  1691. const char* test_suite_name) {
  1692. auto it = suites_.find(std::string(test_suite_name));
  1693. if (it != suites_.end()) {
  1694. it->second.instantiated = true;
  1695. } else {
  1696. GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '"
  1697. << test_suite_name << "'";
  1698. }
  1699. }
  1700. void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
  1701. const auto& ignored = *GetIgnoredParameterizedTestSuites();
  1702. for (const auto& testcase : suites_) {
  1703. if (testcase.second.instantiated) continue;
  1704. if (ignored.find(testcase.first) != ignored.end()) continue;
  1705. std::string message =
  1706. "Type parameterized test suite " + testcase.first +
  1707. " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
  1708. "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
  1709. "\n\n"
  1710. "Ideally, TYPED_TEST_P definitions should only ever be included as "
  1711. "part of binaries that intend to use them. (As opposed to, for "
  1712. "example, being placed in a library that may be linked in to get other "
  1713. "utilities.)"
  1714. "\n\n"
  1715. "To suppress this error for this test suite, insert the following line "
  1716. "(in a non-header) in the namespace it is defined in:"
  1717. "\n\n"
  1718. "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
  1719. testcase.first + ");";
  1720. std::string full_name =
  1721. "UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">";
  1722. RegisterTest( //
  1723. "GoogleTestVerification", full_name.c_str(),
  1724. nullptr, // No type parameter.
  1725. nullptr, // No value parameter.
  1726. testcase.second.code_location.file.c_str(),
  1727. testcase.second.code_location.line, [message, testcase] {
  1728. return new FailureTest(testcase.second.code_location, message,
  1729. kErrorOnUninstantiatedTypeParameterizedTest);
  1730. });
  1731. }
  1732. }
  1733. // A copy of all command line arguments. Set by InitGoogleTest().
  1734. static ::std::vector<std::string> g_argvs;
  1735. ::std::vector<std::string> GetArgvs() {
  1736. #if defined(GTEST_CUSTOM_GET_ARGVS_)
  1737. // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
  1738. // ::string. This code converts it to the appropriate type.
  1739. const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
  1740. return ::std::vector<std::string>(custom.begin(), custom.end());
  1741. #else // defined(GTEST_CUSTOM_GET_ARGVS_)
  1742. return g_argvs;
  1743. #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
  1744. }
  1745. // Returns the current application's name, removing directory path if that
  1746. // is present.
  1747. FilePath GetCurrentExecutableName() {
  1748. FilePath result;
  1749. #if GTEST_OS_WINDOWS || GTEST_OS_OS2
  1750. result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
  1751. #else
  1752. result.Set(FilePath(GetArgvs()[0]));
  1753. #endif // GTEST_OS_WINDOWS
  1754. return result.RemoveDirectoryName();
  1755. }
  1756. // Functions for processing the gtest_output flag.
  1757. // Returns the output format, or "" for normal printed output.
  1758. std::string UnitTestOptions::GetOutputFormat() {
  1759. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1760. const char* const colon = strchr(gtest_output_flag, ':');
  1761. return (colon == nullptr)
  1762. ? std::string(gtest_output_flag)
  1763. : std::string(gtest_output_flag,
  1764. static_cast<size_t>(colon - gtest_output_flag));
  1765. }
  1766. // Returns the name of the requested output file, or the default if none
  1767. // was explicitly specified.
  1768. std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
  1769. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1770. std::string format = GetOutputFormat();
  1771. if (format.empty())
  1772. format = std::string(kDefaultOutputFormat);
  1773. const char* const colon = strchr(gtest_output_flag, ':');
  1774. if (colon == nullptr)
  1775. return internal::FilePath::MakeFileName(
  1776. internal::FilePath(
  1777. UnitTest::GetInstance()->original_working_dir()),
  1778. internal::FilePath(kDefaultOutputFile), 0,
  1779. format.c_str()).string();
  1780. internal::FilePath output_name(colon + 1);
  1781. if (!output_name.IsAbsolutePath())
  1782. output_name = internal::FilePath::ConcatPaths(
  1783. internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
  1784. internal::FilePath(colon + 1));
  1785. if (!output_name.IsDirectory())
  1786. return output_name.string();
  1787. internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
  1788. output_name, internal::GetCurrentExecutableName(),
  1789. GetOutputFormat().c_str()));
  1790. return result.string();
  1791. }
  1792. // Returns true if and only if the wildcard pattern matches the string. Each
  1793. // pattern consists of regular characters, single-character wildcards (?), and
  1794. // multi-character wildcards (*).
  1795. //
  1796. // This function implements a linear-time string globbing algorithm based on
  1797. // https://research.swtch.com/glob.
  1798. static bool PatternMatchesString(const std::string& name_str,
  1799. const char* pattern, const char* pattern_end) {
  1800. const char* name = name_str.c_str();
  1801. const char* const name_begin = name;
  1802. const char* const name_end = name + name_str.size();
  1803. const char* pattern_next = pattern;
  1804. const char* name_next = name;
  1805. while (pattern < pattern_end || name < name_end) {
  1806. if (pattern < pattern_end) {
  1807. switch (*pattern) {
  1808. default: // Match an ordinary character.
  1809. if (name < name_end && *name == *pattern) {
  1810. ++pattern;
  1811. ++name;
  1812. continue;
  1813. }
  1814. break;
  1815. case '?': // Match any single character.
  1816. if (name < name_end) {
  1817. ++pattern;
  1818. ++name;
  1819. continue;
  1820. }
  1821. break;
  1822. case '*':
  1823. // Match zero or more characters. Start by skipping over the wildcard
  1824. // and matching zero characters from name. If that fails, restart and
  1825. // match one more character than the last attempt.
  1826. pattern_next = pattern;
  1827. name_next = name + 1;
  1828. ++pattern;
  1829. continue;
  1830. }
  1831. }
  1832. // Failed to match a character. Restart if possible.
  1833. if (name_begin < name_next && name_next <= name_end) {
  1834. pattern = pattern_next;
  1835. name = name_next;
  1836. continue;
  1837. }
  1838. return false;
  1839. }
  1840. return true;
  1841. }
  1842. bool UnitTestOptions::MatchesFilter(const std::string& name_str,
  1843. const char* filter) {
  1844. // The filter is a list of patterns separated by colons (:).
  1845. const char* pattern = filter;
  1846. while (true) {
  1847. // Find the bounds of this pattern.
  1848. const char* const next_sep = strchr(pattern, ':');
  1849. const char* const pattern_end =
  1850. next_sep != nullptr ? next_sep : pattern + strlen(pattern);
  1851. // Check if this pattern matches name_str.
  1852. if (PatternMatchesString(name_str, pattern, pattern_end)) {
  1853. return true;
  1854. }
  1855. // Give up on this pattern. However, if we found a pattern separator (:),
  1856. // advance to the next pattern (skipping over the separator) and restart.
  1857. if (next_sep == nullptr) {
  1858. return false;
  1859. }
  1860. pattern = next_sep + 1;
  1861. }
  1862. return true;
  1863. }
  1864. // Returns true if and only if the user-specified filter matches the test
  1865. // suite name and the test name.
  1866. bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
  1867. const std::string& test_name) {
  1868. const std::string& full_name = test_suite_name + "." + test_name.c_str();
  1869. // Split --gtest_filter at '-', if there is one, to separate into
  1870. // positive filter and negative filter portions
  1871. const char* const p = GTEST_FLAG(filter).c_str();
  1872. const char* const dash = strchr(p, '-');
  1873. std::string positive;
  1874. std::string negative;
  1875. if (dash == nullptr) {
  1876. positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
  1877. negative = "";
  1878. } else {
  1879. positive = std::string(p, dash); // Everything up to the dash
  1880. negative = std::string(dash + 1); // Everything after the dash
  1881. if (positive.empty()) {
  1882. // Treat '-test1' as the same as '*-test1'
  1883. positive = kUniversalFilter;
  1884. }
  1885. }
  1886. // A filter is a colon-separated list of patterns. It matches a
  1887. // test if any pattern in it matches the test.
  1888. return (MatchesFilter(full_name, positive.c_str()) &&
  1889. !MatchesFilter(full_name, negative.c_str()));
  1890. }
  1891. #if GTEST_HAS_SEH
  1892. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  1893. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  1894. // This function is useful as an __except condition.
  1895. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
  1896. // Google Test should handle a SEH exception if:
  1897. // 1. the user wants it to, AND
  1898. // 2. this is not a breakpoint exception, AND
  1899. // 3. this is not a C++ exception (VC++ implements them via SEH,
  1900. // apparently).
  1901. //
  1902. // SEH exception code for C++ exceptions.
  1903. // (see http://support.microsoft.com/kb/185294 for more information).
  1904. const DWORD kCxxExceptionCode = 0xe06d7363;
  1905. bool should_handle = true;
  1906. if (!GTEST_FLAG(catch_exceptions))
  1907. should_handle = false;
  1908. else if (exception_code == EXCEPTION_BREAKPOINT)
  1909. should_handle = false;
  1910. else if (exception_code == kCxxExceptionCode)
  1911. should_handle = false;
  1912. return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
  1913. }
  1914. #endif // GTEST_HAS_SEH
  1915. } // namespace internal
  1916. // The c'tor sets this object as the test part result reporter used by
  1917. // Google Test. The 'result' parameter specifies where to report the
  1918. // results. Intercepts only failures from the current thread.
  1919. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1920. TestPartResultArray* result)
  1921. : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
  1922. result_(result) {
  1923. Init();
  1924. }
  1925. // The c'tor sets this object as the test part result reporter used by
  1926. // Google Test. The 'result' parameter specifies where to report the
  1927. // results.
  1928. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1929. InterceptMode intercept_mode, TestPartResultArray* result)
  1930. : intercept_mode_(intercept_mode),
  1931. result_(result) {
  1932. Init();
  1933. }
  1934. void ScopedFakeTestPartResultReporter::Init() {
  1935. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1936. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1937. old_reporter_ = impl->GetGlobalTestPartResultReporter();
  1938. impl->SetGlobalTestPartResultReporter(this);
  1939. } else {
  1940. old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
  1941. impl->SetTestPartResultReporterForCurrentThread(this);
  1942. }
  1943. }
  1944. // The d'tor restores the test part result reporter used by Google Test
  1945. // before.
  1946. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
  1947. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1948. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1949. impl->SetGlobalTestPartResultReporter(old_reporter_);
  1950. } else {
  1951. impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
  1952. }
  1953. }
  1954. // Increments the test part result count and remembers the result.
  1955. // This method is from the TestPartResultReporterInterface interface.
  1956. void ScopedFakeTestPartResultReporter::ReportTestPartResult(
  1957. const TestPartResult& result) {
  1958. result_->Append(result);
  1959. }
  1960. namespace internal {
  1961. // Returns the type ID of ::testing::Test. We should always call this
  1962. // instead of GetTypeId< ::testing::Test>() to get the type ID of
  1963. // testing::Test. This is to work around a suspected linker bug when
  1964. // using Google Test as a framework on Mac OS X. The bug causes
  1965. // GetTypeId< ::testing::Test>() to return different values depending
  1966. // on whether the call is from the Google Test framework itself or
  1967. // from user test code. GetTestTypeId() is guaranteed to always
  1968. // return the same value, as it always calls GetTypeId<>() from the
  1969. // gtest.cc, which is within the Google Test framework.
  1970. TypeId GetTestTypeId() {
  1971. return GetTypeId<Test>();
  1972. }
  1973. // The value of GetTestTypeId() as seen from within the Google Test
  1974. // library. This is solely for testing GetTestTypeId().
  1975. extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
  1976. // This predicate-formatter checks that 'results' contains a test part
  1977. // failure of the given type and that the failure message contains the
  1978. // given substring.
  1979. static AssertionResult HasOneFailure(const char* /* results_expr */,
  1980. const char* /* type_expr */,
  1981. const char* /* substr_expr */,
  1982. const TestPartResultArray& results,
  1983. TestPartResult::Type type,
  1984. const std::string& substr) {
  1985. const std::string expected(type == TestPartResult::kFatalFailure ?
  1986. "1 fatal failure" :
  1987. "1 non-fatal failure");
  1988. Message msg;
  1989. if (results.size() != 1) {
  1990. msg << "Expected: " << expected << "\n"
  1991. << " Actual: " << results.size() << " failures";
  1992. for (int i = 0; i < results.size(); i++) {
  1993. msg << "\n" << results.GetTestPartResult(i);
  1994. }
  1995. return AssertionFailure() << msg;
  1996. }
  1997. const TestPartResult& r = results.GetTestPartResult(0);
  1998. if (r.type() != type) {
  1999. return AssertionFailure() << "Expected: " << expected << "\n"
  2000. << " Actual:\n"
  2001. << r;
  2002. }
  2003. if (strstr(r.message(), substr.c_str()) == nullptr) {
  2004. return AssertionFailure() << "Expected: " << expected << " containing \""
  2005. << substr << "\"\n"
  2006. << " Actual:\n"
  2007. << r;
  2008. }
  2009. return AssertionSuccess();
  2010. }
  2011. // The constructor of SingleFailureChecker remembers where to look up
  2012. // test part results, what type of failure we expect, and what
  2013. // substring the failure message should contain.
  2014. SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
  2015. TestPartResult::Type type,
  2016. const std::string& substr)
  2017. : results_(results), type_(type), substr_(substr) {}
  2018. // The destructor of SingleFailureChecker verifies that the given
  2019. // TestPartResultArray contains exactly one failure that has the given
  2020. // type and contains the given substring. If that's not the case, a
  2021. // non-fatal failure will be generated.
  2022. SingleFailureChecker::~SingleFailureChecker() {
  2023. EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
  2024. }
  2025. DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
  2026. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  2027. void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
  2028. const TestPartResult& result) {
  2029. unit_test_->current_test_result()->AddTestPartResult(result);
  2030. unit_test_->listeners()->repeater()->OnTestPartResult(result);
  2031. }
  2032. DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
  2033. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  2034. void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
  2035. const TestPartResult& result) {
  2036. unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
  2037. }
  2038. // Returns the global test part result reporter.
  2039. TestPartResultReporterInterface*
  2040. UnitTestImpl::GetGlobalTestPartResultReporter() {
  2041. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  2042. return global_test_part_result_repoter_;
  2043. }
  2044. // Sets the global test part result reporter.
  2045. void UnitTestImpl::SetGlobalTestPartResultReporter(
  2046. TestPartResultReporterInterface* reporter) {
  2047. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  2048. global_test_part_result_repoter_ = reporter;
  2049. }
  2050. // Returns the test part result reporter for the current thread.
  2051. TestPartResultReporterInterface*
  2052. UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
  2053. return per_thread_test_part_result_reporter_.get();
  2054. }
  2055. // Sets the test part result reporter for the current thread.
  2056. void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
  2057. TestPartResultReporterInterface* reporter) {
  2058. per_thread_test_part_result_reporter_.set(reporter);
  2059. }
  2060. // Gets the number of successful test suites.
  2061. int UnitTestImpl::successful_test_suite_count() const {
  2062. return CountIf(test_suites_, TestSuitePassed);
  2063. }
  2064. // Gets the number of failed test suites.
  2065. int UnitTestImpl::failed_test_suite_count() const {
  2066. return CountIf(test_suites_, TestSuiteFailed);
  2067. }
  2068. // Gets the number of all test suites.
  2069. int UnitTestImpl::total_test_suite_count() const {
  2070. return static_cast<int>(test_suites_.size());
  2071. }
  2072. // Gets the number of all test suites that contain at least one test
  2073. // that should run.
  2074. int UnitTestImpl::test_suite_to_run_count() const {
  2075. return CountIf(test_suites_, ShouldRunTestSuite);
  2076. }
  2077. // Gets the number of successful tests.
  2078. int UnitTestImpl::successful_test_count() const {
  2079. return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
  2080. }
  2081. // Gets the number of skipped tests.
  2082. int UnitTestImpl::skipped_test_count() const {
  2083. return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
  2084. }
  2085. // Gets the number of failed tests.
  2086. int UnitTestImpl::failed_test_count() const {
  2087. return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
  2088. }
  2089. // Gets the number of disabled tests that will be reported in the XML report.
  2090. int UnitTestImpl::reportable_disabled_test_count() const {
  2091. return SumOverTestSuiteList(test_suites_,
  2092. &TestSuite::reportable_disabled_test_count);
  2093. }
  2094. // Gets the number of disabled tests.
  2095. int UnitTestImpl::disabled_test_count() const {
  2096. return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
  2097. }
  2098. // Gets the number of tests to be printed in the XML report.
  2099. int UnitTestImpl::reportable_test_count() const {
  2100. return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
  2101. }
  2102. // Gets the number of all tests.
  2103. int UnitTestImpl::total_test_count() const {
  2104. return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
  2105. }
  2106. // Gets the number of tests that should run.
  2107. int UnitTestImpl::test_to_run_count() const {
  2108. return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
  2109. }
  2110. // Returns the current OS stack trace as an std::string.
  2111. //
  2112. // The maximum number of stack frames to be included is specified by
  2113. // the gtest_stack_trace_depth flag. The skip_count parameter
  2114. // specifies the number of top frames to be skipped, which doesn't
  2115. // count against the number of frames to be included.
  2116. //
  2117. // For example, if Foo() calls Bar(), which in turn calls
  2118. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  2119. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  2120. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
  2121. return os_stack_trace_getter()->CurrentStackTrace(
  2122. static_cast<int>(GTEST_FLAG(stack_trace_depth)),
  2123. skip_count + 1
  2124. // Skips the user-specified number of frames plus this function
  2125. // itself.
  2126. ); // NOLINT
  2127. }
  2128. // A helper class for measuring elapsed times.
  2129. class Timer {
  2130. public:
  2131. Timer() : start_(std::chrono::steady_clock::now()) {}
  2132. // Return time elapsed in milliseconds since the timer was created.
  2133. TimeInMillis Elapsed() {
  2134. return std::chrono::duration_cast<std::chrono::milliseconds>(
  2135. std::chrono::steady_clock::now() - start_)
  2136. .count();
  2137. }
  2138. private:
  2139. std::chrono::steady_clock::time_point start_;
  2140. };
  2141. // Returns a timestamp as milliseconds since the epoch. Note this time may jump
  2142. // around subject to adjustments by the system, to measure elapsed time use
  2143. // Timer instead.
  2144. TimeInMillis GetTimeInMillis() {
  2145. return std::chrono::duration_cast<std::chrono::milliseconds>(
  2146. std::chrono::system_clock::now() -
  2147. std::chrono::system_clock::from_time_t(0))
  2148. .count();
  2149. }
  2150. // Utilities
  2151. // class String.
  2152. #if GTEST_OS_WINDOWS_MOBILE
  2153. // Creates a UTF-16 wide string from the given ANSI string, allocating
  2154. // memory using new. The caller is responsible for deleting the return
  2155. // value using delete[]. Returns the wide string, or NULL if the
  2156. // input is NULL.
  2157. LPCWSTR String::AnsiToUtf16(const char* ansi) {
  2158. if (!ansi) return nullptr;
  2159. const int length = strlen(ansi);
  2160. const int unicode_length =
  2161. MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
  2162. WCHAR* unicode = new WCHAR[unicode_length + 1];
  2163. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  2164. unicode, unicode_length);
  2165. unicode[unicode_length] = 0;
  2166. return unicode;
  2167. }
  2168. // Creates an ANSI string from the given wide string, allocating
  2169. // memory using new. The caller is responsible for deleting the return
  2170. // value using delete[]. Returns the ANSI string, or NULL if the
  2171. // input is NULL.
  2172. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
  2173. if (!utf16_str) return nullptr;
  2174. const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
  2175. 0, nullptr, nullptr);
  2176. char* ansi = new char[ansi_length + 1];
  2177. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
  2178. nullptr);
  2179. ansi[ansi_length] = 0;
  2180. return ansi;
  2181. }
  2182. #endif // GTEST_OS_WINDOWS_MOBILE
  2183. // Compares two C strings. Returns true if and only if they have the same
  2184. // content.
  2185. //
  2186. // Unlike strcmp(), this function can handle NULL argument(s). A NULL
  2187. // C string is considered different to any non-NULL C string,
  2188. // including the empty string.
  2189. bool String::CStringEquals(const char * lhs, const char * rhs) {
  2190. if (lhs == nullptr) return rhs == nullptr;
  2191. if (rhs == nullptr) return false;
  2192. return strcmp(lhs, rhs) == 0;
  2193. }
  2194. #if GTEST_HAS_STD_WSTRING
  2195. // Converts an array of wide chars to a narrow string using the UTF-8
  2196. // encoding, and streams the result to the given Message object.
  2197. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
  2198. Message* msg) {
  2199. for (size_t i = 0; i != length; ) { // NOLINT
  2200. if (wstr[i] != L'\0') {
  2201. *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
  2202. while (i != length && wstr[i] != L'\0')
  2203. i++;
  2204. } else {
  2205. *msg << '\0';
  2206. i++;
  2207. }
  2208. }
  2209. }
  2210. #endif // GTEST_HAS_STD_WSTRING
  2211. void SplitString(const ::std::string& str, char delimiter,
  2212. ::std::vector< ::std::string>* dest) {
  2213. ::std::vector< ::std::string> parsed;
  2214. ::std::string::size_type pos = 0;
  2215. while (::testing::internal::AlwaysTrue()) {
  2216. const ::std::string::size_type colon = str.find(delimiter, pos);
  2217. if (colon == ::std::string::npos) {
  2218. parsed.push_back(str.substr(pos));
  2219. break;
  2220. } else {
  2221. parsed.push_back(str.substr(pos, colon - pos));
  2222. pos = colon + 1;
  2223. }
  2224. }
  2225. dest->swap(parsed);
  2226. }
  2227. } // namespace internal
  2228. // Constructs an empty Message.
  2229. // We allocate the stringstream separately because otherwise each use of
  2230. // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
  2231. // stack frame leading to huge stack frames in some cases; gcc does not reuse
  2232. // the stack space.
  2233. Message::Message() : ss_(new ::std::stringstream) {
  2234. // By default, we want there to be enough precision when printing
  2235. // a double to a Message.
  2236. *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
  2237. }
  2238. // These two overloads allow streaming a wide C string to a Message
  2239. // using the UTF-8 encoding.
  2240. Message& Message::operator <<(const wchar_t* wide_c_str) {
  2241. return *this << internal::String::ShowWideCString(wide_c_str);
  2242. }
  2243. Message& Message::operator <<(wchar_t* wide_c_str) {
  2244. return *this << internal::String::ShowWideCString(wide_c_str);
  2245. }
  2246. #if GTEST_HAS_STD_WSTRING
  2247. // Converts the given wide string to a narrow string using the UTF-8
  2248. // encoding, and streams the result to this Message object.
  2249. Message& Message::operator <<(const ::std::wstring& wstr) {
  2250. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  2251. return *this;
  2252. }
  2253. #endif // GTEST_HAS_STD_WSTRING
  2254. // Gets the text streamed to this object so far as an std::string.
  2255. // Each '\0' character in the buffer is replaced with "\\0".
  2256. std::string Message::GetString() const {
  2257. return internal::StringStreamToString(ss_.get());
  2258. }
  2259. // AssertionResult constructors.
  2260. // Used in EXPECT_TRUE/FALSE(assertion_result).
  2261. AssertionResult::AssertionResult(const AssertionResult& other)
  2262. : success_(other.success_),
  2263. message_(other.message_.get() != nullptr
  2264. ? new ::std::string(*other.message_)
  2265. : static_cast< ::std::string*>(nullptr)) {}
  2266. // Swaps two AssertionResults.
  2267. void AssertionResult::swap(AssertionResult& other) {
  2268. using std::swap;
  2269. swap(success_, other.success_);
  2270. swap(message_, other.message_);
  2271. }
  2272. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  2273. AssertionResult AssertionResult::operator!() const {
  2274. AssertionResult negation(!success_);
  2275. if (message_.get() != nullptr) negation << *message_;
  2276. return negation;
  2277. }
  2278. // Makes a successful assertion result.
  2279. AssertionResult AssertionSuccess() {
  2280. return AssertionResult(true);
  2281. }
  2282. // Makes a failed assertion result.
  2283. AssertionResult AssertionFailure() {
  2284. return AssertionResult(false);
  2285. }
  2286. // Makes a failed assertion result with the given failure message.
  2287. // Deprecated; use AssertionFailure() << message.
  2288. AssertionResult AssertionFailure(const Message& message) {
  2289. return AssertionFailure() << message;
  2290. }
  2291. namespace internal {
  2292. namespace edit_distance {
  2293. std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
  2294. const std::vector<size_t>& right) {
  2295. std::vector<std::vector<double> > costs(
  2296. left.size() + 1, std::vector<double>(right.size() + 1));
  2297. std::vector<std::vector<EditType> > best_move(
  2298. left.size() + 1, std::vector<EditType>(right.size() + 1));
  2299. // Populate for empty right.
  2300. for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
  2301. costs[l_i][0] = static_cast<double>(l_i);
  2302. best_move[l_i][0] = kRemove;
  2303. }
  2304. // Populate for empty left.
  2305. for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
  2306. costs[0][r_i] = static_cast<double>(r_i);
  2307. best_move[0][r_i] = kAdd;
  2308. }
  2309. for (size_t l_i = 0; l_i < left.size(); ++l_i) {
  2310. for (size_t r_i = 0; r_i < right.size(); ++r_i) {
  2311. if (left[l_i] == right[r_i]) {
  2312. // Found a match. Consume it.
  2313. costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
  2314. best_move[l_i + 1][r_i + 1] = kMatch;
  2315. continue;
  2316. }
  2317. const double add = costs[l_i + 1][r_i];
  2318. const double remove = costs[l_i][r_i + 1];
  2319. const double replace = costs[l_i][r_i];
  2320. if (add < remove && add < replace) {
  2321. costs[l_i + 1][r_i + 1] = add + 1;
  2322. best_move[l_i + 1][r_i + 1] = kAdd;
  2323. } else if (remove < add && remove < replace) {
  2324. costs[l_i + 1][r_i + 1] = remove + 1;
  2325. best_move[l_i + 1][r_i + 1] = kRemove;
  2326. } else {
  2327. // We make replace a little more expensive than add/remove to lower
  2328. // their priority.
  2329. costs[l_i + 1][r_i + 1] = replace + 1.00001;
  2330. best_move[l_i + 1][r_i + 1] = kReplace;
  2331. }
  2332. }
  2333. }
  2334. // Reconstruct the best path. We do it in reverse order.
  2335. std::vector<EditType> best_path;
  2336. for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
  2337. EditType move = best_move[l_i][r_i];
  2338. best_path.push_back(move);
  2339. l_i -= move != kAdd;
  2340. r_i -= move != kRemove;
  2341. }
  2342. std::reverse(best_path.begin(), best_path.end());
  2343. return best_path;
  2344. }
  2345. namespace {
  2346. // Helper class to convert string into ids with deduplication.
  2347. class InternalStrings {
  2348. public:
  2349. size_t GetId(const std::string& str) {
  2350. IdMap::iterator it = ids_.find(str);
  2351. if (it != ids_.end()) return it->second;
  2352. size_t id = ids_.size();
  2353. return ids_[str] = id;
  2354. }
  2355. private:
  2356. typedef std::map<std::string, size_t> IdMap;
  2357. IdMap ids_;
  2358. };
  2359. } // namespace
  2360. std::vector<EditType> CalculateOptimalEdits(
  2361. const std::vector<std::string>& left,
  2362. const std::vector<std::string>& right) {
  2363. std::vector<size_t> left_ids, right_ids;
  2364. {
  2365. InternalStrings intern_table;
  2366. for (size_t i = 0; i < left.size(); ++i) {
  2367. left_ids.push_back(intern_table.GetId(left[i]));
  2368. }
  2369. for (size_t i = 0; i < right.size(); ++i) {
  2370. right_ids.push_back(intern_table.GetId(right[i]));
  2371. }
  2372. }
  2373. return CalculateOptimalEdits(left_ids, right_ids);
  2374. }
  2375. namespace {
  2376. // Helper class that holds the state for one hunk and prints it out to the
  2377. // stream.
  2378. // It reorders adds/removes when possible to group all removes before all
  2379. // adds. It also adds the hunk header before printint into the stream.
  2380. class Hunk {
  2381. public:
  2382. Hunk(size_t left_start, size_t right_start)
  2383. : left_start_(left_start),
  2384. right_start_(right_start),
  2385. adds_(),
  2386. removes_(),
  2387. common_() {}
  2388. void PushLine(char edit, const char* line) {
  2389. switch (edit) {
  2390. case ' ':
  2391. ++common_;
  2392. FlushEdits();
  2393. hunk_.push_back(std::make_pair(' ', line));
  2394. break;
  2395. case '-':
  2396. ++removes_;
  2397. hunk_removes_.push_back(std::make_pair('-', line));
  2398. break;
  2399. case '+':
  2400. ++adds_;
  2401. hunk_adds_.push_back(std::make_pair('+', line));
  2402. break;
  2403. }
  2404. }
  2405. void PrintTo(std::ostream* os) {
  2406. PrintHeader(os);
  2407. FlushEdits();
  2408. for (std::list<std::pair<char, const char*> >::const_iterator it =
  2409. hunk_.begin();
  2410. it != hunk_.end(); ++it) {
  2411. *os << it->first << it->second << "\n";
  2412. }
  2413. }
  2414. bool has_edits() const { return adds_ || removes_; }
  2415. private:
  2416. void FlushEdits() {
  2417. hunk_.splice(hunk_.end(), hunk_removes_);
  2418. hunk_.splice(hunk_.end(), hunk_adds_);
  2419. }
  2420. // Print a unified diff header for one hunk.
  2421. // The format is
  2422. // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
  2423. // where the left/right parts are omitted if unnecessary.
  2424. void PrintHeader(std::ostream* ss) const {
  2425. *ss << "@@ ";
  2426. if (removes_) {
  2427. *ss << "-" << left_start_ << "," << (removes_ + common_);
  2428. }
  2429. if (removes_ && adds_) {
  2430. *ss << " ";
  2431. }
  2432. if (adds_) {
  2433. *ss << "+" << right_start_ << "," << (adds_ + common_);
  2434. }
  2435. *ss << " @@\n";
  2436. }
  2437. size_t left_start_, right_start_;
  2438. size_t adds_, removes_, common_;
  2439. std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
  2440. };
  2441. } // namespace
  2442. // Create a list of diff hunks in Unified diff format.
  2443. // Each hunk has a header generated by PrintHeader above plus a body with
  2444. // lines prefixed with ' ' for no change, '-' for deletion and '+' for
  2445. // addition.
  2446. // 'context' represents the desired unchanged prefix/suffix around the diff.
  2447. // If two hunks are close enough that their contexts overlap, then they are
  2448. // joined into one hunk.
  2449. std::string CreateUnifiedDiff(const std::vector<std::string>& left,
  2450. const std::vector<std::string>& right,
  2451. size_t context) {
  2452. const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
  2453. size_t l_i = 0, r_i = 0, edit_i = 0;
  2454. std::stringstream ss;
  2455. while (edit_i < edits.size()) {
  2456. // Find first edit.
  2457. while (edit_i < edits.size() && edits[edit_i] == kMatch) {
  2458. ++l_i;
  2459. ++r_i;
  2460. ++edit_i;
  2461. }
  2462. // Find the first line to include in the hunk.
  2463. const size_t prefix_context = std::min(l_i, context);
  2464. Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
  2465. for (size_t i = prefix_context; i > 0; --i) {
  2466. hunk.PushLine(' ', left[l_i - i].c_str());
  2467. }
  2468. // Iterate the edits until we found enough suffix for the hunk or the input
  2469. // is over.
  2470. size_t n_suffix = 0;
  2471. for (; edit_i < edits.size(); ++edit_i) {
  2472. if (n_suffix >= context) {
  2473. // Continue only if the next hunk is very close.
  2474. auto it = edits.begin() + static_cast<int>(edit_i);
  2475. while (it != edits.end() && *it == kMatch) ++it;
  2476. if (it == edits.end() ||
  2477. static_cast<size_t>(it - edits.begin()) - edit_i >= context) {
  2478. // There is no next edit or it is too far away.
  2479. break;
  2480. }
  2481. }
  2482. EditType edit = edits[edit_i];
  2483. // Reset count when a non match is found.
  2484. n_suffix = edit == kMatch ? n_suffix + 1 : 0;
  2485. if (edit == kMatch || edit == kRemove || edit == kReplace) {
  2486. hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
  2487. }
  2488. if (edit == kAdd || edit == kReplace) {
  2489. hunk.PushLine('+', right[r_i].c_str());
  2490. }
  2491. // Advance indices, depending on edit type.
  2492. l_i += edit != kAdd;
  2493. r_i += edit != kRemove;
  2494. }
  2495. if (!hunk.has_edits()) {
  2496. // We are done. We don't want this hunk.
  2497. break;
  2498. }
  2499. hunk.PrintTo(&ss);
  2500. }
  2501. return ss.str();
  2502. }
  2503. } // namespace edit_distance
  2504. namespace {
  2505. // The string representation of the values received in EqFailure() are already
  2506. // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
  2507. // characters the same.
  2508. std::vector<std::string> SplitEscapedString(const std::string& str) {
  2509. std::vector<std::string> lines;
  2510. size_t start = 0, end = str.size();
  2511. if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
  2512. ++start;
  2513. --end;
  2514. }
  2515. bool escaped = false;
  2516. for (size_t i = start; i + 1 < end; ++i) {
  2517. if (escaped) {
  2518. escaped = false;
  2519. if (str[i] == 'n') {
  2520. lines.push_back(str.substr(start, i - start - 1));
  2521. start = i + 1;
  2522. }
  2523. } else {
  2524. escaped = str[i] == '\\';
  2525. }
  2526. }
  2527. lines.push_back(str.substr(start, end - start));
  2528. return lines;
  2529. }
  2530. } // namespace
  2531. // Constructs and returns the message for an equality assertion
  2532. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  2533. //
  2534. // The first four parameters are the expressions used in the assertion
  2535. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  2536. // where foo is 5 and bar is 6, we have:
  2537. //
  2538. // lhs_expression: "foo"
  2539. // rhs_expression: "bar"
  2540. // lhs_value: "5"
  2541. // rhs_value: "6"
  2542. //
  2543. // The ignoring_case parameter is true if and only if the assertion is a
  2544. // *_STRCASEEQ*. When it's true, the string "Ignoring case" will
  2545. // be inserted into the message.
  2546. AssertionResult EqFailure(const char* lhs_expression,
  2547. const char* rhs_expression,
  2548. const std::string& lhs_value,
  2549. const std::string& rhs_value,
  2550. bool ignoring_case) {
  2551. Message msg;
  2552. msg << "Expected equality of these values:";
  2553. msg << "\n " << lhs_expression;
  2554. if (lhs_value != lhs_expression) {
  2555. msg << "\n Which is: " << lhs_value;
  2556. }
  2557. msg << "\n " << rhs_expression;
  2558. if (rhs_value != rhs_expression) {
  2559. msg << "\n Which is: " << rhs_value;
  2560. }
  2561. if (ignoring_case) {
  2562. msg << "\nIgnoring case";
  2563. }
  2564. if (!lhs_value.empty() && !rhs_value.empty()) {
  2565. const std::vector<std::string> lhs_lines =
  2566. SplitEscapedString(lhs_value);
  2567. const std::vector<std::string> rhs_lines =
  2568. SplitEscapedString(rhs_value);
  2569. if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
  2570. msg << "\nWith diff:\n"
  2571. << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
  2572. }
  2573. }
  2574. return AssertionFailure() << msg;
  2575. }
  2576. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  2577. std::string GetBoolAssertionFailureMessage(
  2578. const AssertionResult& assertion_result,
  2579. const char* expression_text,
  2580. const char* actual_predicate_value,
  2581. const char* expected_predicate_value) {
  2582. const char* actual_message = assertion_result.message();
  2583. Message msg;
  2584. msg << "Value of: " << expression_text
  2585. << "\n Actual: " << actual_predicate_value;
  2586. if (actual_message[0] != '\0')
  2587. msg << " (" << actual_message << ")";
  2588. msg << "\nExpected: " << expected_predicate_value;
  2589. return msg.GetString();
  2590. }
  2591. // Helper function for implementing ASSERT_NEAR.
  2592. AssertionResult DoubleNearPredFormat(const char* expr1,
  2593. const char* expr2,
  2594. const char* abs_error_expr,
  2595. double val1,
  2596. double val2,
  2597. double abs_error) {
  2598. const double diff = fabs(val1 - val2);
  2599. if (diff <= abs_error) return AssertionSuccess();
  2600. // Find the value which is closest to zero.
  2601. const double min_abs = std::min(fabs(val1), fabs(val2));
  2602. // Find the distance to the next double from that value.
  2603. const double epsilon =
  2604. nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
  2605. // Detect the case where abs_error is so small that EXPECT_NEAR is
  2606. // effectively the same as EXPECT_EQUAL, and give an informative error
  2607. // message so that the situation can be more easily understood without
  2608. // requiring exotic floating-point knowledge.
  2609. // Don't do an epsilon check if abs_error is zero because that implies
  2610. // that an equality check was actually intended.
  2611. if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
  2612. abs_error < epsilon) {
  2613. return AssertionFailure()
  2614. << "The difference between " << expr1 << " and " << expr2 << " is "
  2615. << diff << ", where\n"
  2616. << expr1 << " evaluates to " << val1 << ",\n"
  2617. << expr2 << " evaluates to " << val2 << ".\nThe abs_error parameter "
  2618. << abs_error_expr << " evaluates to " << abs_error
  2619. << " which is smaller than the minimum distance between doubles for "
  2620. "numbers of this magnitude which is "
  2621. << epsilon
  2622. << ", thus making this EXPECT_NEAR check equivalent to "
  2623. "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
  2624. }
  2625. return AssertionFailure()
  2626. << "The difference between " << expr1 << " and " << expr2
  2627. << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
  2628. << expr1 << " evaluates to " << val1 << ",\n"
  2629. << expr2 << " evaluates to " << val2 << ", and\n"
  2630. << abs_error_expr << " evaluates to " << abs_error << ".";
  2631. }
  2632. // Helper template for implementing FloatLE() and DoubleLE().
  2633. template <typename RawType>
  2634. AssertionResult FloatingPointLE(const char* expr1,
  2635. const char* expr2,
  2636. RawType val1,
  2637. RawType val2) {
  2638. // Returns success if val1 is less than val2,
  2639. if (val1 < val2) {
  2640. return AssertionSuccess();
  2641. }
  2642. // or if val1 is almost equal to val2.
  2643. const FloatingPoint<RawType> lhs(val1), rhs(val2);
  2644. if (lhs.AlmostEquals(rhs)) {
  2645. return AssertionSuccess();
  2646. }
  2647. // Note that the above two checks will both fail if either val1 or
  2648. // val2 is NaN, as the IEEE floating-point standard requires that
  2649. // any predicate involving a NaN must return false.
  2650. ::std::stringstream val1_ss;
  2651. val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2652. << val1;
  2653. ::std::stringstream val2_ss;
  2654. val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2655. << val2;
  2656. return AssertionFailure()
  2657. << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
  2658. << " Actual: " << StringStreamToString(&val1_ss) << " vs "
  2659. << StringStreamToString(&val2_ss);
  2660. }
  2661. } // namespace internal
  2662. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2663. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2664. AssertionResult FloatLE(const char* expr1, const char* expr2,
  2665. float val1, float val2) {
  2666. return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
  2667. }
  2668. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2669. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2670. AssertionResult DoubleLE(const char* expr1, const char* expr2,
  2671. double val1, double val2) {
  2672. return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
  2673. }
  2674. namespace internal {
  2675. // The helper function for {ASSERT|EXPECT}_STREQ.
  2676. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  2677. const char* rhs_expression,
  2678. const char* lhs,
  2679. const char* rhs) {
  2680. if (String::CStringEquals(lhs, rhs)) {
  2681. return AssertionSuccess();
  2682. }
  2683. return EqFailure(lhs_expression,
  2684. rhs_expression,
  2685. PrintToString(lhs),
  2686. PrintToString(rhs),
  2687. false);
  2688. }
  2689. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  2690. AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
  2691. const char* rhs_expression,
  2692. const char* lhs,
  2693. const char* rhs) {
  2694. if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
  2695. return AssertionSuccess();
  2696. }
  2697. return EqFailure(lhs_expression,
  2698. rhs_expression,
  2699. PrintToString(lhs),
  2700. PrintToString(rhs),
  2701. true);
  2702. }
  2703. // The helper function for {ASSERT|EXPECT}_STRNE.
  2704. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  2705. const char* s2_expression,
  2706. const char* s1,
  2707. const char* s2) {
  2708. if (!String::CStringEquals(s1, s2)) {
  2709. return AssertionSuccess();
  2710. } else {
  2711. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  2712. << s2_expression << "), actual: \""
  2713. << s1 << "\" vs \"" << s2 << "\"";
  2714. }
  2715. }
  2716. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  2717. AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  2718. const char* s2_expression,
  2719. const char* s1,
  2720. const char* s2) {
  2721. if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
  2722. return AssertionSuccess();
  2723. } else {
  2724. return AssertionFailure()
  2725. << "Expected: (" << s1_expression << ") != ("
  2726. << s2_expression << ") (ignoring case), actual: \""
  2727. << s1 << "\" vs \"" << s2 << "\"";
  2728. }
  2729. }
  2730. } // namespace internal
  2731. namespace {
  2732. // Helper functions for implementing IsSubString() and IsNotSubstring().
  2733. // This group of overloaded functions return true if and only if needle
  2734. // is a substring of haystack. NULL is considered a substring of
  2735. // itself only.
  2736. bool IsSubstringPred(const char* needle, const char* haystack) {
  2737. if (needle == nullptr || haystack == nullptr) return needle == haystack;
  2738. return strstr(haystack, needle) != nullptr;
  2739. }
  2740. bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
  2741. if (needle == nullptr || haystack == nullptr) return needle == haystack;
  2742. return wcsstr(haystack, needle) != nullptr;
  2743. }
  2744. // StringType here can be either ::std::string or ::std::wstring.
  2745. template <typename StringType>
  2746. bool IsSubstringPred(const StringType& needle,
  2747. const StringType& haystack) {
  2748. return haystack.find(needle) != StringType::npos;
  2749. }
  2750. // This function implements either IsSubstring() or IsNotSubstring(),
  2751. // depending on the value of the expected_to_be_substring parameter.
  2752. // StringType here can be const char*, const wchar_t*, ::std::string,
  2753. // or ::std::wstring.
  2754. template <typename StringType>
  2755. AssertionResult IsSubstringImpl(
  2756. bool expected_to_be_substring,
  2757. const char* needle_expr, const char* haystack_expr,
  2758. const StringType& needle, const StringType& haystack) {
  2759. if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
  2760. return AssertionSuccess();
  2761. const bool is_wide_string = sizeof(needle[0]) > 1;
  2762. const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
  2763. return AssertionFailure()
  2764. << "Value of: " << needle_expr << "\n"
  2765. << " Actual: " << begin_string_quote << needle << "\"\n"
  2766. << "Expected: " << (expected_to_be_substring ? "" : "not ")
  2767. << "a substring of " << haystack_expr << "\n"
  2768. << "Which is: " << begin_string_quote << haystack << "\"";
  2769. }
  2770. } // namespace
  2771. // IsSubstring() and IsNotSubstring() check whether needle is a
  2772. // substring of haystack (NULL is considered a substring of itself
  2773. // only), and return an appropriate error message when they fail.
  2774. AssertionResult IsSubstring(
  2775. const char* needle_expr, const char* haystack_expr,
  2776. const char* needle, const char* haystack) {
  2777. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2778. }
  2779. AssertionResult IsSubstring(
  2780. const char* needle_expr, const char* haystack_expr,
  2781. const wchar_t* needle, const wchar_t* haystack) {
  2782. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2783. }
  2784. AssertionResult IsNotSubstring(
  2785. const char* needle_expr, const char* haystack_expr,
  2786. const char* needle, const char* haystack) {
  2787. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2788. }
  2789. AssertionResult IsNotSubstring(
  2790. const char* needle_expr, const char* haystack_expr,
  2791. const wchar_t* needle, const wchar_t* haystack) {
  2792. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2793. }
  2794. AssertionResult IsSubstring(
  2795. const char* needle_expr, const char* haystack_expr,
  2796. const ::std::string& needle, const ::std::string& haystack) {
  2797. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2798. }
  2799. AssertionResult IsNotSubstring(
  2800. const char* needle_expr, const char* haystack_expr,
  2801. const ::std::string& needle, const ::std::string& haystack) {
  2802. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2803. }
  2804. #if GTEST_HAS_STD_WSTRING
  2805. AssertionResult IsSubstring(
  2806. const char* needle_expr, const char* haystack_expr,
  2807. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2808. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2809. }
  2810. AssertionResult IsNotSubstring(
  2811. const char* needle_expr, const char* haystack_expr,
  2812. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2813. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2814. }
  2815. #endif // GTEST_HAS_STD_WSTRING
  2816. namespace internal {
  2817. #if GTEST_OS_WINDOWS
  2818. namespace {
  2819. // Helper function for IsHRESULT{SuccessFailure} predicates
  2820. AssertionResult HRESULTFailureHelper(const char* expr,
  2821. const char* expected,
  2822. long hr) { // NOLINT
  2823. # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
  2824. // Windows CE doesn't support FormatMessage.
  2825. const char error_text[] = "";
  2826. # else
  2827. // Looks up the human-readable system message for the HRESULT code
  2828. // and since we're not passing any params to FormatMessage, we don't
  2829. // want inserts expanded.
  2830. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
  2831. FORMAT_MESSAGE_IGNORE_INSERTS;
  2832. const DWORD kBufSize = 4096;
  2833. // Gets the system's human readable message string for this HRESULT.
  2834. char error_text[kBufSize] = { '\0' };
  2835. DWORD message_length = ::FormatMessageA(kFlags,
  2836. 0, // no source, we're asking system
  2837. static_cast<DWORD>(hr), // the error
  2838. 0, // no line width restrictions
  2839. error_text, // output buffer
  2840. kBufSize, // buf size
  2841. nullptr); // no arguments for inserts
  2842. // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
  2843. for (; message_length && IsSpace(error_text[message_length - 1]);
  2844. --message_length) {
  2845. error_text[message_length - 1] = '\0';
  2846. }
  2847. # endif // GTEST_OS_WINDOWS_MOBILE
  2848. const std::string error_hex("0x" + String::FormatHexInt(hr));
  2849. return ::testing::AssertionFailure()
  2850. << "Expected: " << expr << " " << expected << ".\n"
  2851. << " Actual: " << error_hex << " " << error_text << "\n";
  2852. }
  2853. } // namespace
  2854. AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
  2855. if (SUCCEEDED(hr)) {
  2856. return AssertionSuccess();
  2857. }
  2858. return HRESULTFailureHelper(expr, "succeeds", hr);
  2859. }
  2860. AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
  2861. if (FAILED(hr)) {
  2862. return AssertionSuccess();
  2863. }
  2864. return HRESULTFailureHelper(expr, "fails", hr);
  2865. }
  2866. #endif // GTEST_OS_WINDOWS
  2867. // Utility functions for encoding Unicode text (wide strings) in
  2868. // UTF-8.
  2869. // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
  2870. // like this:
  2871. //
  2872. // Code-point length Encoding
  2873. // 0 - 7 bits 0xxxxxxx
  2874. // 8 - 11 bits 110xxxxx 10xxxxxx
  2875. // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
  2876. // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  2877. // The maximum code-point a one-byte UTF-8 sequence can represent.
  2878. constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1;
  2879. // The maximum code-point a two-byte UTF-8 sequence can represent.
  2880. constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1;
  2881. // The maximum code-point a three-byte UTF-8 sequence can represent.
  2882. constexpr uint32_t kMaxCodePoint3 = (static_cast<uint32_t>(1) << (4 + 2*6)) - 1;
  2883. // The maximum code-point a four-byte UTF-8 sequence can represent.
  2884. constexpr uint32_t kMaxCodePoint4 = (static_cast<uint32_t>(1) << (3 + 3*6)) - 1;
  2885. // Chops off the n lowest bits from a bit pattern. Returns the n
  2886. // lowest bits. As a side effect, the original bit pattern will be
  2887. // shifted to the right by n bits.
  2888. inline uint32_t ChopLowBits(uint32_t* bits, int n) {
  2889. const uint32_t low_bits = *bits & ((static_cast<uint32_t>(1) << n) - 1);
  2890. *bits >>= n;
  2891. return low_bits;
  2892. }
  2893. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  2894. // code_point parameter is of type uint32_t because wchar_t may not be
  2895. // wide enough to contain a code point.
  2896. // If the code_point is not a valid Unicode code point
  2897. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  2898. // to "(Invalid Unicode 0xXXXXXXXX)".
  2899. std::string CodePointToUtf8(uint32_t code_point) {
  2900. if (code_point > kMaxCodePoint4) {
  2901. return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")";
  2902. }
  2903. char str[5]; // Big enough for the largest valid code point.
  2904. if (code_point <= kMaxCodePoint1) {
  2905. str[1] = '\0';
  2906. str[0] = static_cast<char>(code_point); // 0xxxxxxx
  2907. } else if (code_point <= kMaxCodePoint2) {
  2908. str[2] = '\0';
  2909. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2910. str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
  2911. } else if (code_point <= kMaxCodePoint3) {
  2912. str[3] = '\0';
  2913. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2914. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2915. str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
  2916. } else { // code_point <= kMaxCodePoint4
  2917. str[4] = '\0';
  2918. str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2919. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2920. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2921. str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
  2922. }
  2923. return str;
  2924. }
  2925. // The following two functions only make sense if the system
  2926. // uses UTF-16 for wide string encoding. All supported systems
  2927. // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
  2928. // Determines if the arguments constitute UTF-16 surrogate pair
  2929. // and thus should be combined into a single Unicode code point
  2930. // using CreateCodePointFromUtf16SurrogatePair.
  2931. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
  2932. return sizeof(wchar_t) == 2 &&
  2933. (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
  2934. }
  2935. // Creates a Unicode code point from UTF16 surrogate pair.
  2936. inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first,
  2937. wchar_t second) {
  2938. const auto first_u = static_cast<uint32_t>(first);
  2939. const auto second_u = static_cast<uint32_t>(second);
  2940. const uint32_t mask = (1 << 10) - 1;
  2941. return (sizeof(wchar_t) == 2)
  2942. ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
  2943. :
  2944. // This function should not be called when the condition is
  2945. // false, but we provide a sensible default in case it is.
  2946. first_u;
  2947. }
  2948. // Converts a wide string to a narrow string in UTF-8 encoding.
  2949. // The wide string is assumed to have the following encoding:
  2950. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
  2951. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  2952. // Parameter str points to a null-terminated wide string.
  2953. // Parameter num_chars may additionally limit the number
  2954. // of wchar_t characters processed. -1 is used when the entire string
  2955. // should be processed.
  2956. // If the string contains code points that are not valid Unicode code points
  2957. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  2958. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  2959. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  2960. // will be encoded as individual Unicode characters from Basic Normal Plane.
  2961. std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
  2962. if (num_chars == -1)
  2963. num_chars = static_cast<int>(wcslen(str));
  2964. ::std::stringstream stream;
  2965. for (int i = 0; i < num_chars; ++i) {
  2966. uint32_t unicode_code_point;
  2967. if (str[i] == L'\0') {
  2968. break;
  2969. } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
  2970. unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
  2971. str[i + 1]);
  2972. i++;
  2973. } else {
  2974. unicode_code_point = static_cast<uint32_t>(str[i]);
  2975. }
  2976. stream << CodePointToUtf8(unicode_code_point);
  2977. }
  2978. return StringStreamToString(&stream);
  2979. }
  2980. // Converts a wide C string to an std::string using the UTF-8 encoding.
  2981. // NULL will be converted to "(null)".
  2982. std::string String::ShowWideCString(const wchar_t * wide_c_str) {
  2983. if (wide_c_str == nullptr) return "(null)";
  2984. return internal::WideStringToUtf8(wide_c_str, -1);
  2985. }
  2986. // Compares two wide C strings. Returns true if and only if they have the
  2987. // same content.
  2988. //
  2989. // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
  2990. // C string is considered different to any non-NULL C string,
  2991. // including the empty string.
  2992. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
  2993. if (lhs == nullptr) return rhs == nullptr;
  2994. if (rhs == nullptr) return false;
  2995. return wcscmp(lhs, rhs) == 0;
  2996. }
  2997. // Helper function for *_STREQ on wide strings.
  2998. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  2999. const char* rhs_expression,
  3000. const wchar_t* lhs,
  3001. const wchar_t* rhs) {
  3002. if (String::WideCStringEquals(lhs, rhs)) {
  3003. return AssertionSuccess();
  3004. }
  3005. return EqFailure(lhs_expression,
  3006. rhs_expression,
  3007. PrintToString(lhs),
  3008. PrintToString(rhs),
  3009. false);
  3010. }
  3011. // Helper function for *_STRNE on wide strings.
  3012. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  3013. const char* s2_expression,
  3014. const wchar_t* s1,
  3015. const wchar_t* s2) {
  3016. if (!String::WideCStringEquals(s1, s2)) {
  3017. return AssertionSuccess();
  3018. }
  3019. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  3020. << s2_expression << "), actual: "
  3021. << PrintToString(s1)
  3022. << " vs " << PrintToString(s2);
  3023. }
  3024. // Compares two C strings, ignoring case. Returns true if and only if they have
  3025. // the same content.
  3026. //
  3027. // Unlike strcasecmp(), this function can handle NULL argument(s). A
  3028. // NULL C string is considered different to any non-NULL C string,
  3029. // including the empty string.
  3030. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
  3031. if (lhs == nullptr) return rhs == nullptr;
  3032. if (rhs == nullptr) return false;
  3033. return posix::StrCaseCmp(lhs, rhs) == 0;
  3034. }
  3035. // Compares two wide C strings, ignoring case. Returns true if and only if they
  3036. // have the same content.
  3037. //
  3038. // Unlike wcscasecmp(), this function can handle NULL argument(s).
  3039. // A NULL C string is considered different to any non-NULL wide C string,
  3040. // including the empty string.
  3041. // NB: The implementations on different platforms slightly differ.
  3042. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  3043. // environment variable. On GNU platform this method uses wcscasecmp
  3044. // which compares according to LC_CTYPE category of the current locale.
  3045. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  3046. // current locale.
  3047. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  3048. const wchar_t* rhs) {
  3049. if (lhs == nullptr) return rhs == nullptr;
  3050. if (rhs == nullptr) return false;
  3051. #if GTEST_OS_WINDOWS
  3052. return _wcsicmp(lhs, rhs) == 0;
  3053. #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
  3054. return wcscasecmp(lhs, rhs) == 0;
  3055. #else
  3056. // Android, Mac OS X and Cygwin don't define wcscasecmp.
  3057. // Other unknown OSes may not define it either.
  3058. wint_t left, right;
  3059. do {
  3060. left = towlower(static_cast<wint_t>(*lhs++));
  3061. right = towlower(static_cast<wint_t>(*rhs++));
  3062. } while (left && left == right);
  3063. return left == right;
  3064. #endif // OS selector
  3065. }
  3066. // Returns true if and only if str ends with the given suffix, ignoring case.
  3067. // Any string is considered to end with an empty suffix.
  3068. bool String::EndsWithCaseInsensitive(
  3069. const std::string& str, const std::string& suffix) {
  3070. const size_t str_len = str.length();
  3071. const size_t suffix_len = suffix.length();
  3072. return (str_len >= suffix_len) &&
  3073. CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
  3074. suffix.c_str());
  3075. }
  3076. // Formats an int value as "%02d".
  3077. std::string String::FormatIntWidth2(int value) {
  3078. return FormatIntWidthN(value, 2);
  3079. }
  3080. // Formats an int value to given width with leading zeros.
  3081. std::string String::FormatIntWidthN(int value, int width) {
  3082. std::stringstream ss;
  3083. ss << std::setfill('0') << std::setw(width) << value;
  3084. return ss.str();
  3085. }
  3086. // Formats an int value as "%X".
  3087. std::string String::FormatHexUInt32(uint32_t value) {
  3088. std::stringstream ss;
  3089. ss << std::hex << std::uppercase << value;
  3090. return ss.str();
  3091. }
  3092. // Formats an int value as "%X".
  3093. std::string String::FormatHexInt(int value) {
  3094. return FormatHexUInt32(static_cast<uint32_t>(value));
  3095. }
  3096. // Formats a byte as "%02X".
  3097. std::string String::FormatByte(unsigned char value) {
  3098. std::stringstream ss;
  3099. ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
  3100. << static_cast<unsigned int>(value);
  3101. return ss.str();
  3102. }
  3103. // Converts the buffer in a stringstream to an std::string, converting NUL
  3104. // bytes to "\\0" along the way.
  3105. std::string StringStreamToString(::std::stringstream* ss) {
  3106. const ::std::string& str = ss->str();
  3107. const char* const start = str.c_str();
  3108. const char* const end = start + str.length();
  3109. std::string result;
  3110. result.reserve(static_cast<size_t>(2 * (end - start)));
  3111. for (const char* ch = start; ch != end; ++ch) {
  3112. if (*ch == '\0') {
  3113. result += "\\0"; // Replaces NUL with "\\0";
  3114. } else {
  3115. result += *ch;
  3116. }
  3117. }
  3118. return result;
  3119. }
  3120. // Appends the user-supplied message to the Google-Test-generated message.
  3121. std::string AppendUserMessage(const std::string& gtest_msg,
  3122. const Message& user_msg) {
  3123. // Appends the user message if it's non-empty.
  3124. const std::string user_msg_string = user_msg.GetString();
  3125. if (user_msg_string.empty()) {
  3126. return gtest_msg;
  3127. }
  3128. if (gtest_msg.empty()) {
  3129. return user_msg_string;
  3130. }
  3131. return gtest_msg + "\n" + user_msg_string;
  3132. }
  3133. } // namespace internal
  3134. // class TestResult
  3135. // Creates an empty TestResult.
  3136. TestResult::TestResult()
  3137. : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
  3138. // D'tor.
  3139. TestResult::~TestResult() {
  3140. }
  3141. // Returns the i-th test part result among all the results. i can
  3142. // range from 0 to total_part_count() - 1. If i is not in that range,
  3143. // aborts the program.
  3144. const TestPartResult& TestResult::GetTestPartResult(int i) const {
  3145. if (i < 0 || i >= total_part_count())
  3146. internal::posix::Abort();
  3147. return test_part_results_.at(static_cast<size_t>(i));
  3148. }
  3149. // Returns the i-th test property. i can range from 0 to
  3150. // test_property_count() - 1. If i is not in that range, aborts the
  3151. // program.
  3152. const TestProperty& TestResult::GetTestProperty(int i) const {
  3153. if (i < 0 || i >= test_property_count())
  3154. internal::posix::Abort();
  3155. return test_properties_.at(static_cast<size_t>(i));
  3156. }
  3157. // Clears the test part results.
  3158. void TestResult::ClearTestPartResults() {
  3159. test_part_results_.clear();
  3160. }
  3161. // Adds a test part result to the list.
  3162. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
  3163. test_part_results_.push_back(test_part_result);
  3164. }
  3165. // Adds a test property to the list. If a property with the same key as the
  3166. // supplied property is already represented, the value of this test_property
  3167. // replaces the old value for that key.
  3168. void TestResult::RecordProperty(const std::string& xml_element,
  3169. const TestProperty& test_property) {
  3170. if (!ValidateTestProperty(xml_element, test_property)) {
  3171. return;
  3172. }
  3173. internal::MutexLock lock(&test_properties_mutex_);
  3174. const std::vector<TestProperty>::iterator property_with_matching_key =
  3175. std::find_if(test_properties_.begin(), test_properties_.end(),
  3176. internal::TestPropertyKeyIs(test_property.key()));
  3177. if (property_with_matching_key == test_properties_.end()) {
  3178. test_properties_.push_back(test_property);
  3179. return;
  3180. }
  3181. property_with_matching_key->SetValue(test_property.value());
  3182. }
  3183. // The list of reserved attributes used in the <testsuites> element of XML
  3184. // output.
  3185. static const char* const kReservedTestSuitesAttributes[] = {
  3186. "disabled",
  3187. "errors",
  3188. "failures",
  3189. "name",
  3190. "random_seed",
  3191. "tests",
  3192. "time",
  3193. "timestamp"
  3194. };
  3195. // The list of reserved attributes used in the <testsuite> element of XML
  3196. // output.
  3197. static const char* const kReservedTestSuiteAttributes[] = {
  3198. "disabled", "errors", "failures", "name",
  3199. "tests", "time", "timestamp", "skipped"};
  3200. // The list of reserved attributes used in the <testcase> element of XML output.
  3201. static const char* const kReservedTestCaseAttributes[] = {
  3202. "classname", "name", "status", "time", "type_param",
  3203. "value_param", "file", "line"};
  3204. // Use a slightly different set for allowed output to ensure existing tests can
  3205. // still RecordProperty("result") or "RecordProperty(timestamp")
  3206. static const char* const kReservedOutputTestCaseAttributes[] = {
  3207. "classname", "name", "status", "time", "type_param",
  3208. "value_param", "file", "line", "result", "timestamp"};
  3209. template <size_t kSize>
  3210. std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
  3211. return std::vector<std::string>(array, array + kSize);
  3212. }
  3213. static std::vector<std::string> GetReservedAttributesForElement(
  3214. const std::string& xml_element) {
  3215. if (xml_element == "testsuites") {
  3216. return ArrayAsVector(kReservedTestSuitesAttributes);
  3217. } else if (xml_element == "testsuite") {
  3218. return ArrayAsVector(kReservedTestSuiteAttributes);
  3219. } else if (xml_element == "testcase") {
  3220. return ArrayAsVector(kReservedTestCaseAttributes);
  3221. } else {
  3222. GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
  3223. }
  3224. // This code is unreachable but some compilers may not realizes that.
  3225. return std::vector<std::string>();
  3226. }
  3227. // TODO(jdesprez): Merge the two getReserved attributes once skip is improved
  3228. static std::vector<std::string> GetReservedOutputAttributesForElement(
  3229. const std::string& xml_element) {
  3230. if (xml_element == "testsuites") {
  3231. return ArrayAsVector(kReservedTestSuitesAttributes);
  3232. } else if (xml_element == "testsuite") {
  3233. return ArrayAsVector(kReservedTestSuiteAttributes);
  3234. } else if (xml_element == "testcase") {
  3235. return ArrayAsVector(kReservedOutputTestCaseAttributes);
  3236. } else {
  3237. GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
  3238. }
  3239. // This code is unreachable but some compilers may not realizes that.
  3240. return std::vector<std::string>();
  3241. }
  3242. static std::string FormatWordList(const std::vector<std::string>& words) {
  3243. Message word_list;
  3244. for (size_t i = 0; i < words.size(); ++i) {
  3245. if (i > 0 && words.size() > 2) {
  3246. word_list << ", ";
  3247. }
  3248. if (i == words.size() - 1) {
  3249. word_list << "and ";
  3250. }
  3251. word_list << "'" << words[i] << "'";
  3252. }
  3253. return word_list.GetString();
  3254. }
  3255. static bool ValidateTestPropertyName(
  3256. const std::string& property_name,
  3257. const std::vector<std::string>& reserved_names) {
  3258. if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
  3259. reserved_names.end()) {
  3260. ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
  3261. << " (" << FormatWordList(reserved_names)
  3262. << " are reserved by " << GTEST_NAME_ << ")";
  3263. return false;
  3264. }
  3265. return true;
  3266. }
  3267. // Adds a failure if the key is a reserved attribute of the element named
  3268. // xml_element. Returns true if the property is valid.
  3269. bool TestResult::ValidateTestProperty(const std::string& xml_element,
  3270. const TestProperty& test_property) {
  3271. return ValidateTestPropertyName(test_property.key(),
  3272. GetReservedAttributesForElement(xml_element));
  3273. }
  3274. // Clears the object.
  3275. void TestResult::Clear() {
  3276. test_part_results_.clear();
  3277. test_properties_.clear();
  3278. death_test_count_ = 0;
  3279. elapsed_time_ = 0;
  3280. }
  3281. // Returns true off the test part was skipped.
  3282. static bool TestPartSkipped(const TestPartResult& result) {
  3283. return result.skipped();
  3284. }
  3285. // Returns true if and only if the test was skipped.
  3286. bool TestResult::Skipped() const {
  3287. return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
  3288. }
  3289. // Returns true if and only if the test failed.
  3290. bool TestResult::Failed() const {
  3291. for (int i = 0; i < total_part_count(); ++i) {
  3292. if (GetTestPartResult(i).failed())
  3293. return true;
  3294. }
  3295. return false;
  3296. }
  3297. // Returns true if and only if the test part fatally failed.
  3298. static bool TestPartFatallyFailed(const TestPartResult& result) {
  3299. return result.fatally_failed();
  3300. }
  3301. // Returns true if and only if the test fatally failed.
  3302. bool TestResult::HasFatalFailure() const {
  3303. return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
  3304. }
  3305. // Returns true if and only if the test part non-fatally failed.
  3306. static bool TestPartNonfatallyFailed(const TestPartResult& result) {
  3307. return result.nonfatally_failed();
  3308. }
  3309. // Returns true if and only if the test has a non-fatal failure.
  3310. bool TestResult::HasNonfatalFailure() const {
  3311. return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
  3312. }
  3313. // Gets the number of all test parts. This is the sum of the number
  3314. // of successful test parts and the number of failed test parts.
  3315. int TestResult::total_part_count() const {
  3316. return static_cast<int>(test_part_results_.size());
  3317. }
  3318. // Returns the number of the test properties.
  3319. int TestResult::test_property_count() const {
  3320. return static_cast<int>(test_properties_.size());
  3321. }
  3322. // class Test
  3323. // Creates a Test object.
  3324. // The c'tor saves the states of all flags.
  3325. Test::Test()
  3326. : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
  3327. }
  3328. // The d'tor restores the states of all flags. The actual work is
  3329. // done by the d'tor of the gtest_flag_saver_ field, and thus not
  3330. // visible here.
  3331. Test::~Test() {
  3332. }
  3333. // Sets up the test fixture.
  3334. //
  3335. // A sub-class may override this.
  3336. void Test::SetUp() {
  3337. }
  3338. // Tears down the test fixture.
  3339. //
  3340. // A sub-class may override this.
  3341. void Test::TearDown() {
  3342. }
  3343. // Allows user supplied key value pairs to be recorded for later output.
  3344. void Test::RecordProperty(const std::string& key, const std::string& value) {
  3345. UnitTest::GetInstance()->RecordProperty(key, value);
  3346. }
  3347. // Allows user supplied key value pairs to be recorded for later output.
  3348. void Test::RecordProperty(const std::string& key, int value) {
  3349. Message value_message;
  3350. value_message << value;
  3351. RecordProperty(key, value_message.GetString().c_str());
  3352. }
  3353. namespace internal {
  3354. void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  3355. const std::string& message) {
  3356. // This function is a friend of UnitTest and as such has access to
  3357. // AddTestPartResult.
  3358. UnitTest::GetInstance()->AddTestPartResult(
  3359. result_type,
  3360. nullptr, // No info about the source file where the exception occurred.
  3361. -1, // We have no info on which line caused the exception.
  3362. message,
  3363. ""); // No stack trace, either.
  3364. }
  3365. } // namespace internal
  3366. // Google Test requires all tests in the same test suite to use the same test
  3367. // fixture class. This function checks if the current test has the
  3368. // same fixture class as the first test in the current test suite. If
  3369. // yes, it returns true; otherwise it generates a Google Test failure and
  3370. // returns false.
  3371. bool Test::HasSameFixtureClass() {
  3372. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3373. const TestSuite* const test_suite = impl->current_test_suite();
  3374. // Info about the first test in the current test suite.
  3375. const TestInfo* const first_test_info = test_suite->test_info_list()[0];
  3376. const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
  3377. const char* const first_test_name = first_test_info->name();
  3378. // Info about the current test.
  3379. const TestInfo* const this_test_info = impl->current_test_info();
  3380. const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
  3381. const char* const this_test_name = this_test_info->name();
  3382. if (this_fixture_id != first_fixture_id) {
  3383. // Is the first test defined using TEST?
  3384. const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
  3385. // Is this test defined using TEST?
  3386. const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
  3387. if (first_is_TEST || this_is_TEST) {
  3388. // Both TEST and TEST_F appear in same test suite, which is incorrect.
  3389. // Tell the user how to fix this.
  3390. // Gets the name of the TEST and the name of the TEST_F. Note
  3391. // that first_is_TEST and this_is_TEST cannot both be true, as
  3392. // the fixture IDs are different for the two tests.
  3393. const char* const TEST_name =
  3394. first_is_TEST ? first_test_name : this_test_name;
  3395. const char* const TEST_F_name =
  3396. first_is_TEST ? this_test_name : first_test_name;
  3397. ADD_FAILURE()
  3398. << "All tests in the same test suite must use the same test fixture\n"
  3399. << "class, so mixing TEST_F and TEST in the same test suite is\n"
  3400. << "illegal. In test suite " << this_test_info->test_suite_name()
  3401. << ",\n"
  3402. << "test " << TEST_F_name << " is defined using TEST_F but\n"
  3403. << "test " << TEST_name << " is defined using TEST. You probably\n"
  3404. << "want to change the TEST to TEST_F or move it to another test\n"
  3405. << "case.";
  3406. } else {
  3407. // Two fixture classes with the same name appear in two different
  3408. // namespaces, which is not allowed. Tell the user how to fix this.
  3409. ADD_FAILURE()
  3410. << "All tests in the same test suite must use the same test fixture\n"
  3411. << "class. However, in test suite "
  3412. << this_test_info->test_suite_name() << ",\n"
  3413. << "you defined test " << first_test_name << " and test "
  3414. << this_test_name << "\n"
  3415. << "using two different test fixture classes. This can happen if\n"
  3416. << "the two classes are from different namespaces or translation\n"
  3417. << "units and have the same name. You should probably rename one\n"
  3418. << "of the classes to put the tests into different test suites.";
  3419. }
  3420. return false;
  3421. }
  3422. return true;
  3423. }
  3424. #if GTEST_HAS_SEH
  3425. // Adds an "exception thrown" fatal failure to the current test. This
  3426. // function returns its result via an output parameter pointer because VC++
  3427. // prohibits creation of objects with destructors on stack in functions
  3428. // using __try (see error C2712).
  3429. static std::string* FormatSehExceptionMessage(DWORD exception_code,
  3430. const char* location) {
  3431. Message message;
  3432. message << "SEH exception with code 0x" << std::setbase(16) <<
  3433. exception_code << std::setbase(10) << " thrown in " << location << ".";
  3434. return new std::string(message.GetString());
  3435. }
  3436. #endif // GTEST_HAS_SEH
  3437. namespace internal {
  3438. #if GTEST_HAS_EXCEPTIONS
  3439. // Adds an "exception thrown" fatal failure to the current test.
  3440. static std::string FormatCxxExceptionMessage(const char* description,
  3441. const char* location) {
  3442. Message message;
  3443. if (description != nullptr) {
  3444. message << "C++ exception with description \"" << description << "\"";
  3445. } else {
  3446. message << "Unknown C++ exception";
  3447. }
  3448. message << " thrown in " << location << ".";
  3449. return message.GetString();
  3450. }
  3451. static std::string PrintTestPartResultToString(
  3452. const TestPartResult& test_part_result);
  3453. GoogleTestFailureException::GoogleTestFailureException(
  3454. const TestPartResult& failure)
  3455. : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
  3456. #endif // GTEST_HAS_EXCEPTIONS
  3457. // We put these helper functions in the internal namespace as IBM's xlC
  3458. // compiler rejects the code if they were declared static.
  3459. // Runs the given method and handles SEH exceptions it throws, when
  3460. // SEH is supported; returns the 0-value for type Result in case of an
  3461. // SEH exception. (Microsoft compilers cannot handle SEH and C++
  3462. // exceptions in the same function. Therefore, we provide a separate
  3463. // wrapper function for handling SEH exceptions.)
  3464. template <class T, typename Result>
  3465. Result HandleSehExceptionsInMethodIfSupported(
  3466. T* object, Result (T::*method)(), const char* location) {
  3467. #if GTEST_HAS_SEH
  3468. __try {
  3469. return (object->*method)();
  3470. } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
  3471. GetExceptionCode())) {
  3472. // We create the exception message on the heap because VC++ prohibits
  3473. // creation of objects with destructors on stack in functions using __try
  3474. // (see error C2712).
  3475. std::string* exception_message = FormatSehExceptionMessage(
  3476. GetExceptionCode(), location);
  3477. internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
  3478. *exception_message);
  3479. delete exception_message;
  3480. return static_cast<Result>(0);
  3481. }
  3482. #else
  3483. (void)location;
  3484. return (object->*method)();
  3485. #endif // GTEST_HAS_SEH
  3486. }
  3487. // Runs the given method and catches and reports C++ and/or SEH-style
  3488. // exceptions, if they are supported; returns the 0-value for type
  3489. // Result in case of an SEH exception.
  3490. template <class T, typename Result>
  3491. Result HandleExceptionsInMethodIfSupported(
  3492. T* object, Result (T::*method)(), const char* location) {
  3493. // NOTE: The user code can affect the way in which Google Test handles
  3494. // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
  3495. // RUN_ALL_TESTS() starts. It is technically possible to check the flag
  3496. // after the exception is caught and either report or re-throw the
  3497. // exception based on the flag's value:
  3498. //
  3499. // try {
  3500. // // Perform the test method.
  3501. // } catch (...) {
  3502. // if (GTEST_FLAG(catch_exceptions))
  3503. // // Report the exception as failure.
  3504. // else
  3505. // throw; // Re-throws the original exception.
  3506. // }
  3507. //
  3508. // However, the purpose of this flag is to allow the program to drop into
  3509. // the debugger when the exception is thrown. On most platforms, once the
  3510. // control enters the catch block, the exception origin information is
  3511. // lost and the debugger will stop the program at the point of the
  3512. // re-throw in this function -- instead of at the point of the original
  3513. // throw statement in the code under test. For this reason, we perform
  3514. // the check early, sacrificing the ability to affect Google Test's
  3515. // exception handling in the method where the exception is thrown.
  3516. if (internal::GetUnitTestImpl()->catch_exceptions()) {
  3517. #if GTEST_HAS_EXCEPTIONS
  3518. try {
  3519. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  3520. } catch (const AssertionException&) { // NOLINT
  3521. // This failure was reported already.
  3522. } catch (const internal::GoogleTestFailureException&) { // NOLINT
  3523. // This exception type can only be thrown by a failed Google
  3524. // Test assertion with the intention of letting another testing
  3525. // framework catch it. Therefore we just re-throw it.
  3526. throw;
  3527. } catch (const std::exception& e) { // NOLINT
  3528. internal::ReportFailureInUnknownLocation(
  3529. TestPartResult::kFatalFailure,
  3530. FormatCxxExceptionMessage(e.what(), location));
  3531. } catch (...) { // NOLINT
  3532. internal::ReportFailureInUnknownLocation(
  3533. TestPartResult::kFatalFailure,
  3534. FormatCxxExceptionMessage(nullptr, location));
  3535. }
  3536. return static_cast<Result>(0);
  3537. #else
  3538. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  3539. #endif // GTEST_HAS_EXCEPTIONS
  3540. } else {
  3541. return (object->*method)();
  3542. }
  3543. }
  3544. } // namespace internal
  3545. // Runs the test and updates the test result.
  3546. void Test::Run() {
  3547. if (!HasSameFixtureClass()) return;
  3548. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3549. impl->os_stack_trace_getter()->UponLeavingGTest();
  3550. internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
  3551. // We will run the test only if SetUp() was successful and didn't call
  3552. // GTEST_SKIP().
  3553. if (!HasFatalFailure() && !IsSkipped()) {
  3554. impl->os_stack_trace_getter()->UponLeavingGTest();
  3555. internal::HandleExceptionsInMethodIfSupported(
  3556. this, &Test::TestBody, "the test body");
  3557. }
  3558. // However, we want to clean up as much as possible. Hence we will
  3559. // always call TearDown(), even if SetUp() or the test body has
  3560. // failed.
  3561. impl->os_stack_trace_getter()->UponLeavingGTest();
  3562. internal::HandleExceptionsInMethodIfSupported(
  3563. this, &Test::TearDown, "TearDown()");
  3564. }
  3565. // Returns true if and only if the current test has a fatal failure.
  3566. bool Test::HasFatalFailure() {
  3567. return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
  3568. }
  3569. // Returns true if and only if the current test has a non-fatal failure.
  3570. bool Test::HasNonfatalFailure() {
  3571. return internal::GetUnitTestImpl()->current_test_result()->
  3572. HasNonfatalFailure();
  3573. }
  3574. // Returns true if and only if the current test was skipped.
  3575. bool Test::IsSkipped() {
  3576. return internal::GetUnitTestImpl()->current_test_result()->Skipped();
  3577. }
  3578. // class TestInfo
  3579. // Constructs a TestInfo object. It assumes ownership of the test factory
  3580. // object.
  3581. TestInfo::TestInfo(const std::string& a_test_suite_name,
  3582. const std::string& a_name, const char* a_type_param,
  3583. const char* a_value_param,
  3584. internal::CodeLocation a_code_location,
  3585. internal::TypeId fixture_class_id,
  3586. internal::TestFactoryBase* factory)
  3587. : test_suite_name_(a_test_suite_name),
  3588. name_(a_name),
  3589. type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
  3590. value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
  3591. location_(a_code_location),
  3592. fixture_class_id_(fixture_class_id),
  3593. should_run_(false),
  3594. is_disabled_(false),
  3595. matches_filter_(false),
  3596. is_in_another_shard_(false),
  3597. factory_(factory),
  3598. result_() {}
  3599. // Destructs a TestInfo object.
  3600. TestInfo::~TestInfo() { delete factory_; }
  3601. namespace internal {
  3602. // Creates a new TestInfo object and registers it with Google Test;
  3603. // returns the created object.
  3604. //
  3605. // Arguments:
  3606. //
  3607. // test_suite_name: name of the test suite
  3608. // name: name of the test
  3609. // type_param: the name of the test's type parameter, or NULL if
  3610. // this is not a typed or a type-parameterized test.
  3611. // value_param: text representation of the test's value parameter,
  3612. // or NULL if this is not a value-parameterized test.
  3613. // code_location: code location where the test is defined
  3614. // fixture_class_id: ID of the test fixture class
  3615. // set_up_tc: pointer to the function that sets up the test suite
  3616. // tear_down_tc: pointer to the function that tears down the test suite
  3617. // factory: pointer to the factory that creates a test object.
  3618. // The newly created TestInfo instance will assume
  3619. // ownership of the factory object.
  3620. TestInfo* MakeAndRegisterTestInfo(
  3621. const char* test_suite_name, const char* name, const char* type_param,
  3622. const char* value_param, CodeLocation code_location,
  3623. TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
  3624. TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
  3625. TestInfo* const test_info =
  3626. new TestInfo(test_suite_name, name, type_param, value_param,
  3627. code_location, fixture_class_id, factory);
  3628. GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
  3629. return test_info;
  3630. }
  3631. void ReportInvalidTestSuiteType(const char* test_suite_name,
  3632. CodeLocation code_location) {
  3633. Message errors;
  3634. errors
  3635. << "Attempted redefinition of test suite " << test_suite_name << ".\n"
  3636. << "All tests in the same test suite must use the same test fixture\n"
  3637. << "class. However, in test suite " << test_suite_name << ", you tried\n"
  3638. << "to define a test using a fixture class different from the one\n"
  3639. << "used earlier. This can happen if the two fixture classes are\n"
  3640. << "from different namespaces and have the same name. You should\n"
  3641. << "probably rename one of the classes to put the tests into different\n"
  3642. << "test suites.";
  3643. GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
  3644. code_location.line)
  3645. << " " << errors.GetString();
  3646. }
  3647. } // namespace internal
  3648. namespace {
  3649. // A predicate that checks the test name of a TestInfo against a known
  3650. // value.
  3651. //
  3652. // This is used for implementation of the TestSuite class only. We put
  3653. // it in the anonymous namespace to prevent polluting the outer
  3654. // namespace.
  3655. //
  3656. // TestNameIs is copyable.
  3657. class TestNameIs {
  3658. public:
  3659. // Constructor.
  3660. //
  3661. // TestNameIs has NO default constructor.
  3662. explicit TestNameIs(const char* name)
  3663. : name_(name) {}
  3664. // Returns true if and only if the test name of test_info matches name_.
  3665. bool operator()(const TestInfo * test_info) const {
  3666. return test_info && test_info->name() == name_;
  3667. }
  3668. private:
  3669. std::string name_;
  3670. };
  3671. } // namespace
  3672. namespace internal {
  3673. // This method expands all parameterized tests registered with macros TEST_P
  3674. // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
  3675. // This will be done just once during the program runtime.
  3676. void UnitTestImpl::RegisterParameterizedTests() {
  3677. if (!parameterized_tests_registered_) {
  3678. parameterized_test_registry_.RegisterTests();
  3679. type_parameterized_test_registry_.CheckForInstantiations();
  3680. parameterized_tests_registered_ = true;
  3681. }
  3682. }
  3683. } // namespace internal
  3684. // Creates the test object, runs it, records its result, and then
  3685. // deletes it.
  3686. void TestInfo::Run() {
  3687. if (!should_run_) return;
  3688. // Tells UnitTest where to store test result.
  3689. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3690. impl->set_current_test_info(this);
  3691. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3692. // Notifies the unit test event listeners that a test is about to start.
  3693. repeater->OnTestStart(*this);
  3694. result_.set_start_timestamp(internal::GetTimeInMillis());
  3695. internal::Timer timer;
  3696. impl->os_stack_trace_getter()->UponLeavingGTest();
  3697. // Creates the test object.
  3698. Test* const test = internal::HandleExceptionsInMethodIfSupported(
  3699. factory_, &internal::TestFactoryBase::CreateTest,
  3700. "the test fixture's constructor");
  3701. // Runs the test if the constructor didn't generate a fatal failure or invoke
  3702. // GTEST_SKIP().
  3703. // Note that the object will not be null
  3704. if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
  3705. // This doesn't throw as all user code that can throw are wrapped into
  3706. // exception handling code.
  3707. test->Run();
  3708. }
  3709. if (test != nullptr) {
  3710. // Deletes the test object.
  3711. impl->os_stack_trace_getter()->UponLeavingGTest();
  3712. internal::HandleExceptionsInMethodIfSupported(
  3713. test, &Test::DeleteSelf_, "the test fixture's destructor");
  3714. }
  3715. result_.set_elapsed_time(timer.Elapsed());
  3716. // Notifies the unit test event listener that a test has just finished.
  3717. repeater->OnTestEnd(*this);
  3718. // Tells UnitTest to stop associating assertion results to this
  3719. // test.
  3720. impl->set_current_test_info(nullptr);
  3721. }
  3722. // Skip and records a skipped test result for this object.
  3723. void TestInfo::Skip() {
  3724. if (!should_run_) return;
  3725. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3726. impl->set_current_test_info(this);
  3727. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3728. // Notifies the unit test event listeners that a test is about to start.
  3729. repeater->OnTestStart(*this);
  3730. const TestPartResult test_part_result =
  3731. TestPartResult(TestPartResult::kSkip, this->file(), this->line(), "");
  3732. impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
  3733. test_part_result);
  3734. // Notifies the unit test event listener that a test has just finished.
  3735. repeater->OnTestEnd(*this);
  3736. impl->set_current_test_info(nullptr);
  3737. }
  3738. // class TestSuite
  3739. // Gets the number of successful tests in this test suite.
  3740. int TestSuite::successful_test_count() const {
  3741. return CountIf(test_info_list_, TestPassed);
  3742. }
  3743. // Gets the number of successful tests in this test suite.
  3744. int TestSuite::skipped_test_count() const {
  3745. return CountIf(test_info_list_, TestSkipped);
  3746. }
  3747. // Gets the number of failed tests in this test suite.
  3748. int TestSuite::failed_test_count() const {
  3749. return CountIf(test_info_list_, TestFailed);
  3750. }
  3751. // Gets the number of disabled tests that will be reported in the XML report.
  3752. int TestSuite::reportable_disabled_test_count() const {
  3753. return CountIf(test_info_list_, TestReportableDisabled);
  3754. }
  3755. // Gets the number of disabled tests in this test suite.
  3756. int TestSuite::disabled_test_count() const {
  3757. return CountIf(test_info_list_, TestDisabled);
  3758. }
  3759. // Gets the number of tests to be printed in the XML report.
  3760. int TestSuite::reportable_test_count() const {
  3761. return CountIf(test_info_list_, TestReportable);
  3762. }
  3763. // Get the number of tests in this test suite that should run.
  3764. int TestSuite::test_to_run_count() const {
  3765. return CountIf(test_info_list_, ShouldRunTest);
  3766. }
  3767. // Gets the number of all tests.
  3768. int TestSuite::total_test_count() const {
  3769. return static_cast<int>(test_info_list_.size());
  3770. }
  3771. // Creates a TestSuite with the given name.
  3772. //
  3773. // Arguments:
  3774. //
  3775. // a_name: name of the test suite
  3776. // a_type_param: the name of the test suite's type parameter, or NULL if
  3777. // this is not a typed or a type-parameterized test suite.
  3778. // set_up_tc: pointer to the function that sets up the test suite
  3779. // tear_down_tc: pointer to the function that tears down the test suite
  3780. TestSuite::TestSuite(const char* a_name, const char* a_type_param,
  3781. internal::SetUpTestSuiteFunc set_up_tc,
  3782. internal::TearDownTestSuiteFunc tear_down_tc)
  3783. : name_(a_name),
  3784. type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
  3785. set_up_tc_(set_up_tc),
  3786. tear_down_tc_(tear_down_tc),
  3787. should_run_(false),
  3788. start_timestamp_(0),
  3789. elapsed_time_(0) {}
  3790. // Destructor of TestSuite.
  3791. TestSuite::~TestSuite() {
  3792. // Deletes every Test in the collection.
  3793. ForEach(test_info_list_, internal::Delete<TestInfo>);
  3794. }
  3795. // Returns the i-th test among all the tests. i can range from 0 to
  3796. // total_test_count() - 1. If i is not in that range, returns NULL.
  3797. const TestInfo* TestSuite::GetTestInfo(int i) const {
  3798. const int index = GetElementOr(test_indices_, i, -1);
  3799. return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
  3800. }
  3801. // Returns the i-th test among all the tests. i can range from 0 to
  3802. // total_test_count() - 1. If i is not in that range, returns NULL.
  3803. TestInfo* TestSuite::GetMutableTestInfo(int i) {
  3804. const int index = GetElementOr(test_indices_, i, -1);
  3805. return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
  3806. }
  3807. // Adds a test to this test suite. Will delete the test upon
  3808. // destruction of the TestSuite object.
  3809. void TestSuite::AddTestInfo(TestInfo* test_info) {
  3810. test_info_list_.push_back(test_info);
  3811. test_indices_.push_back(static_cast<int>(test_indices_.size()));
  3812. }
  3813. // Runs every test in this TestSuite.
  3814. void TestSuite::Run() {
  3815. if (!should_run_) return;
  3816. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3817. impl->set_current_test_suite(this);
  3818. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3819. // Call both legacy and the new API
  3820. repeater->OnTestSuiteStart(*this);
  3821. // Legacy API is deprecated but still available
  3822. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3823. repeater->OnTestCaseStart(*this);
  3824. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3825. impl->os_stack_trace_getter()->UponLeavingGTest();
  3826. internal::HandleExceptionsInMethodIfSupported(
  3827. this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
  3828. start_timestamp_ = internal::GetTimeInMillis();
  3829. internal::Timer timer;
  3830. for (int i = 0; i < total_test_count(); i++) {
  3831. GetMutableTestInfo(i)->Run();
  3832. if (GTEST_FLAG(fail_fast) && GetMutableTestInfo(i)->result()->Failed()) {
  3833. for (int j = i + 1; j < total_test_count(); j++) {
  3834. GetMutableTestInfo(j)->Skip();
  3835. }
  3836. break;
  3837. }
  3838. }
  3839. elapsed_time_ = timer.Elapsed();
  3840. impl->os_stack_trace_getter()->UponLeavingGTest();
  3841. internal::HandleExceptionsInMethodIfSupported(
  3842. this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()");
  3843. // Call both legacy and the new API
  3844. repeater->OnTestSuiteEnd(*this);
  3845. // Legacy API is deprecated but still available
  3846. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3847. repeater->OnTestCaseEnd(*this);
  3848. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3849. impl->set_current_test_suite(nullptr);
  3850. }
  3851. // Skips all tests under this TestSuite.
  3852. void TestSuite::Skip() {
  3853. if (!should_run_) return;
  3854. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3855. impl->set_current_test_suite(this);
  3856. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3857. // Call both legacy and the new API
  3858. repeater->OnTestSuiteStart(*this);
  3859. // Legacy API is deprecated but still available
  3860. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3861. repeater->OnTestCaseStart(*this);
  3862. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3863. for (int i = 0; i < total_test_count(); i++) {
  3864. GetMutableTestInfo(i)->Skip();
  3865. }
  3866. // Call both legacy and the new API
  3867. repeater->OnTestSuiteEnd(*this);
  3868. // Legacy API is deprecated but still available
  3869. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3870. repeater->OnTestCaseEnd(*this);
  3871. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3872. impl->set_current_test_suite(nullptr);
  3873. }
  3874. // Clears the results of all tests in this test suite.
  3875. void TestSuite::ClearResult() {
  3876. ad_hoc_test_result_.Clear();
  3877. ForEach(test_info_list_, TestInfo::ClearTestResult);
  3878. }
  3879. // Shuffles the tests in this test suite.
  3880. void TestSuite::ShuffleTests(internal::Random* random) {
  3881. Shuffle(random, &test_indices_);
  3882. }
  3883. // Restores the test order to before the first shuffle.
  3884. void TestSuite::UnshuffleTests() {
  3885. for (size_t i = 0; i < test_indices_.size(); i++) {
  3886. test_indices_[i] = static_cast<int>(i);
  3887. }
  3888. }
  3889. // Formats a countable noun. Depending on its quantity, either the
  3890. // singular form or the plural form is used. e.g.
  3891. //
  3892. // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
  3893. // FormatCountableNoun(5, "book", "books") returns "5 books".
  3894. static std::string FormatCountableNoun(int count,
  3895. const char * singular_form,
  3896. const char * plural_form) {
  3897. return internal::StreamableToString(count) + " " +
  3898. (count == 1 ? singular_form : plural_form);
  3899. }
  3900. // Formats the count of tests.
  3901. static std::string FormatTestCount(int test_count) {
  3902. return FormatCountableNoun(test_count, "test", "tests");
  3903. }
  3904. // Formats the count of test suites.
  3905. static std::string FormatTestSuiteCount(int test_suite_count) {
  3906. return FormatCountableNoun(test_suite_count, "test suite", "test suites");
  3907. }
  3908. // Converts a TestPartResult::Type enum to human-friendly string
  3909. // representation. Both kNonFatalFailure and kFatalFailure are translated
  3910. // to "Failure", as the user usually doesn't care about the difference
  3911. // between the two when viewing the test result.
  3912. static const char * TestPartResultTypeToString(TestPartResult::Type type) {
  3913. switch (type) {
  3914. case TestPartResult::kSkip:
  3915. return "Skipped\n";
  3916. case TestPartResult::kSuccess:
  3917. return "Success";
  3918. case TestPartResult::kNonFatalFailure:
  3919. case TestPartResult::kFatalFailure:
  3920. #ifdef _MSC_VER
  3921. return "error: ";
  3922. #else
  3923. return "Failure\n";
  3924. #endif
  3925. default:
  3926. return "Unknown result type";
  3927. }
  3928. }
  3929. namespace internal {
  3930. namespace {
  3931. enum class GTestColor { kDefault, kRed, kGreen, kYellow };
  3932. } // namespace
  3933. // Prints a TestPartResult to an std::string.
  3934. static std::string PrintTestPartResultToString(
  3935. const TestPartResult& test_part_result) {
  3936. return (Message()
  3937. << internal::FormatFileLocation(test_part_result.file_name(),
  3938. test_part_result.line_number())
  3939. << " " << TestPartResultTypeToString(test_part_result.type())
  3940. << test_part_result.message()).GetString();
  3941. }
  3942. // Prints a TestPartResult.
  3943. static void PrintTestPartResult(const TestPartResult& test_part_result) {
  3944. const std::string& result =
  3945. PrintTestPartResultToString(test_part_result);
  3946. printf("%s\n", result.c_str());
  3947. fflush(stdout);
  3948. // If the test program runs in Visual Studio or a debugger, the
  3949. // following statements add the test part result message to the Output
  3950. // window such that the user can double-click on it to jump to the
  3951. // corresponding source code location; otherwise they do nothing.
  3952. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3953. // We don't call OutputDebugString*() on Windows Mobile, as printing
  3954. // to stdout is done by OutputDebugString() there already - we don't
  3955. // want the same message printed twice.
  3956. ::OutputDebugStringA(result.c_str());
  3957. ::OutputDebugStringA("\n");
  3958. #endif
  3959. }
  3960. // class PrettyUnitTestResultPrinter
  3961. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
  3962. !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  3963. // Returns the character attribute for the given color.
  3964. static WORD GetColorAttribute(GTestColor color) {
  3965. switch (color) {
  3966. case GTestColor::kRed:
  3967. return FOREGROUND_RED;
  3968. case GTestColor::kGreen:
  3969. return FOREGROUND_GREEN;
  3970. case GTestColor::kYellow:
  3971. return FOREGROUND_RED | FOREGROUND_GREEN;
  3972. default: return 0;
  3973. }
  3974. }
  3975. static int GetBitOffset(WORD color_mask) {
  3976. if (color_mask == 0) return 0;
  3977. int bitOffset = 0;
  3978. while ((color_mask & 1) == 0) {
  3979. color_mask >>= 1;
  3980. ++bitOffset;
  3981. }
  3982. return bitOffset;
  3983. }
  3984. static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
  3985. // Let's reuse the BG
  3986. static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
  3987. BACKGROUND_RED | BACKGROUND_INTENSITY;
  3988. static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
  3989. FOREGROUND_RED | FOREGROUND_INTENSITY;
  3990. const WORD existing_bg = old_color_attrs & background_mask;
  3991. WORD new_color =
  3992. GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
  3993. static const int bg_bitOffset = GetBitOffset(background_mask);
  3994. static const int fg_bitOffset = GetBitOffset(foreground_mask);
  3995. if (((new_color & background_mask) >> bg_bitOffset) ==
  3996. ((new_color & foreground_mask) >> fg_bitOffset)) {
  3997. new_color ^= FOREGROUND_INTENSITY; // invert intensity
  3998. }
  3999. return new_color;
  4000. }
  4001. #else
  4002. // Returns the ANSI color code for the given color. GTestColor::kDefault is
  4003. // an invalid input.
  4004. static const char* GetAnsiColorCode(GTestColor color) {
  4005. switch (color) {
  4006. case GTestColor::kRed:
  4007. return "1";
  4008. case GTestColor::kGreen:
  4009. return "2";
  4010. case GTestColor::kYellow:
  4011. return "3";
  4012. default:
  4013. return nullptr;
  4014. }
  4015. }
  4016. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  4017. // Returns true if and only if Google Test should use colors in the output.
  4018. bool ShouldUseColor(bool stdout_is_tty) {
  4019. const char* const gtest_color = GTEST_FLAG(color).c_str();
  4020. if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
  4021. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
  4022. // On Windows the TERM variable is usually not set, but the
  4023. // console there does support colors.
  4024. return stdout_is_tty;
  4025. #else
  4026. // On non-Windows platforms, we rely on the TERM variable.
  4027. const char* const term = posix::GetEnv("TERM");
  4028. const bool term_supports_color =
  4029. String::CStringEquals(term, "xterm") ||
  4030. String::CStringEquals(term, "xterm-color") ||
  4031. String::CStringEquals(term, "xterm-256color") ||
  4032. String::CStringEquals(term, "screen") ||
  4033. String::CStringEquals(term, "screen-256color") ||
  4034. String::CStringEquals(term, "tmux") ||
  4035. String::CStringEquals(term, "tmux-256color") ||
  4036. String::CStringEquals(term, "rxvt-unicode") ||
  4037. String::CStringEquals(term, "rxvt-unicode-256color") ||
  4038. String::CStringEquals(term, "linux") ||
  4039. String::CStringEquals(term, "cygwin");
  4040. return stdout_is_tty && term_supports_color;
  4041. #endif // GTEST_OS_WINDOWS
  4042. }
  4043. return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
  4044. String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
  4045. String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
  4046. String::CStringEquals(gtest_color, "1");
  4047. // We take "yes", "true", "t", and "1" as meaning "yes". If the
  4048. // value is neither one of these nor "auto", we treat it as "no" to
  4049. // be conservative.
  4050. }
  4051. // Helpers for printing colored strings to stdout. Note that on Windows, we
  4052. // cannot simply emit special characters and have the terminal change colors.
  4053. // This routine must actually emit the characters rather than return a string
  4054. // that would be colored when printed, as can be done on Linux.
  4055. GTEST_ATTRIBUTE_PRINTF_(2, 3)
  4056. static void ColoredPrintf(GTestColor color, const char *fmt, ...) {
  4057. va_list args;
  4058. va_start(args, fmt);
  4059. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
  4060. GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)
  4061. const bool use_color = AlwaysFalse();
  4062. #else
  4063. static const bool in_color_mode =
  4064. ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
  4065. const bool use_color = in_color_mode && (color != GTestColor::kDefault);
  4066. #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
  4067. if (!use_color) {
  4068. vprintf(fmt, args);
  4069. va_end(args);
  4070. return;
  4071. }
  4072. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
  4073. !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  4074. const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  4075. // Gets the current text color.
  4076. CONSOLE_SCREEN_BUFFER_INFO buffer_info;
  4077. GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
  4078. const WORD old_color_attrs = buffer_info.wAttributes;
  4079. const WORD new_color = GetNewColor(color, old_color_attrs);
  4080. // We need to flush the stream buffers into the console before each
  4081. // SetConsoleTextAttribute call lest it affect the text that is already
  4082. // printed but has not yet reached the console.
  4083. fflush(stdout);
  4084. SetConsoleTextAttribute(stdout_handle, new_color);
  4085. vprintf(fmt, args);
  4086. fflush(stdout);
  4087. // Restores the text color.
  4088. SetConsoleTextAttribute(stdout_handle, old_color_attrs);
  4089. #else
  4090. printf("\033[0;3%sm", GetAnsiColorCode(color));
  4091. vprintf(fmt, args);
  4092. printf("\033[m"); // Resets the terminal to default.
  4093. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  4094. va_end(args);
  4095. }
  4096. // Text printed in Google Test's text output and --gtest_list_tests
  4097. // output to label the type parameter and value parameter for a test.
  4098. static const char kTypeParamLabel[] = "TypeParam";
  4099. static const char kValueParamLabel[] = "GetParam()";
  4100. static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
  4101. const char* const type_param = test_info.type_param();
  4102. const char* const value_param = test_info.value_param();
  4103. if (type_param != nullptr || value_param != nullptr) {
  4104. printf(", where ");
  4105. if (type_param != nullptr) {
  4106. printf("%s = %s", kTypeParamLabel, type_param);
  4107. if (value_param != nullptr) printf(" and ");
  4108. }
  4109. if (value_param != nullptr) {
  4110. printf("%s = %s", kValueParamLabel, value_param);
  4111. }
  4112. }
  4113. }
  4114. // This class implements the TestEventListener interface.
  4115. //
  4116. // Class PrettyUnitTestResultPrinter is copyable.
  4117. class PrettyUnitTestResultPrinter : public TestEventListener {
  4118. public:
  4119. PrettyUnitTestResultPrinter() {}
  4120. static void PrintTestName(const char* test_suite, const char* test) {
  4121. printf("%s.%s", test_suite, test);
  4122. }
  4123. // The following methods override what's in the TestEventListener class.
  4124. void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
  4125. void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
  4126. void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
  4127. void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
  4128. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4129. void OnTestCaseStart(const TestCase& test_case) override;
  4130. #else
  4131. void OnTestSuiteStart(const TestSuite& test_suite) override;
  4132. #endif // OnTestCaseStart
  4133. void OnTestStart(const TestInfo& test_info) override;
  4134. void OnTestPartResult(const TestPartResult& result) override;
  4135. void OnTestEnd(const TestInfo& test_info) override;
  4136. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4137. void OnTestCaseEnd(const TestCase& test_case) override;
  4138. #else
  4139. void OnTestSuiteEnd(const TestSuite& test_suite) override;
  4140. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4141. void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
  4142. void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
  4143. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  4144. void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
  4145. private:
  4146. static void PrintFailedTests(const UnitTest& unit_test);
  4147. static void PrintFailedTestSuites(const UnitTest& unit_test);
  4148. static void PrintSkippedTests(const UnitTest& unit_test);
  4149. };
  4150. // Fired before each iteration of tests starts.
  4151. void PrettyUnitTestResultPrinter::OnTestIterationStart(
  4152. const UnitTest& unit_test, int iteration) {
  4153. if (GTEST_FLAG(repeat) != 1)
  4154. printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
  4155. const char* const filter = GTEST_FLAG(filter).c_str();
  4156. // Prints the filter if it's not *. This reminds the user that some
  4157. // tests may be skipped.
  4158. if (!String::CStringEquals(filter, kUniversalFilter)) {
  4159. ColoredPrintf(GTestColor::kYellow, "Note: %s filter = %s\n", GTEST_NAME_,
  4160. filter);
  4161. }
  4162. if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
  4163. const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
  4164. ColoredPrintf(GTestColor::kYellow, "Note: This is test shard %d of %s.\n",
  4165. static_cast<int>(shard_index) + 1,
  4166. internal::posix::GetEnv(kTestTotalShards));
  4167. }
  4168. if (GTEST_FLAG(shuffle)) {
  4169. ColoredPrintf(GTestColor::kYellow,
  4170. "Note: Randomizing tests' orders with a seed of %d .\n",
  4171. unit_test.random_seed());
  4172. }
  4173. ColoredPrintf(GTestColor::kGreen, "[==========] ");
  4174. printf("Running %s from %s.\n",
  4175. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  4176. FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
  4177. fflush(stdout);
  4178. }
  4179. void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
  4180. const UnitTest& /*unit_test*/) {
  4181. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  4182. printf("Global test environment set-up.\n");
  4183. fflush(stdout);
  4184. }
  4185. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4186. void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
  4187. const std::string counts =
  4188. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  4189. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  4190. printf("%s from %s", counts.c_str(), test_case.name());
  4191. if (test_case.type_param() == nullptr) {
  4192. printf("\n");
  4193. } else {
  4194. printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
  4195. }
  4196. fflush(stdout);
  4197. }
  4198. #else
  4199. void PrettyUnitTestResultPrinter::OnTestSuiteStart(
  4200. const TestSuite& test_suite) {
  4201. const std::string counts =
  4202. FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
  4203. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  4204. printf("%s from %s", counts.c_str(), test_suite.name());
  4205. if (test_suite.type_param() == nullptr) {
  4206. printf("\n");
  4207. } else {
  4208. printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
  4209. }
  4210. fflush(stdout);
  4211. }
  4212. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4213. void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
  4214. ColoredPrintf(GTestColor::kGreen, "[ RUN ] ");
  4215. PrintTestName(test_info.test_suite_name(), test_info.name());
  4216. printf("\n");
  4217. fflush(stdout);
  4218. }
  4219. // Called after an assertion failure.
  4220. void PrettyUnitTestResultPrinter::OnTestPartResult(
  4221. const TestPartResult& result) {
  4222. switch (result.type()) {
  4223. // If the test part succeeded, we don't need to do anything.
  4224. case TestPartResult::kSuccess:
  4225. return;
  4226. default:
  4227. // Print failure message from the assertion
  4228. // (e.g. expected this and got that).
  4229. PrintTestPartResult(result);
  4230. fflush(stdout);
  4231. }
  4232. }
  4233. void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  4234. if (test_info.result()->Passed()) {
  4235. ColoredPrintf(GTestColor::kGreen, "[ OK ] ");
  4236. } else if (test_info.result()->Skipped()) {
  4237. ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
  4238. } else {
  4239. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  4240. }
  4241. PrintTestName(test_info.test_suite_name(), test_info.name());
  4242. if (test_info.result()->Failed())
  4243. PrintFullTestCommentIfPresent(test_info);
  4244. if (GTEST_FLAG(print_time)) {
  4245. printf(" (%s ms)\n", internal::StreamableToString(
  4246. test_info.result()->elapsed_time()).c_str());
  4247. } else {
  4248. printf("\n");
  4249. }
  4250. fflush(stdout);
  4251. }
  4252. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4253. void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
  4254. if (!GTEST_FLAG(print_time)) return;
  4255. const std::string counts =
  4256. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  4257. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  4258. printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
  4259. internal::StreamableToString(test_case.elapsed_time()).c_str());
  4260. fflush(stdout);
  4261. }
  4262. #else
  4263. void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
  4264. if (!GTEST_FLAG(print_time)) return;
  4265. const std::string counts =
  4266. FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
  4267. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  4268. printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
  4269. internal::StreamableToString(test_suite.elapsed_time()).c_str());
  4270. fflush(stdout);
  4271. }
  4272. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4273. void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
  4274. const UnitTest& /*unit_test*/) {
  4275. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  4276. printf("Global test environment tear-down\n");
  4277. fflush(stdout);
  4278. }
  4279. // Internal helper for printing the list of failed tests.
  4280. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
  4281. const int failed_test_count = unit_test.failed_test_count();
  4282. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  4283. printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
  4284. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  4285. const TestSuite& test_suite = *unit_test.GetTestSuite(i);
  4286. if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
  4287. continue;
  4288. }
  4289. for (int j = 0; j < test_suite.total_test_count(); ++j) {
  4290. const TestInfo& test_info = *test_suite.GetTestInfo(j);
  4291. if (!test_info.should_run() || !test_info.result()->Failed()) {
  4292. continue;
  4293. }
  4294. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  4295. printf("%s.%s", test_suite.name(), test_info.name());
  4296. PrintFullTestCommentIfPresent(test_info);
  4297. printf("\n");
  4298. }
  4299. }
  4300. printf("\n%2d FAILED %s\n", failed_test_count,
  4301. failed_test_count == 1 ? "TEST" : "TESTS");
  4302. }
  4303. // Internal helper for printing the list of test suite failures not covered by
  4304. // PrintFailedTests.
  4305. void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
  4306. const UnitTest& unit_test) {
  4307. int suite_failure_count = 0;
  4308. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  4309. const TestSuite& test_suite = *unit_test.GetTestSuite(i);
  4310. if (!test_suite.should_run()) {
  4311. continue;
  4312. }
  4313. if (test_suite.ad_hoc_test_result().Failed()) {
  4314. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  4315. printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
  4316. ++suite_failure_count;
  4317. }
  4318. }
  4319. if (suite_failure_count > 0) {
  4320. printf("\n%2d FAILED TEST %s\n", suite_failure_count,
  4321. suite_failure_count == 1 ? "SUITE" : "SUITES");
  4322. }
  4323. }
  4324. // Internal helper for printing the list of skipped tests.
  4325. void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
  4326. const int skipped_test_count = unit_test.skipped_test_count();
  4327. if (skipped_test_count == 0) {
  4328. return;
  4329. }
  4330. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  4331. const TestSuite& test_suite = *unit_test.GetTestSuite(i);
  4332. if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
  4333. continue;
  4334. }
  4335. for (int j = 0; j < test_suite.total_test_count(); ++j) {
  4336. const TestInfo& test_info = *test_suite.GetTestInfo(j);
  4337. if (!test_info.should_run() || !test_info.result()->Skipped()) {
  4338. continue;
  4339. }
  4340. ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
  4341. printf("%s.%s", test_suite.name(), test_info.name());
  4342. printf("\n");
  4343. }
  4344. }
  4345. }
  4346. void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4347. int /*iteration*/) {
  4348. ColoredPrintf(GTestColor::kGreen, "[==========] ");
  4349. printf("%s from %s ran.",
  4350. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  4351. FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
  4352. if (GTEST_FLAG(print_time)) {
  4353. printf(" (%s ms total)",
  4354. internal::StreamableToString(unit_test.elapsed_time()).c_str());
  4355. }
  4356. printf("\n");
  4357. ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
  4358. printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  4359. const int skipped_test_count = unit_test.skipped_test_count();
  4360. if (skipped_test_count > 0) {
  4361. ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
  4362. printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
  4363. PrintSkippedTests(unit_test);
  4364. }
  4365. if (!unit_test.Passed()) {
  4366. PrintFailedTests(unit_test);
  4367. PrintFailedTestSuites(unit_test);
  4368. }
  4369. int num_disabled = unit_test.reportable_disabled_test_count();
  4370. if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
  4371. if (unit_test.Passed()) {
  4372. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
  4373. }
  4374. ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
  4375. num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
  4376. }
  4377. // Ensure that Google Test output is printed before, e.g., heapchecker output.
  4378. fflush(stdout);
  4379. }
  4380. // End PrettyUnitTestResultPrinter
  4381. // This class implements the TestEventListener interface.
  4382. //
  4383. // Class BriefUnitTestResultPrinter is copyable.
  4384. class BriefUnitTestResultPrinter : public TestEventListener {
  4385. public:
  4386. BriefUnitTestResultPrinter() {}
  4387. static void PrintTestName(const char* test_suite, const char* test) {
  4388. printf("%s.%s", test_suite, test);
  4389. }
  4390. // The following methods override what's in the TestEventListener class.
  4391. void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
  4392. void OnTestIterationStart(const UnitTest& /*unit_test*/,
  4393. int /*iteration*/) override {}
  4394. void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
  4395. void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
  4396. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4397. void OnTestCaseStart(const TestCase& /*test_case*/) override {}
  4398. #else
  4399. void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
  4400. #endif // OnTestCaseStart
  4401. void OnTestStart(const TestInfo& /*test_info*/) override {}
  4402. void OnTestPartResult(const TestPartResult& result) override;
  4403. void OnTestEnd(const TestInfo& test_info) override;
  4404. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4405. void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
  4406. #else
  4407. void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
  4408. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4409. void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
  4410. void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
  4411. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  4412. void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
  4413. };
  4414. // Called after an assertion failure.
  4415. void BriefUnitTestResultPrinter::OnTestPartResult(
  4416. const TestPartResult& result) {
  4417. switch (result.type()) {
  4418. // If the test part succeeded, we don't need to do anything.
  4419. case TestPartResult::kSuccess:
  4420. return;
  4421. default:
  4422. // Print failure message from the assertion
  4423. // (e.g. expected this and got that).
  4424. PrintTestPartResult(result);
  4425. fflush(stdout);
  4426. }
  4427. }
  4428. void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  4429. if (test_info.result()->Failed()) {
  4430. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  4431. PrintTestName(test_info.test_suite_name(), test_info.name());
  4432. PrintFullTestCommentIfPresent(test_info);
  4433. if (GTEST_FLAG(print_time)) {
  4434. printf(" (%s ms)\n",
  4435. internal::StreamableToString(test_info.result()->elapsed_time())
  4436. .c_str());
  4437. } else {
  4438. printf("\n");
  4439. }
  4440. fflush(stdout);
  4441. }
  4442. }
  4443. void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4444. int /*iteration*/) {
  4445. ColoredPrintf(GTestColor::kGreen, "[==========] ");
  4446. printf("%s from %s ran.",
  4447. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  4448. FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
  4449. if (GTEST_FLAG(print_time)) {
  4450. printf(" (%s ms total)",
  4451. internal::StreamableToString(unit_test.elapsed_time()).c_str());
  4452. }
  4453. printf("\n");
  4454. ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
  4455. printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  4456. const int skipped_test_count = unit_test.skipped_test_count();
  4457. if (skipped_test_count > 0) {
  4458. ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
  4459. printf("%s.\n", FormatTestCount(skipped_test_count).c_str());
  4460. }
  4461. int num_disabled = unit_test.reportable_disabled_test_count();
  4462. if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
  4463. if (unit_test.Passed()) {
  4464. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
  4465. }
  4466. ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
  4467. num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
  4468. }
  4469. // Ensure that Google Test output is printed before, e.g., heapchecker output.
  4470. fflush(stdout);
  4471. }
  4472. // End BriefUnitTestResultPrinter
  4473. // class TestEventRepeater
  4474. //
  4475. // This class forwards events to other event listeners.
  4476. class TestEventRepeater : public TestEventListener {
  4477. public:
  4478. TestEventRepeater() : forwarding_enabled_(true) {}
  4479. ~TestEventRepeater() override;
  4480. void Append(TestEventListener *listener);
  4481. TestEventListener* Release(TestEventListener* listener);
  4482. // Controls whether events will be forwarded to listeners_. Set to false
  4483. // in death test child processes.
  4484. bool forwarding_enabled() const { return forwarding_enabled_; }
  4485. void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
  4486. void OnTestProgramStart(const UnitTest& unit_test) override;
  4487. void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
  4488. void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
  4489. void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
  4490. // Legacy API is deprecated but still available
  4491. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4492. void OnTestCaseStart(const TestSuite& parameter) override;
  4493. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4494. void OnTestSuiteStart(const TestSuite& parameter) override;
  4495. void OnTestStart(const TestInfo& test_info) override;
  4496. void OnTestPartResult(const TestPartResult& result) override;
  4497. void OnTestEnd(const TestInfo& test_info) override;
  4498. // Legacy API is deprecated but still available
  4499. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4500. void OnTestCaseEnd(const TestCase& parameter) override;
  4501. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4502. void OnTestSuiteEnd(const TestSuite& parameter) override;
  4503. void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
  4504. void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
  4505. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  4506. void OnTestProgramEnd(const UnitTest& unit_test) override;
  4507. private:
  4508. // Controls whether events will be forwarded to listeners_. Set to false
  4509. // in death test child processes.
  4510. bool forwarding_enabled_;
  4511. // The list of listeners that receive events.
  4512. std::vector<TestEventListener*> listeners_;
  4513. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
  4514. };
  4515. TestEventRepeater::~TestEventRepeater() {
  4516. ForEach(listeners_, Delete<TestEventListener>);
  4517. }
  4518. void TestEventRepeater::Append(TestEventListener *listener) {
  4519. listeners_.push_back(listener);
  4520. }
  4521. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
  4522. for (size_t i = 0; i < listeners_.size(); ++i) {
  4523. if (listeners_[i] == listener) {
  4524. listeners_.erase(listeners_.begin() + static_cast<int>(i));
  4525. return listener;
  4526. }
  4527. }
  4528. return nullptr;
  4529. }
  4530. // Since most methods are very similar, use macros to reduce boilerplate.
  4531. // This defines a member that forwards the call to all listeners.
  4532. #define GTEST_REPEATER_METHOD_(Name, Type) \
  4533. void TestEventRepeater::Name(const Type& parameter) { \
  4534. if (forwarding_enabled_) { \
  4535. for (size_t i = 0; i < listeners_.size(); i++) { \
  4536. listeners_[i]->Name(parameter); \
  4537. } \
  4538. } \
  4539. }
  4540. // This defines a member that forwards the call to all listeners in reverse
  4541. // order.
  4542. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
  4543. void TestEventRepeater::Name(const Type& parameter) { \
  4544. if (forwarding_enabled_) { \
  4545. for (size_t i = listeners_.size(); i != 0; i--) { \
  4546. listeners_[i - 1]->Name(parameter); \
  4547. } \
  4548. } \
  4549. }
  4550. GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
  4551. GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
  4552. // Legacy API is deprecated but still available
  4553. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4554. GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
  4555. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4556. GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
  4557. GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
  4558. GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
  4559. GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
  4560. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
  4561. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
  4562. GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
  4563. // Legacy API is deprecated but still available
  4564. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4565. GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
  4566. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4567. GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
  4568. GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
  4569. #undef GTEST_REPEATER_METHOD_
  4570. #undef GTEST_REVERSE_REPEATER_METHOD_
  4571. void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
  4572. int iteration) {
  4573. if (forwarding_enabled_) {
  4574. for (size_t i = 0; i < listeners_.size(); i++) {
  4575. listeners_[i]->OnTestIterationStart(unit_test, iteration);
  4576. }
  4577. }
  4578. }
  4579. void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
  4580. int iteration) {
  4581. if (forwarding_enabled_) {
  4582. for (size_t i = listeners_.size(); i > 0; i--) {
  4583. listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration);
  4584. }
  4585. }
  4586. }
  4587. // End TestEventRepeater
  4588. // This class generates an XML output file.
  4589. class XmlUnitTestResultPrinter : public EmptyTestEventListener {
  4590. public:
  4591. explicit XmlUnitTestResultPrinter(const char* output_file);
  4592. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  4593. void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);
  4594. // Prints an XML summary of all unit tests.
  4595. static void PrintXmlTestsList(std::ostream* stream,
  4596. const std::vector<TestSuite*>& test_suites);
  4597. private:
  4598. // Is c a whitespace character that is normalized to a space character
  4599. // when it appears in an XML attribute value?
  4600. static bool IsNormalizableWhitespace(char c) {
  4601. return c == 0x9 || c == 0xA || c == 0xD;
  4602. }
  4603. // May c appear in a well-formed XML document?
  4604. static bool IsValidXmlCharacter(char c) {
  4605. return IsNormalizableWhitespace(c) || c >= 0x20;
  4606. }
  4607. // Returns an XML-escaped copy of the input string str. If
  4608. // is_attribute is true, the text is meant to appear as an attribute
  4609. // value, and normalizable whitespace is preserved by replacing it
  4610. // with character references.
  4611. static std::string EscapeXml(const std::string& str, bool is_attribute);
  4612. // Returns the given string with all characters invalid in XML removed.
  4613. static std::string RemoveInvalidXmlCharacters(const std::string& str);
  4614. // Convenience wrapper around EscapeXml when str is an attribute value.
  4615. static std::string EscapeXmlAttribute(const std::string& str) {
  4616. return EscapeXml(str, true);
  4617. }
  4618. // Convenience wrapper around EscapeXml when str is not an attribute value.
  4619. static std::string EscapeXmlText(const char* str) {
  4620. return EscapeXml(str, false);
  4621. }
  4622. // Verifies that the given attribute belongs to the given element and
  4623. // streams the attribute as XML.
  4624. static void OutputXmlAttribute(std::ostream* stream,
  4625. const std::string& element_name,
  4626. const std::string& name,
  4627. const std::string& value);
  4628. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  4629. static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
  4630. // Streams a test suite XML stanza containing the given test result.
  4631. //
  4632. // Requires: result.Failed()
  4633. static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
  4634. const TestResult& result);
  4635. // Streams an XML representation of a TestResult object.
  4636. static void OutputXmlTestResult(::std::ostream* stream,
  4637. const TestResult& result);
  4638. // Streams an XML representation of a TestInfo object.
  4639. static void OutputXmlTestInfo(::std::ostream* stream,
  4640. const char* test_suite_name,
  4641. const TestInfo& test_info);
  4642. // Prints an XML representation of a TestSuite object
  4643. static void PrintXmlTestSuite(::std::ostream* stream,
  4644. const TestSuite& test_suite);
  4645. // Prints an XML summary of unit_test to output stream out.
  4646. static void PrintXmlUnitTest(::std::ostream* stream,
  4647. const UnitTest& unit_test);
  4648. // Produces a string representing the test properties in a result as space
  4649. // delimited XML attributes based on the property key="value" pairs.
  4650. // When the std::string is not empty, it includes a space at the beginning,
  4651. // to delimit this attribute from prior attributes.
  4652. static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
  4653. // Streams an XML representation of the test properties of a TestResult
  4654. // object.
  4655. static void OutputXmlTestProperties(std::ostream* stream,
  4656. const TestResult& result);
  4657. // The output file.
  4658. const std::string output_file_;
  4659. GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
  4660. };
  4661. // Creates a new XmlUnitTestResultPrinter.
  4662. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
  4663. : output_file_(output_file) {
  4664. if (output_file_.empty()) {
  4665. GTEST_LOG_(FATAL) << "XML output file may not be null";
  4666. }
  4667. }
  4668. // Called after the unit test ends.
  4669. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4670. int /*iteration*/) {
  4671. FILE* xmlout = OpenFileForWriting(output_file_);
  4672. std::stringstream stream;
  4673. PrintXmlUnitTest(&stream, unit_test);
  4674. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  4675. fclose(xmlout);
  4676. }
  4677. void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
  4678. const std::vector<TestSuite*>& test_suites) {
  4679. FILE* xmlout = OpenFileForWriting(output_file_);
  4680. std::stringstream stream;
  4681. PrintXmlTestsList(&stream, test_suites);
  4682. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  4683. fclose(xmlout);
  4684. }
  4685. // Returns an XML-escaped copy of the input string str. If is_attribute
  4686. // is true, the text is meant to appear as an attribute value, and
  4687. // normalizable whitespace is preserved by replacing it with character
  4688. // references.
  4689. //
  4690. // Invalid XML characters in str, if any, are stripped from the output.
  4691. // It is expected that most, if not all, of the text processed by this
  4692. // module will consist of ordinary English text.
  4693. // If this module is ever modified to produce version 1.1 XML output,
  4694. // most invalid characters can be retained using character references.
  4695. std::string XmlUnitTestResultPrinter::EscapeXml(
  4696. const std::string& str, bool is_attribute) {
  4697. Message m;
  4698. for (size_t i = 0; i < str.size(); ++i) {
  4699. const char ch = str[i];
  4700. switch (ch) {
  4701. case '<':
  4702. m << "&lt;";
  4703. break;
  4704. case '>':
  4705. m << "&gt;";
  4706. break;
  4707. case '&':
  4708. m << "&amp;";
  4709. break;
  4710. case '\'':
  4711. if (is_attribute)
  4712. m << "&apos;";
  4713. else
  4714. m << '\'';
  4715. break;
  4716. case '"':
  4717. if (is_attribute)
  4718. m << "&quot;";
  4719. else
  4720. m << '"';
  4721. break;
  4722. default:
  4723. if (IsValidXmlCharacter(ch)) {
  4724. if (is_attribute && IsNormalizableWhitespace(ch))
  4725. m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
  4726. << ";";
  4727. else
  4728. m << ch;
  4729. }
  4730. break;
  4731. }
  4732. }
  4733. return m.GetString();
  4734. }
  4735. // Returns the given string with all characters invalid in XML removed.
  4736. // Currently invalid characters are dropped from the string. An
  4737. // alternative is to replace them with certain characters such as . or ?.
  4738. std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
  4739. const std::string& str) {
  4740. std::string output;
  4741. output.reserve(str.size());
  4742. for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
  4743. if (IsValidXmlCharacter(*it))
  4744. output.push_back(*it);
  4745. return output;
  4746. }
  4747. // The following routines generate an XML representation of a UnitTest
  4748. // object.
  4749. // GOOGLETEST_CM0009 DO NOT DELETE
  4750. //
  4751. // This is how Google Test concepts map to the DTD:
  4752. //
  4753. // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
  4754. // <testsuite name="testcase-name"> <-- corresponds to a TestSuite object
  4755. // <testcase name="test-name"> <-- corresponds to a TestInfo object
  4756. // <failure message="...">...</failure>
  4757. // <failure message="...">...</failure>
  4758. // <failure message="...">...</failure>
  4759. // <-- individual assertion failures
  4760. // </testcase>
  4761. // </testsuite>
  4762. // </testsuites>
  4763. // Formats the given time in milliseconds as seconds.
  4764. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
  4765. ::std::stringstream ss;
  4766. ss << (static_cast<double>(ms) * 1e-3);
  4767. return ss.str();
  4768. }
  4769. static bool PortableLocaltime(time_t seconds, struct tm* out) {
  4770. #if defined(_MSC_VER)
  4771. return localtime_s(out, &seconds) == 0;
  4772. #elif defined(__MINGW32__) || defined(__MINGW64__)
  4773. // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
  4774. // Windows' localtime(), which has a thread-local tm buffer.
  4775. struct tm* tm_ptr = localtime(&seconds); // NOLINT
  4776. if (tm_ptr == nullptr) return false;
  4777. *out = *tm_ptr;
  4778. return true;
  4779. #elif defined(__STDC_LIB_EXT1__)
  4780. // Uses localtime_s when available as localtime_r is only available from
  4781. // C23 standard.
  4782. return localtime_s(&seconds, out) != nullptr;
  4783. #else
  4784. return localtime_r(&seconds, out) != nullptr;
  4785. #endif
  4786. }
  4787. // Converts the given epoch time in milliseconds to a date string in the ISO
  4788. // 8601 format, without the timezone information.
  4789. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
  4790. struct tm time_struct;
  4791. if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  4792. return "";
  4793. // YYYY-MM-DDThh:mm:ss.sss
  4794. return StreamableToString(time_struct.tm_year + 1900) + "-" +
  4795. String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  4796. String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  4797. String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  4798. String::FormatIntWidth2(time_struct.tm_min) + ":" +
  4799. String::FormatIntWidth2(time_struct.tm_sec) + "." +
  4800. String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);
  4801. }
  4802. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  4803. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
  4804. const char* data) {
  4805. const char* segment = data;
  4806. *stream << "<![CDATA[";
  4807. for (;;) {
  4808. const char* const next_segment = strstr(segment, "]]>");
  4809. if (next_segment != nullptr) {
  4810. stream->write(
  4811. segment, static_cast<std::streamsize>(next_segment - segment));
  4812. *stream << "]]>]]&gt;<![CDATA[";
  4813. segment = next_segment + strlen("]]>");
  4814. } else {
  4815. *stream << segment;
  4816. break;
  4817. }
  4818. }
  4819. *stream << "]]>";
  4820. }
  4821. void XmlUnitTestResultPrinter::OutputXmlAttribute(
  4822. std::ostream* stream,
  4823. const std::string& element_name,
  4824. const std::string& name,
  4825. const std::string& value) {
  4826. const std::vector<std::string>& allowed_names =
  4827. GetReservedOutputAttributesForElement(element_name);
  4828. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4829. allowed_names.end())
  4830. << "Attribute " << name << " is not allowed for element <" << element_name
  4831. << ">.";
  4832. *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
  4833. }
  4834. // Streams a test suite XML stanza containing the given test result.
  4835. void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
  4836. ::std::ostream* stream, const TestResult& result) {
  4837. // Output the boilerplate for a minimal test suite with one test.
  4838. *stream << " <testsuite";
  4839. OutputXmlAttribute(stream, "testsuite", "name", "NonTestSuiteFailure");
  4840. OutputXmlAttribute(stream, "testsuite", "tests", "1");
  4841. OutputXmlAttribute(stream, "testsuite", "failures", "1");
  4842. OutputXmlAttribute(stream, "testsuite", "disabled", "0");
  4843. OutputXmlAttribute(stream, "testsuite", "skipped", "0");
  4844. OutputXmlAttribute(stream, "testsuite", "errors", "0");
  4845. OutputXmlAttribute(stream, "testsuite", "time",
  4846. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  4847. OutputXmlAttribute(
  4848. stream, "testsuite", "timestamp",
  4849. FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
  4850. *stream << ">";
  4851. // Output the boilerplate for a minimal test case with a single test.
  4852. *stream << " <testcase";
  4853. OutputXmlAttribute(stream, "testcase", "name", "");
  4854. OutputXmlAttribute(stream, "testcase", "status", "run");
  4855. OutputXmlAttribute(stream, "testcase", "result", "completed");
  4856. OutputXmlAttribute(stream, "testcase", "classname", "");
  4857. OutputXmlAttribute(stream, "testcase", "time",
  4858. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  4859. OutputXmlAttribute(
  4860. stream, "testcase", "timestamp",
  4861. FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
  4862. // Output the actual test result.
  4863. OutputXmlTestResult(stream, result);
  4864. // Complete the test suite.
  4865. *stream << " </testsuite>\n";
  4866. }
  4867. // Prints an XML representation of a TestInfo object.
  4868. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
  4869. const char* test_suite_name,
  4870. const TestInfo& test_info) {
  4871. const TestResult& result = *test_info.result();
  4872. const std::string kTestsuite = "testcase";
  4873. if (test_info.is_in_another_shard()) {
  4874. return;
  4875. }
  4876. *stream << " <testcase";
  4877. OutputXmlAttribute(stream, kTestsuite, "name", test_info.name());
  4878. if (test_info.value_param() != nullptr) {
  4879. OutputXmlAttribute(stream, kTestsuite, "value_param",
  4880. test_info.value_param());
  4881. }
  4882. if (test_info.type_param() != nullptr) {
  4883. OutputXmlAttribute(stream, kTestsuite, "type_param",
  4884. test_info.type_param());
  4885. }
  4886. if (GTEST_FLAG(list_tests)) {
  4887. OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
  4888. OutputXmlAttribute(stream, kTestsuite, "line",
  4889. StreamableToString(test_info.line()));
  4890. *stream << " />\n";
  4891. return;
  4892. }
  4893. OutputXmlAttribute(stream, kTestsuite, "status",
  4894. test_info.should_run() ? "run" : "notrun");
  4895. OutputXmlAttribute(stream, kTestsuite, "result",
  4896. test_info.should_run()
  4897. ? (result.Skipped() ? "skipped" : "completed")
  4898. : "suppressed");
  4899. OutputXmlAttribute(stream, kTestsuite, "time",
  4900. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  4901. OutputXmlAttribute(
  4902. stream, kTestsuite, "timestamp",
  4903. FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
  4904. OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
  4905. OutputXmlTestResult(stream, result);
  4906. }
  4907. void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
  4908. const TestResult& result) {
  4909. int failures = 0;
  4910. int skips = 0;
  4911. for (int i = 0; i < result.total_part_count(); ++i) {
  4912. const TestPartResult& part = result.GetTestPartResult(i);
  4913. if (part.failed()) {
  4914. if (++failures == 1 && skips == 0) {
  4915. *stream << ">\n";
  4916. }
  4917. const std::string location =
  4918. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  4919. part.line_number());
  4920. const std::string summary = location + "\n" + part.summary();
  4921. *stream << " <failure message=\""
  4922. << EscapeXmlAttribute(summary)
  4923. << "\" type=\"\">";
  4924. const std::string detail = location + "\n" + part.message();
  4925. OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
  4926. *stream << "</failure>\n";
  4927. } else if (part.skipped()) {
  4928. if (++skips == 1 && failures == 0) {
  4929. *stream << ">\n";
  4930. }
  4931. const std::string location =
  4932. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  4933. part.line_number());
  4934. const std::string summary = location + "\n" + part.summary();
  4935. *stream << " <skipped message=\""
  4936. << EscapeXmlAttribute(summary.c_str()) << "\">";
  4937. const std::string detail = location + "\n" + part.message();
  4938. OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
  4939. *stream << "</skipped>\n";
  4940. }
  4941. }
  4942. if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
  4943. *stream << " />\n";
  4944. } else {
  4945. if (failures == 0 && skips == 0) {
  4946. *stream << ">\n";
  4947. }
  4948. OutputXmlTestProperties(stream, result);
  4949. *stream << " </testcase>\n";
  4950. }
  4951. }
  4952. // Prints an XML representation of a TestSuite object
  4953. void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
  4954. const TestSuite& test_suite) {
  4955. const std::string kTestsuite = "testsuite";
  4956. *stream << " <" << kTestsuite;
  4957. OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
  4958. OutputXmlAttribute(stream, kTestsuite, "tests",
  4959. StreamableToString(test_suite.reportable_test_count()));
  4960. if (!GTEST_FLAG(list_tests)) {
  4961. OutputXmlAttribute(stream, kTestsuite, "failures",
  4962. StreamableToString(test_suite.failed_test_count()));
  4963. OutputXmlAttribute(
  4964. stream, kTestsuite, "disabled",
  4965. StreamableToString(test_suite.reportable_disabled_test_count()));
  4966. OutputXmlAttribute(stream, kTestsuite, "skipped",
  4967. StreamableToString(test_suite.skipped_test_count()));
  4968. OutputXmlAttribute(stream, kTestsuite, "errors", "0");
  4969. OutputXmlAttribute(stream, kTestsuite, "time",
  4970. FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
  4971. OutputXmlAttribute(
  4972. stream, kTestsuite, "timestamp",
  4973. FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp()));
  4974. *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
  4975. }
  4976. *stream << ">\n";
  4977. for (int i = 0; i < test_suite.total_test_count(); ++i) {
  4978. if (test_suite.GetTestInfo(i)->is_reportable())
  4979. OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
  4980. }
  4981. *stream << " </" << kTestsuite << ">\n";
  4982. }
  4983. // Prints an XML summary of unit_test to output stream out.
  4984. void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
  4985. const UnitTest& unit_test) {
  4986. const std::string kTestsuites = "testsuites";
  4987. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  4988. *stream << "<" << kTestsuites;
  4989. OutputXmlAttribute(stream, kTestsuites, "tests",
  4990. StreamableToString(unit_test.reportable_test_count()));
  4991. OutputXmlAttribute(stream, kTestsuites, "failures",
  4992. StreamableToString(unit_test.failed_test_count()));
  4993. OutputXmlAttribute(
  4994. stream, kTestsuites, "disabled",
  4995. StreamableToString(unit_test.reportable_disabled_test_count()));
  4996. OutputXmlAttribute(stream, kTestsuites, "errors", "0");
  4997. OutputXmlAttribute(stream, kTestsuites, "time",
  4998. FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
  4999. OutputXmlAttribute(
  5000. stream, kTestsuites, "timestamp",
  5001. FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
  5002. if (GTEST_FLAG(shuffle)) {
  5003. OutputXmlAttribute(stream, kTestsuites, "random_seed",
  5004. StreamableToString(unit_test.random_seed()));
  5005. }
  5006. *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
  5007. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  5008. *stream << ">\n";
  5009. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  5010. if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
  5011. PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
  5012. }
  5013. // If there was a test failure outside of one of the test suites (like in a
  5014. // test environment) include that in the output.
  5015. if (unit_test.ad_hoc_test_result().Failed()) {
  5016. OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
  5017. }
  5018. *stream << "</" << kTestsuites << ">\n";
  5019. }
  5020. void XmlUnitTestResultPrinter::PrintXmlTestsList(
  5021. std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
  5022. const std::string kTestsuites = "testsuites";
  5023. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  5024. *stream << "<" << kTestsuites;
  5025. int total_tests = 0;
  5026. for (auto test_suite : test_suites) {
  5027. total_tests += test_suite->total_test_count();
  5028. }
  5029. OutputXmlAttribute(stream, kTestsuites, "tests",
  5030. StreamableToString(total_tests));
  5031. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  5032. *stream << ">\n";
  5033. for (auto test_suite : test_suites) {
  5034. PrintXmlTestSuite(stream, *test_suite);
  5035. }
  5036. *stream << "</" << kTestsuites << ">\n";
  5037. }
  5038. // Produces a string representing the test properties in a result as space
  5039. // delimited XML attributes based on the property key="value" pairs.
  5040. std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
  5041. const TestResult& result) {
  5042. Message attributes;
  5043. for (int i = 0; i < result.test_property_count(); ++i) {
  5044. const TestProperty& property = result.GetTestProperty(i);
  5045. attributes << " " << property.key() << "="
  5046. << "\"" << EscapeXmlAttribute(property.value()) << "\"";
  5047. }
  5048. return attributes.GetString();
  5049. }
  5050. void XmlUnitTestResultPrinter::OutputXmlTestProperties(
  5051. std::ostream* stream, const TestResult& result) {
  5052. const std::string kProperties = "properties";
  5053. const std::string kProperty = "property";
  5054. if (result.test_property_count() <= 0) {
  5055. return;
  5056. }
  5057. *stream << "<" << kProperties << ">\n";
  5058. for (int i = 0; i < result.test_property_count(); ++i) {
  5059. const TestProperty& property = result.GetTestProperty(i);
  5060. *stream << "<" << kProperty;
  5061. *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
  5062. *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
  5063. *stream << "/>\n";
  5064. }
  5065. *stream << "</" << kProperties << ">\n";
  5066. }
  5067. // End XmlUnitTestResultPrinter
  5068. // This class generates an JSON output file.
  5069. class JsonUnitTestResultPrinter : public EmptyTestEventListener {
  5070. public:
  5071. explicit JsonUnitTestResultPrinter(const char* output_file);
  5072. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  5073. // Prints an JSON summary of all unit tests.
  5074. static void PrintJsonTestList(::std::ostream* stream,
  5075. const std::vector<TestSuite*>& test_suites);
  5076. private:
  5077. // Returns an JSON-escaped copy of the input string str.
  5078. static std::string EscapeJson(const std::string& str);
  5079. //// Verifies that the given attribute belongs to the given element and
  5080. //// streams the attribute as JSON.
  5081. static void OutputJsonKey(std::ostream* stream,
  5082. const std::string& element_name,
  5083. const std::string& name,
  5084. const std::string& value,
  5085. const std::string& indent,
  5086. bool comma = true);
  5087. static void OutputJsonKey(std::ostream* stream,
  5088. const std::string& element_name,
  5089. const std::string& name,
  5090. int value,
  5091. const std::string& indent,
  5092. bool comma = true);
  5093. // Streams a test suite JSON stanza containing the given test result.
  5094. //
  5095. // Requires: result.Failed()
  5096. static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
  5097. const TestResult& result);
  5098. // Streams a JSON representation of a TestResult object.
  5099. static void OutputJsonTestResult(::std::ostream* stream,
  5100. const TestResult& result);
  5101. // Streams a JSON representation of a TestInfo object.
  5102. static void OutputJsonTestInfo(::std::ostream* stream,
  5103. const char* test_suite_name,
  5104. const TestInfo& test_info);
  5105. // Prints a JSON representation of a TestSuite object
  5106. static void PrintJsonTestSuite(::std::ostream* stream,
  5107. const TestSuite& test_suite);
  5108. // Prints a JSON summary of unit_test to output stream out.
  5109. static void PrintJsonUnitTest(::std::ostream* stream,
  5110. const UnitTest& unit_test);
  5111. // Produces a string representing the test properties in a result as
  5112. // a JSON dictionary.
  5113. static std::string TestPropertiesAsJson(const TestResult& result,
  5114. const std::string& indent);
  5115. // The output file.
  5116. const std::string output_file_;
  5117. GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
  5118. };
  5119. // Creates a new JsonUnitTestResultPrinter.
  5120. JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
  5121. : output_file_(output_file) {
  5122. if (output_file_.empty()) {
  5123. GTEST_LOG_(FATAL) << "JSON output file may not be null";
  5124. }
  5125. }
  5126. void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  5127. int /*iteration*/) {
  5128. FILE* jsonout = OpenFileForWriting(output_file_);
  5129. std::stringstream stream;
  5130. PrintJsonUnitTest(&stream, unit_test);
  5131. fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
  5132. fclose(jsonout);
  5133. }
  5134. // Returns an JSON-escaped copy of the input string str.
  5135. std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
  5136. Message m;
  5137. for (size_t i = 0; i < str.size(); ++i) {
  5138. const char ch = str[i];
  5139. switch (ch) {
  5140. case '\\':
  5141. case '"':
  5142. case '/':
  5143. m << '\\' << ch;
  5144. break;
  5145. case '\b':
  5146. m << "\\b";
  5147. break;
  5148. case '\t':
  5149. m << "\\t";
  5150. break;
  5151. case '\n':
  5152. m << "\\n";
  5153. break;
  5154. case '\f':
  5155. m << "\\f";
  5156. break;
  5157. case '\r':
  5158. m << "\\r";
  5159. break;
  5160. default:
  5161. if (ch < ' ') {
  5162. m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
  5163. } else {
  5164. m << ch;
  5165. }
  5166. break;
  5167. }
  5168. }
  5169. return m.GetString();
  5170. }
  5171. // The following routines generate an JSON representation of a UnitTest
  5172. // object.
  5173. // Formats the given time in milliseconds as seconds.
  5174. static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
  5175. ::std::stringstream ss;
  5176. ss << (static_cast<double>(ms) * 1e-3) << "s";
  5177. return ss.str();
  5178. }
  5179. // Converts the given epoch time in milliseconds to a date string in the
  5180. // RFC3339 format, without the timezone information.
  5181. static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
  5182. struct tm time_struct;
  5183. if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  5184. return "";
  5185. // YYYY-MM-DDThh:mm:ss
  5186. return StreamableToString(time_struct.tm_year + 1900) + "-" +
  5187. String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  5188. String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  5189. String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  5190. String::FormatIntWidth2(time_struct.tm_min) + ":" +
  5191. String::FormatIntWidth2(time_struct.tm_sec) + "Z";
  5192. }
  5193. static inline std::string Indent(size_t width) {
  5194. return std::string(width, ' ');
  5195. }
  5196. void JsonUnitTestResultPrinter::OutputJsonKey(
  5197. std::ostream* stream,
  5198. const std::string& element_name,
  5199. const std::string& name,
  5200. const std::string& value,
  5201. const std::string& indent,
  5202. bool comma) {
  5203. const std::vector<std::string>& allowed_names =
  5204. GetReservedOutputAttributesForElement(element_name);
  5205. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  5206. allowed_names.end())
  5207. << "Key \"" << name << "\" is not allowed for value \"" << element_name
  5208. << "\".";
  5209. *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
  5210. if (comma)
  5211. *stream << ",\n";
  5212. }
  5213. void JsonUnitTestResultPrinter::OutputJsonKey(
  5214. std::ostream* stream,
  5215. const std::string& element_name,
  5216. const std::string& name,
  5217. int value,
  5218. const std::string& indent,
  5219. bool comma) {
  5220. const std::vector<std::string>& allowed_names =
  5221. GetReservedOutputAttributesForElement(element_name);
  5222. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  5223. allowed_names.end())
  5224. << "Key \"" << name << "\" is not allowed for value \"" << element_name
  5225. << "\".";
  5226. *stream << indent << "\"" << name << "\": " << StreamableToString(value);
  5227. if (comma)
  5228. *stream << ",\n";
  5229. }
  5230. // Streams a test suite JSON stanza containing the given test result.
  5231. void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
  5232. ::std::ostream* stream, const TestResult& result) {
  5233. // Output the boilerplate for a new test suite.
  5234. *stream << Indent(4) << "{\n";
  5235. OutputJsonKey(stream, "testsuite", "name", "NonTestSuiteFailure", Indent(6));
  5236. OutputJsonKey(stream, "testsuite", "tests", 1, Indent(6));
  5237. if (!GTEST_FLAG(list_tests)) {
  5238. OutputJsonKey(stream, "testsuite", "failures", 1, Indent(6));
  5239. OutputJsonKey(stream, "testsuite", "disabled", 0, Indent(6));
  5240. OutputJsonKey(stream, "testsuite", "skipped", 0, Indent(6));
  5241. OutputJsonKey(stream, "testsuite", "errors", 0, Indent(6));
  5242. OutputJsonKey(stream, "testsuite", "time",
  5243. FormatTimeInMillisAsDuration(result.elapsed_time()),
  5244. Indent(6));
  5245. OutputJsonKey(stream, "testsuite", "timestamp",
  5246. FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
  5247. Indent(6));
  5248. }
  5249. *stream << Indent(6) << "\"testsuite\": [\n";
  5250. // Output the boilerplate for a new test case.
  5251. *stream << Indent(8) << "{\n";
  5252. OutputJsonKey(stream, "testcase", "name", "", Indent(10));
  5253. OutputJsonKey(stream, "testcase", "status", "RUN", Indent(10));
  5254. OutputJsonKey(stream, "testcase", "result", "COMPLETED", Indent(10));
  5255. OutputJsonKey(stream, "testcase", "timestamp",
  5256. FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
  5257. Indent(10));
  5258. OutputJsonKey(stream, "testcase", "time",
  5259. FormatTimeInMillisAsDuration(result.elapsed_time()),
  5260. Indent(10));
  5261. OutputJsonKey(stream, "testcase", "classname", "", Indent(10), false);
  5262. *stream << TestPropertiesAsJson(result, Indent(10));
  5263. // Output the actual test result.
  5264. OutputJsonTestResult(stream, result);
  5265. // Finish the test suite.
  5266. *stream << "\n" << Indent(6) << "]\n" << Indent(4) << "}";
  5267. }
  5268. // Prints a JSON representation of a TestInfo object.
  5269. void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
  5270. const char* test_suite_name,
  5271. const TestInfo& test_info) {
  5272. const TestResult& result = *test_info.result();
  5273. const std::string kTestsuite = "testcase";
  5274. const std::string kIndent = Indent(10);
  5275. *stream << Indent(8) << "{\n";
  5276. OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent);
  5277. if (test_info.value_param() != nullptr) {
  5278. OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(),
  5279. kIndent);
  5280. }
  5281. if (test_info.type_param() != nullptr) {
  5282. OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
  5283. kIndent);
  5284. }
  5285. if (GTEST_FLAG(list_tests)) {
  5286. OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
  5287. OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
  5288. *stream << "\n" << Indent(8) << "}";
  5289. return;
  5290. }
  5291. OutputJsonKey(stream, kTestsuite, "status",
  5292. test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
  5293. OutputJsonKey(stream, kTestsuite, "result",
  5294. test_info.should_run()
  5295. ? (result.Skipped() ? "SKIPPED" : "COMPLETED")
  5296. : "SUPPRESSED",
  5297. kIndent);
  5298. OutputJsonKey(stream, kTestsuite, "timestamp",
  5299. FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
  5300. kIndent);
  5301. OutputJsonKey(stream, kTestsuite, "time",
  5302. FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
  5303. OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent,
  5304. false);
  5305. *stream << TestPropertiesAsJson(result, kIndent);
  5306. OutputJsonTestResult(stream, result);
  5307. }
  5308. void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
  5309. const TestResult& result) {
  5310. const std::string kIndent = Indent(10);
  5311. int failures = 0;
  5312. for (int i = 0; i < result.total_part_count(); ++i) {
  5313. const TestPartResult& part = result.GetTestPartResult(i);
  5314. if (part.failed()) {
  5315. *stream << ",\n";
  5316. if (++failures == 1) {
  5317. *stream << kIndent << "\"" << "failures" << "\": [\n";
  5318. }
  5319. const std::string location =
  5320. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  5321. part.line_number());
  5322. const std::string message = EscapeJson(location + "\n" + part.message());
  5323. *stream << kIndent << " {\n"
  5324. << kIndent << " \"failure\": \"" << message << "\",\n"
  5325. << kIndent << " \"type\": \"\"\n"
  5326. << kIndent << " }";
  5327. }
  5328. }
  5329. if (failures > 0)
  5330. *stream << "\n" << kIndent << "]";
  5331. *stream << "\n" << Indent(8) << "}";
  5332. }
  5333. // Prints an JSON representation of a TestSuite object
  5334. void JsonUnitTestResultPrinter::PrintJsonTestSuite(
  5335. std::ostream* stream, const TestSuite& test_suite) {
  5336. const std::string kTestsuite = "testsuite";
  5337. const std::string kIndent = Indent(6);
  5338. *stream << Indent(4) << "{\n";
  5339. OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
  5340. OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
  5341. kIndent);
  5342. if (!GTEST_FLAG(list_tests)) {
  5343. OutputJsonKey(stream, kTestsuite, "failures",
  5344. test_suite.failed_test_count(), kIndent);
  5345. OutputJsonKey(stream, kTestsuite, "disabled",
  5346. test_suite.reportable_disabled_test_count(), kIndent);
  5347. OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
  5348. OutputJsonKey(
  5349. stream, kTestsuite, "timestamp",
  5350. FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()),
  5351. kIndent);
  5352. OutputJsonKey(stream, kTestsuite, "time",
  5353. FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
  5354. kIndent, false);
  5355. *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
  5356. << ",\n";
  5357. }
  5358. *stream << kIndent << "\"" << kTestsuite << "\": [\n";
  5359. bool comma = false;
  5360. for (int i = 0; i < test_suite.total_test_count(); ++i) {
  5361. if (test_suite.GetTestInfo(i)->is_reportable()) {
  5362. if (comma) {
  5363. *stream << ",\n";
  5364. } else {
  5365. comma = true;
  5366. }
  5367. OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
  5368. }
  5369. }
  5370. *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
  5371. }
  5372. // Prints a JSON summary of unit_test to output stream out.
  5373. void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
  5374. const UnitTest& unit_test) {
  5375. const std::string kTestsuites = "testsuites";
  5376. const std::string kIndent = Indent(2);
  5377. *stream << "{\n";
  5378. OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
  5379. kIndent);
  5380. OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
  5381. kIndent);
  5382. OutputJsonKey(stream, kTestsuites, "disabled",
  5383. unit_test.reportable_disabled_test_count(), kIndent);
  5384. OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
  5385. if (GTEST_FLAG(shuffle)) {
  5386. OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
  5387. kIndent);
  5388. }
  5389. OutputJsonKey(stream, kTestsuites, "timestamp",
  5390. FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
  5391. kIndent);
  5392. OutputJsonKey(stream, kTestsuites, "time",
  5393. FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
  5394. false);
  5395. *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
  5396. << ",\n";
  5397. OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  5398. *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  5399. bool comma = false;
  5400. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  5401. if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
  5402. if (comma) {
  5403. *stream << ",\n";
  5404. } else {
  5405. comma = true;
  5406. }
  5407. PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
  5408. }
  5409. }
  5410. // If there was a test failure outside of one of the test suites (like in a
  5411. // test environment) include that in the output.
  5412. if (unit_test.ad_hoc_test_result().Failed()) {
  5413. OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
  5414. }
  5415. *stream << "\n" << kIndent << "]\n" << "}\n";
  5416. }
  5417. void JsonUnitTestResultPrinter::PrintJsonTestList(
  5418. std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
  5419. const std::string kTestsuites = "testsuites";
  5420. const std::string kIndent = Indent(2);
  5421. *stream << "{\n";
  5422. int total_tests = 0;
  5423. for (auto test_suite : test_suites) {
  5424. total_tests += test_suite->total_test_count();
  5425. }
  5426. OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
  5427. OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  5428. *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  5429. for (size_t i = 0; i < test_suites.size(); ++i) {
  5430. if (i != 0) {
  5431. *stream << ",\n";
  5432. }
  5433. PrintJsonTestSuite(stream, *test_suites[i]);
  5434. }
  5435. *stream << "\n"
  5436. << kIndent << "]\n"
  5437. << "}\n";
  5438. }
  5439. // Produces a string representing the test properties in a result as
  5440. // a JSON dictionary.
  5441. std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
  5442. const TestResult& result, const std::string& indent) {
  5443. Message attributes;
  5444. for (int i = 0; i < result.test_property_count(); ++i) {
  5445. const TestProperty& property = result.GetTestProperty(i);
  5446. attributes << ",\n" << indent << "\"" << property.key() << "\": "
  5447. << "\"" << EscapeJson(property.value()) << "\"";
  5448. }
  5449. return attributes.GetString();
  5450. }
  5451. // End JsonUnitTestResultPrinter
  5452. #if GTEST_CAN_STREAM_RESULTS_
  5453. // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
  5454. // replaces them by "%xx" where xx is their hexadecimal value. For
  5455. // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
  5456. // in both time and space -- important as the input str may contain an
  5457. // arbitrarily long test failure message and stack trace.
  5458. std::string StreamingListener::UrlEncode(const char* str) {
  5459. std::string result;
  5460. result.reserve(strlen(str) + 1);
  5461. for (char ch = *str; ch != '\0'; ch = *++str) {
  5462. switch (ch) {
  5463. case '%':
  5464. case '=':
  5465. case '&':
  5466. case '\n':
  5467. result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
  5468. break;
  5469. default:
  5470. result.push_back(ch);
  5471. break;
  5472. }
  5473. }
  5474. return result;
  5475. }
  5476. void StreamingListener::SocketWriter::MakeConnection() {
  5477. GTEST_CHECK_(sockfd_ == -1)
  5478. << "MakeConnection() can't be called when there is already a connection.";
  5479. addrinfo hints;
  5480. memset(&hints, 0, sizeof(hints));
  5481. hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
  5482. hints.ai_socktype = SOCK_STREAM;
  5483. addrinfo* servinfo = nullptr;
  5484. // Use the getaddrinfo() to get a linked list of IP addresses for
  5485. // the given host name.
  5486. const int error_num = getaddrinfo(
  5487. host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
  5488. if (error_num != 0) {
  5489. GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
  5490. << gai_strerror(error_num);
  5491. }
  5492. // Loop through all the results and connect to the first we can.
  5493. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
  5494. cur_addr = cur_addr->ai_next) {
  5495. sockfd_ = socket(
  5496. cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
  5497. if (sockfd_ != -1) {
  5498. // Connect the client socket to the server socket.
  5499. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
  5500. close(sockfd_);
  5501. sockfd_ = -1;
  5502. }
  5503. }
  5504. }
  5505. freeaddrinfo(servinfo); // all done with this structure
  5506. if (sockfd_ == -1) {
  5507. GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
  5508. << host_name_ << ":" << port_num_;
  5509. }
  5510. }
  5511. // End of class Streaming Listener
  5512. #endif // GTEST_CAN_STREAM_RESULTS__
  5513. // class OsStackTraceGetter
  5514. const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
  5515. "... " GTEST_NAME_ " internal frames ...";
  5516. std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
  5517. GTEST_LOCK_EXCLUDED_(mutex_) {
  5518. #if GTEST_HAS_ABSL
  5519. std::string result;
  5520. if (max_depth <= 0) {
  5521. return result;
  5522. }
  5523. max_depth = std::min(max_depth, kMaxStackTraceDepth);
  5524. std::vector<void*> raw_stack(max_depth);
  5525. // Skips the frames requested by the caller, plus this function.
  5526. const int raw_stack_size =
  5527. absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
  5528. void* caller_frame = nullptr;
  5529. {
  5530. MutexLock lock(&mutex_);
  5531. caller_frame = caller_frame_;
  5532. }
  5533. for (int i = 0; i < raw_stack_size; ++i) {
  5534. if (raw_stack[i] == caller_frame &&
  5535. !GTEST_FLAG(show_internal_stack_frames)) {
  5536. // Add a marker to the trace and stop adding frames.
  5537. absl::StrAppend(&result, kElidedFramesMarker, "\n");
  5538. break;
  5539. }
  5540. char tmp[1024];
  5541. const char* symbol = "(unknown)";
  5542. if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
  5543. symbol = tmp;
  5544. }
  5545. char line[1024];
  5546. snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
  5547. result += line;
  5548. }
  5549. return result;
  5550. #else // !GTEST_HAS_ABSL
  5551. static_cast<void>(max_depth);
  5552. static_cast<void>(skip_count);
  5553. return "";
  5554. #endif // GTEST_HAS_ABSL
  5555. }
  5556. void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
  5557. #if GTEST_HAS_ABSL
  5558. void* caller_frame = nullptr;
  5559. if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
  5560. caller_frame = nullptr;
  5561. }
  5562. MutexLock lock(&mutex_);
  5563. caller_frame_ = caller_frame;
  5564. #endif // GTEST_HAS_ABSL
  5565. }
  5566. // A helper class that creates the premature-exit file in its
  5567. // constructor and deletes the file in its destructor.
  5568. class ScopedPrematureExitFile {
  5569. public:
  5570. explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
  5571. : premature_exit_filepath_(premature_exit_filepath ?
  5572. premature_exit_filepath : "") {
  5573. // If a path to the premature-exit file is specified...
  5574. if (!premature_exit_filepath_.empty()) {
  5575. // create the file with a single "0" character in it. I/O
  5576. // errors are ignored as there's nothing better we can do and we
  5577. // don't want to fail the test because of this.
  5578. FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
  5579. fwrite("0", 1, 1, pfile);
  5580. fclose(pfile);
  5581. }
  5582. }
  5583. ~ScopedPrematureExitFile() {
  5584. #if !defined GTEST_OS_ESP8266
  5585. if (!premature_exit_filepath_.empty()) {
  5586. int retval = remove(premature_exit_filepath_.c_str());
  5587. if (retval) {
  5588. GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
  5589. << premature_exit_filepath_ << "\" with error "
  5590. << retval;
  5591. }
  5592. }
  5593. #endif
  5594. }
  5595. private:
  5596. const std::string premature_exit_filepath_;
  5597. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
  5598. };
  5599. } // namespace internal
  5600. // class TestEventListeners
  5601. TestEventListeners::TestEventListeners()
  5602. : repeater_(new internal::TestEventRepeater()),
  5603. default_result_printer_(nullptr),
  5604. default_xml_generator_(nullptr) {}
  5605. TestEventListeners::~TestEventListeners() { delete repeater_; }
  5606. // Returns the standard listener responsible for the default console
  5607. // output. Can be removed from the listeners list to shut down default
  5608. // console output. Note that removing this object from the listener list
  5609. // with Release transfers its ownership to the user.
  5610. void TestEventListeners::Append(TestEventListener* listener) {
  5611. repeater_->Append(listener);
  5612. }
  5613. // Removes the given event listener from the list and returns it. It then
  5614. // becomes the caller's responsibility to delete the listener. Returns
  5615. // NULL if the listener is not found in the list.
  5616. TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
  5617. if (listener == default_result_printer_)
  5618. default_result_printer_ = nullptr;
  5619. else if (listener == default_xml_generator_)
  5620. default_xml_generator_ = nullptr;
  5621. return repeater_->Release(listener);
  5622. }
  5623. // Returns repeater that broadcasts the TestEventListener events to all
  5624. // subscribers.
  5625. TestEventListener* TestEventListeners::repeater() { return repeater_; }
  5626. // Sets the default_result_printer attribute to the provided listener.
  5627. // The listener is also added to the listener list and previous
  5628. // default_result_printer is removed from it and deleted. The listener can
  5629. // also be NULL in which case it will not be added to the list. Does
  5630. // nothing if the previous and the current listener objects are the same.
  5631. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
  5632. if (default_result_printer_ != listener) {
  5633. // It is an error to pass this method a listener that is already in the
  5634. // list.
  5635. delete Release(default_result_printer_);
  5636. default_result_printer_ = listener;
  5637. if (listener != nullptr) Append(listener);
  5638. }
  5639. }
  5640. // Sets the default_xml_generator attribute to the provided listener. The
  5641. // listener is also added to the listener list and previous
  5642. // default_xml_generator is removed from it and deleted. The listener can
  5643. // also be NULL in which case it will not be added to the list. Does
  5644. // nothing if the previous and the current listener objects are the same.
  5645. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
  5646. if (default_xml_generator_ != listener) {
  5647. // It is an error to pass this method a listener that is already in the
  5648. // list.
  5649. delete Release(default_xml_generator_);
  5650. default_xml_generator_ = listener;
  5651. if (listener != nullptr) Append(listener);
  5652. }
  5653. }
  5654. // Controls whether events will be forwarded by the repeater to the
  5655. // listeners in the list.
  5656. bool TestEventListeners::EventForwardingEnabled() const {
  5657. return repeater_->forwarding_enabled();
  5658. }
  5659. void TestEventListeners::SuppressEventForwarding() {
  5660. repeater_->set_forwarding_enabled(false);
  5661. }
  5662. // class UnitTest
  5663. // Gets the singleton UnitTest object. The first time this method is
  5664. // called, a UnitTest object is constructed and returned. Consecutive
  5665. // calls will return the same object.
  5666. //
  5667. // We don't protect this under mutex_ as a user is not supposed to
  5668. // call this before main() starts, from which point on the return
  5669. // value will never change.
  5670. UnitTest* UnitTest::GetInstance() {
  5671. // CodeGear C++Builder insists on a public destructor for the
  5672. // default implementation. Use this implementation to keep good OO
  5673. // design with private destructor.
  5674. #if defined(__BORLANDC__)
  5675. static UnitTest* const instance = new UnitTest;
  5676. return instance;
  5677. #else
  5678. static UnitTest instance;
  5679. return &instance;
  5680. #endif // defined(__BORLANDC__)
  5681. }
  5682. // Gets the number of successful test suites.
  5683. int UnitTest::successful_test_suite_count() const {
  5684. return impl()->successful_test_suite_count();
  5685. }
  5686. // Gets the number of failed test suites.
  5687. int UnitTest::failed_test_suite_count() const {
  5688. return impl()->failed_test_suite_count();
  5689. }
  5690. // Gets the number of all test suites.
  5691. int UnitTest::total_test_suite_count() const {
  5692. return impl()->total_test_suite_count();
  5693. }
  5694. // Gets the number of all test suites that contain at least one test
  5695. // that should run.
  5696. int UnitTest::test_suite_to_run_count() const {
  5697. return impl()->test_suite_to_run_count();
  5698. }
  5699. // Legacy API is deprecated but still available
  5700. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5701. int UnitTest::successful_test_case_count() const {
  5702. return impl()->successful_test_suite_count();
  5703. }
  5704. int UnitTest::failed_test_case_count() const {
  5705. return impl()->failed_test_suite_count();
  5706. }
  5707. int UnitTest::total_test_case_count() const {
  5708. return impl()->total_test_suite_count();
  5709. }
  5710. int UnitTest::test_case_to_run_count() const {
  5711. return impl()->test_suite_to_run_count();
  5712. }
  5713. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5714. // Gets the number of successful tests.
  5715. int UnitTest::successful_test_count() const {
  5716. return impl()->successful_test_count();
  5717. }
  5718. // Gets the number of skipped tests.
  5719. int UnitTest::skipped_test_count() const {
  5720. return impl()->skipped_test_count();
  5721. }
  5722. // Gets the number of failed tests.
  5723. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
  5724. // Gets the number of disabled tests that will be reported in the XML report.
  5725. int UnitTest::reportable_disabled_test_count() const {
  5726. return impl()->reportable_disabled_test_count();
  5727. }
  5728. // Gets the number of disabled tests.
  5729. int UnitTest::disabled_test_count() const {
  5730. return impl()->disabled_test_count();
  5731. }
  5732. // Gets the number of tests to be printed in the XML report.
  5733. int UnitTest::reportable_test_count() const {
  5734. return impl()->reportable_test_count();
  5735. }
  5736. // Gets the number of all tests.
  5737. int UnitTest::total_test_count() const { return impl()->total_test_count(); }
  5738. // Gets the number of tests that should run.
  5739. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
  5740. // Gets the time of the test program start, in ms from the start of the
  5741. // UNIX epoch.
  5742. internal::TimeInMillis UnitTest::start_timestamp() const {
  5743. return impl()->start_timestamp();
  5744. }
  5745. // Gets the elapsed time, in milliseconds.
  5746. internal::TimeInMillis UnitTest::elapsed_time() const {
  5747. return impl()->elapsed_time();
  5748. }
  5749. // Returns true if and only if the unit test passed (i.e. all test suites
  5750. // passed).
  5751. bool UnitTest::Passed() const { return impl()->Passed(); }
  5752. // Returns true if and only if the unit test failed (i.e. some test suite
  5753. // failed or something outside of all tests failed).
  5754. bool UnitTest::Failed() const { return impl()->Failed(); }
  5755. // Gets the i-th test suite among all the test suites. i can range from 0 to
  5756. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  5757. const TestSuite* UnitTest::GetTestSuite(int i) const {
  5758. return impl()->GetTestSuite(i);
  5759. }
  5760. // Legacy API is deprecated but still available
  5761. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5762. const TestCase* UnitTest::GetTestCase(int i) const {
  5763. return impl()->GetTestCase(i);
  5764. }
  5765. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5766. // Returns the TestResult containing information on test failures and
  5767. // properties logged outside of individual test suites.
  5768. const TestResult& UnitTest::ad_hoc_test_result() const {
  5769. return *impl()->ad_hoc_test_result();
  5770. }
  5771. // Gets the i-th test suite among all the test suites. i can range from 0 to
  5772. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  5773. TestSuite* UnitTest::GetMutableTestSuite(int i) {
  5774. return impl()->GetMutableSuiteCase(i);
  5775. }
  5776. // Returns the list of event listeners that can be used to track events
  5777. // inside Google Test.
  5778. TestEventListeners& UnitTest::listeners() {
  5779. return *impl()->listeners();
  5780. }
  5781. // Registers and returns a global test environment. When a test
  5782. // program is run, all global test environments will be set-up in the
  5783. // order they were registered. After all tests in the program have
  5784. // finished, all global test environments will be torn-down in the
  5785. // *reverse* order they were registered.
  5786. //
  5787. // The UnitTest object takes ownership of the given environment.
  5788. //
  5789. // We don't protect this under mutex_, as we only support calling it
  5790. // from the main thread.
  5791. Environment* UnitTest::AddEnvironment(Environment* env) {
  5792. if (env == nullptr) {
  5793. return nullptr;
  5794. }
  5795. impl_->environments().push_back(env);
  5796. return env;
  5797. }
  5798. // Adds a TestPartResult to the current TestResult object. All Google Test
  5799. // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
  5800. // this to report their results. The user code should use the
  5801. // assertion macros instead of calling this directly.
  5802. void UnitTest::AddTestPartResult(
  5803. TestPartResult::Type result_type,
  5804. const char* file_name,
  5805. int line_number,
  5806. const std::string& message,
  5807. const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
  5808. Message msg;
  5809. msg << message;
  5810. internal::MutexLock lock(&mutex_);
  5811. if (impl_->gtest_trace_stack().size() > 0) {
  5812. msg << "\n" << GTEST_NAME_ << " trace:";
  5813. for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
  5814. const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
  5815. msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
  5816. << " " << trace.message;
  5817. }
  5818. }
  5819. if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
  5820. msg << internal::kStackTraceMarker << os_stack_trace;
  5821. }
  5822. const TestPartResult result = TestPartResult(
  5823. result_type, file_name, line_number, msg.GetString().c_str());
  5824. impl_->GetTestPartResultReporterForCurrentThread()->
  5825. ReportTestPartResult(result);
  5826. if (result_type != TestPartResult::kSuccess &&
  5827. result_type != TestPartResult::kSkip) {
  5828. // gtest_break_on_failure takes precedence over
  5829. // gtest_throw_on_failure. This allows a user to set the latter
  5830. // in the code (perhaps in order to use Google Test assertions
  5831. // with another testing framework) and specify the former on the
  5832. // command line for debugging.
  5833. if (GTEST_FLAG(break_on_failure)) {
  5834. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  5835. // Using DebugBreak on Windows allows gtest to still break into a debugger
  5836. // when a failure happens and both the --gtest_break_on_failure and
  5837. // the --gtest_catch_exceptions flags are specified.
  5838. DebugBreak();
  5839. #elif (!defined(__native_client__)) && \
  5840. ((defined(__clang__) || defined(__GNUC__)) && \
  5841. (defined(__x86_64__) || defined(__i386__)))
  5842. // with clang/gcc we can achieve the same effect on x86 by invoking int3
  5843. asm("int3");
  5844. #else
  5845. // Dereference nullptr through a volatile pointer to prevent the compiler
  5846. // from removing. We use this rather than abort() or __builtin_trap() for
  5847. // portability: some debuggers don't correctly trap abort().
  5848. *static_cast<volatile int*>(nullptr) = 1;
  5849. #endif // GTEST_OS_WINDOWS
  5850. } else if (GTEST_FLAG(throw_on_failure)) {
  5851. #if GTEST_HAS_EXCEPTIONS
  5852. throw internal::GoogleTestFailureException(result);
  5853. #else
  5854. // We cannot call abort() as it generates a pop-up in debug mode
  5855. // that cannot be suppressed in VC 7.1 or below.
  5856. exit(1);
  5857. #endif
  5858. }
  5859. }
  5860. }
  5861. // Adds a TestProperty to the current TestResult object when invoked from
  5862. // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
  5863. // from SetUpTestSuite or TearDownTestSuite, or to the global property set
  5864. // when invoked elsewhere. If the result already contains a property with
  5865. // the same key, the value will be updated.
  5866. void UnitTest::RecordProperty(const std::string& key,
  5867. const std::string& value) {
  5868. impl_->RecordProperty(TestProperty(key, value));
  5869. }
  5870. // Runs all tests in this UnitTest object and prints the result.
  5871. // Returns 0 if successful, or 1 otherwise.
  5872. //
  5873. // We don't protect this under mutex_, as we only support calling it
  5874. // from the main thread.
  5875. int UnitTest::Run() {
  5876. const bool in_death_test_child_process =
  5877. internal::GTEST_FLAG(internal_run_death_test).length() > 0;
  5878. // Google Test implements this protocol for catching that a test
  5879. // program exits before returning control to Google Test:
  5880. //
  5881. // 1. Upon start, Google Test creates a file whose absolute path
  5882. // is specified by the environment variable
  5883. // TEST_PREMATURE_EXIT_FILE.
  5884. // 2. When Google Test has finished its work, it deletes the file.
  5885. //
  5886. // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
  5887. // running a Google-Test-based test program and check the existence
  5888. // of the file at the end of the test execution to see if it has
  5889. // exited prematurely.
  5890. // If we are in the child process of a death test, don't
  5891. // create/delete the premature exit file, as doing so is unnecessary
  5892. // and will confuse the parent process. Otherwise, create/delete
  5893. // the file upon entering/leaving this function. If the program
  5894. // somehow exits before this function has a chance to return, the
  5895. // premature-exit file will be left undeleted, causing a test runner
  5896. // that understands the premature-exit-file protocol to report the
  5897. // test as having failed.
  5898. const internal::ScopedPrematureExitFile premature_exit_file(
  5899. in_death_test_child_process
  5900. ? nullptr
  5901. : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
  5902. // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
  5903. // used for the duration of the program.
  5904. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
  5905. #if GTEST_OS_WINDOWS
  5906. // Either the user wants Google Test to catch exceptions thrown by the
  5907. // tests or this is executing in the context of death test child
  5908. // process. In either case the user does not want to see pop-up dialogs
  5909. // about crashes - they are expected.
  5910. if (impl()->catch_exceptions() || in_death_test_child_process) {
  5911. # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  5912. // SetErrorMode doesn't exist on CE.
  5913. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
  5914. SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
  5915. # endif // !GTEST_OS_WINDOWS_MOBILE
  5916. # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
  5917. // Death test children can be terminated with _abort(). On Windows,
  5918. // _abort() can show a dialog with a warning message. This forces the
  5919. // abort message to go to stderr instead.
  5920. _set_error_mode(_OUT_TO_STDERR);
  5921. # endif
  5922. # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
  5923. // In the debug version, Visual Studio pops up a separate dialog
  5924. // offering a choice to debug the aborted program. We need to suppress
  5925. // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
  5926. // executed. Google Test will notify the user of any unexpected
  5927. // failure via stderr.
  5928. if (!GTEST_FLAG(break_on_failure))
  5929. _set_abort_behavior(
  5930. 0x0, // Clear the following flags:
  5931. _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
  5932. // In debug mode, the Windows CRT can crash with an assertion over invalid
  5933. // input (e.g. passing an invalid file descriptor). The default handling
  5934. // for these assertions is to pop up a dialog and wait for user input.
  5935. // Instead ask the CRT to dump such assertions to stderr non-interactively.
  5936. if (!IsDebuggerPresent()) {
  5937. (void)_CrtSetReportMode(_CRT_ASSERT,
  5938. _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  5939. (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
  5940. }
  5941. # endif
  5942. }
  5943. #endif // GTEST_OS_WINDOWS
  5944. return internal::HandleExceptionsInMethodIfSupported(
  5945. impl(),
  5946. &internal::UnitTestImpl::RunAllTests,
  5947. "auxiliary test code (environments or event listeners)") ? 0 : 1;
  5948. }
  5949. // Returns the working directory when the first TEST() or TEST_F() was
  5950. // executed.
  5951. const char* UnitTest::original_working_dir() const {
  5952. return impl_->original_working_dir_.c_str();
  5953. }
  5954. // Returns the TestSuite object for the test that's currently running,
  5955. // or NULL if no test is running.
  5956. const TestSuite* UnitTest::current_test_suite() const
  5957. GTEST_LOCK_EXCLUDED_(mutex_) {
  5958. internal::MutexLock lock(&mutex_);
  5959. return impl_->current_test_suite();
  5960. }
  5961. // Legacy API is still available but deprecated
  5962. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5963. const TestCase* UnitTest::current_test_case() const
  5964. GTEST_LOCK_EXCLUDED_(mutex_) {
  5965. internal::MutexLock lock(&mutex_);
  5966. return impl_->current_test_suite();
  5967. }
  5968. #endif
  5969. // Returns the TestInfo object for the test that's currently running,
  5970. // or NULL if no test is running.
  5971. const TestInfo* UnitTest::current_test_info() const
  5972. GTEST_LOCK_EXCLUDED_(mutex_) {
  5973. internal::MutexLock lock(&mutex_);
  5974. return impl_->current_test_info();
  5975. }
  5976. // Returns the random seed used at the start of the current test run.
  5977. int UnitTest::random_seed() const { return impl_->random_seed(); }
  5978. // Returns ParameterizedTestSuiteRegistry object used to keep track of
  5979. // value-parameterized tests and instantiate and register them.
  5980. internal::ParameterizedTestSuiteRegistry&
  5981. UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
  5982. return impl_->parameterized_test_registry();
  5983. }
  5984. // Creates an empty UnitTest.
  5985. UnitTest::UnitTest() {
  5986. impl_ = new internal::UnitTestImpl(this);
  5987. }
  5988. // Destructor of UnitTest.
  5989. UnitTest::~UnitTest() {
  5990. delete impl_;
  5991. }
  5992. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  5993. // Google Test trace stack.
  5994. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
  5995. GTEST_LOCK_EXCLUDED_(mutex_) {
  5996. internal::MutexLock lock(&mutex_);
  5997. impl_->gtest_trace_stack().push_back(trace);
  5998. }
  5999. // Pops a trace from the per-thread Google Test trace stack.
  6000. void UnitTest::PopGTestTrace()
  6001. GTEST_LOCK_EXCLUDED_(mutex_) {
  6002. internal::MutexLock lock(&mutex_);
  6003. impl_->gtest_trace_stack().pop_back();
  6004. }
  6005. namespace internal {
  6006. UnitTestImpl::UnitTestImpl(UnitTest* parent)
  6007. : parent_(parent),
  6008. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
  6009. default_global_test_part_result_reporter_(this),
  6010. default_per_thread_test_part_result_reporter_(this),
  6011. GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
  6012. &default_global_test_part_result_reporter_),
  6013. per_thread_test_part_result_reporter_(
  6014. &default_per_thread_test_part_result_reporter_),
  6015. parameterized_test_registry_(),
  6016. parameterized_tests_registered_(false),
  6017. last_death_test_suite_(-1),
  6018. current_test_suite_(nullptr),
  6019. current_test_info_(nullptr),
  6020. ad_hoc_test_result_(),
  6021. os_stack_trace_getter_(nullptr),
  6022. post_flag_parse_init_performed_(false),
  6023. random_seed_(0), // Will be overridden by the flag before first use.
  6024. random_(0), // Will be reseeded before first use.
  6025. start_timestamp_(0),
  6026. elapsed_time_(0),
  6027. #if GTEST_HAS_DEATH_TEST
  6028. death_test_factory_(new DefaultDeathTestFactory),
  6029. #endif
  6030. // Will be overridden by the flag before first use.
  6031. catch_exceptions_(false) {
  6032. listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
  6033. }
  6034. UnitTestImpl::~UnitTestImpl() {
  6035. // Deletes every TestSuite.
  6036. ForEach(test_suites_, internal::Delete<TestSuite>);
  6037. // Deletes every Environment.
  6038. ForEach(environments_, internal::Delete<Environment>);
  6039. delete os_stack_trace_getter_;
  6040. }
  6041. // Adds a TestProperty to the current TestResult object when invoked in a
  6042. // context of a test, to current test suite's ad_hoc_test_result when invoke
  6043. // from SetUpTestSuite/TearDownTestSuite, or to the global property set
  6044. // otherwise. If the result already contains a property with the same key,
  6045. // the value will be updated.
  6046. void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
  6047. std::string xml_element;
  6048. TestResult* test_result; // TestResult appropriate for property recording.
  6049. if (current_test_info_ != nullptr) {
  6050. xml_element = "testcase";
  6051. test_result = &(current_test_info_->result_);
  6052. } else if (current_test_suite_ != nullptr) {
  6053. xml_element = "testsuite";
  6054. test_result = &(current_test_suite_->ad_hoc_test_result_);
  6055. } else {
  6056. xml_element = "testsuites";
  6057. test_result = &ad_hoc_test_result_;
  6058. }
  6059. test_result->RecordProperty(xml_element, test_property);
  6060. }
  6061. #if GTEST_HAS_DEATH_TEST
  6062. // Disables event forwarding if the control is currently in a death test
  6063. // subprocess. Must not be called before InitGoogleTest.
  6064. void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
  6065. if (internal_run_death_test_flag_.get() != nullptr)
  6066. listeners()->SuppressEventForwarding();
  6067. }
  6068. #endif // GTEST_HAS_DEATH_TEST
  6069. // Initializes event listeners performing XML output as specified by
  6070. // UnitTestOptions. Must not be called before InitGoogleTest.
  6071. void UnitTestImpl::ConfigureXmlOutput() {
  6072. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  6073. if (output_format == "xml") {
  6074. listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
  6075. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  6076. } else if (output_format == "json") {
  6077. listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
  6078. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  6079. } else if (output_format != "") {
  6080. GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
  6081. << output_format << "\" ignored.";
  6082. }
  6083. }
  6084. #if GTEST_CAN_STREAM_RESULTS_
  6085. // Initializes event listeners for streaming test results in string form.
  6086. // Must not be called before InitGoogleTest.
  6087. void UnitTestImpl::ConfigureStreamingOutput() {
  6088. const std::string& target = GTEST_FLAG(stream_result_to);
  6089. if (!target.empty()) {
  6090. const size_t pos = target.find(':');
  6091. if (pos != std::string::npos) {
  6092. listeners()->Append(new StreamingListener(target.substr(0, pos),
  6093. target.substr(pos+1)));
  6094. } else {
  6095. GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
  6096. << "\" ignored.";
  6097. }
  6098. }
  6099. }
  6100. #endif // GTEST_CAN_STREAM_RESULTS_
  6101. // Performs initialization dependent upon flag values obtained in
  6102. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  6103. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  6104. // this function is also called from RunAllTests. Since this function can be
  6105. // called more than once, it has to be idempotent.
  6106. void UnitTestImpl::PostFlagParsingInit() {
  6107. // Ensures that this function does not execute more than once.
  6108. if (!post_flag_parse_init_performed_) {
  6109. post_flag_parse_init_performed_ = true;
  6110. #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  6111. // Register to send notifications about key process state changes.
  6112. listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
  6113. #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  6114. #if GTEST_HAS_DEATH_TEST
  6115. InitDeathTestSubprocessControlInfo();
  6116. SuppressTestEventsIfInSubprocess();
  6117. #endif // GTEST_HAS_DEATH_TEST
  6118. // Registers parameterized tests. This makes parameterized tests
  6119. // available to the UnitTest reflection API without running
  6120. // RUN_ALL_TESTS.
  6121. RegisterParameterizedTests();
  6122. // Configures listeners for XML output. This makes it possible for users
  6123. // to shut down the default XML output before invoking RUN_ALL_TESTS.
  6124. ConfigureXmlOutput();
  6125. if (GTEST_FLAG(brief)) {
  6126. listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter);
  6127. }
  6128. #if GTEST_CAN_STREAM_RESULTS_
  6129. // Configures listeners for streaming test results to the specified server.
  6130. ConfigureStreamingOutput();
  6131. #endif // GTEST_CAN_STREAM_RESULTS_
  6132. #if GTEST_HAS_ABSL
  6133. if (GTEST_FLAG(install_failure_signal_handler)) {
  6134. absl::FailureSignalHandlerOptions options;
  6135. absl::InstallFailureSignalHandler(options);
  6136. }
  6137. #endif // GTEST_HAS_ABSL
  6138. }
  6139. }
  6140. // A predicate that checks the name of a TestSuite against a known
  6141. // value.
  6142. //
  6143. // This is used for implementation of the UnitTest class only. We put
  6144. // it in the anonymous namespace to prevent polluting the outer
  6145. // namespace.
  6146. //
  6147. // TestSuiteNameIs is copyable.
  6148. class TestSuiteNameIs {
  6149. public:
  6150. // Constructor.
  6151. explicit TestSuiteNameIs(const std::string& name) : name_(name) {}
  6152. // Returns true if and only if the name of test_suite matches name_.
  6153. bool operator()(const TestSuite* test_suite) const {
  6154. return test_suite != nullptr &&
  6155. strcmp(test_suite->name(), name_.c_str()) == 0;
  6156. }
  6157. private:
  6158. std::string name_;
  6159. };
  6160. // Finds and returns a TestSuite with the given name. If one doesn't
  6161. // exist, creates one and returns it. It's the CALLER'S
  6162. // RESPONSIBILITY to ensure that this function is only called WHEN THE
  6163. // TESTS ARE NOT SHUFFLED.
  6164. //
  6165. // Arguments:
  6166. //
  6167. // test_suite_name: name of the test suite
  6168. // type_param: the name of the test suite's type parameter, or NULL if
  6169. // this is not a typed or a type-parameterized test suite.
  6170. // set_up_tc: pointer to the function that sets up the test suite
  6171. // tear_down_tc: pointer to the function that tears down the test suite
  6172. TestSuite* UnitTestImpl::GetTestSuite(
  6173. const char* test_suite_name, const char* type_param,
  6174. internal::SetUpTestSuiteFunc set_up_tc,
  6175. internal::TearDownTestSuiteFunc tear_down_tc) {
  6176. // Can we find a TestSuite with the given name?
  6177. const auto test_suite =
  6178. std::find_if(test_suites_.rbegin(), test_suites_.rend(),
  6179. TestSuiteNameIs(test_suite_name));
  6180. if (test_suite != test_suites_.rend()) return *test_suite;
  6181. // No. Let's create one.
  6182. auto* const new_test_suite =
  6183. new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
  6184. // Is this a death test suite?
  6185. if (internal::UnitTestOptions::MatchesFilter(test_suite_name,
  6186. kDeathTestSuiteFilter)) {
  6187. // Yes. Inserts the test suite after the last death test suite
  6188. // defined so far. This only works when the test suites haven't
  6189. // been shuffled. Otherwise we may end up running a death test
  6190. // after a non-death test.
  6191. ++last_death_test_suite_;
  6192. test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
  6193. new_test_suite);
  6194. } else {
  6195. // No. Appends to the end of the list.
  6196. test_suites_.push_back(new_test_suite);
  6197. }
  6198. test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
  6199. return new_test_suite;
  6200. }
  6201. // Helpers for setting up / tearing down the given environment. They
  6202. // are for use in the ForEach() function.
  6203. static void SetUpEnvironment(Environment* env) { env->SetUp(); }
  6204. static void TearDownEnvironment(Environment* env) { env->TearDown(); }
  6205. // Runs all tests in this UnitTest object, prints the result, and
  6206. // returns true if all tests are successful. If any exception is
  6207. // thrown during a test, the test is considered to be failed, but the
  6208. // rest of the tests will still be run.
  6209. //
  6210. // When parameterized tests are enabled, it expands and registers
  6211. // parameterized tests first in RegisterParameterizedTests().
  6212. // All other functions called from RunAllTests() may safely assume that
  6213. // parameterized tests are ready to be counted and run.
  6214. bool UnitTestImpl::RunAllTests() {
  6215. // True if and only if Google Test is initialized before RUN_ALL_TESTS() is
  6216. // called.
  6217. const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
  6218. // Do not run any test if the --help flag was specified.
  6219. if (g_help_flag)
  6220. return true;
  6221. // Repeats the call to the post-flag parsing initialization in case the
  6222. // user didn't call InitGoogleTest.
  6223. PostFlagParsingInit();
  6224. // Even if sharding is not on, test runners may want to use the
  6225. // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
  6226. // protocol.
  6227. internal::WriteToShardStatusFileIfNeeded();
  6228. // True if and only if we are in a subprocess for running a thread-safe-style
  6229. // death test.
  6230. bool in_subprocess_for_death_test = false;
  6231. #if GTEST_HAS_DEATH_TEST
  6232. in_subprocess_for_death_test =
  6233. (internal_run_death_test_flag_.get() != nullptr);
  6234. # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  6235. if (in_subprocess_for_death_test) {
  6236. GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
  6237. }
  6238. # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  6239. #endif // GTEST_HAS_DEATH_TEST
  6240. const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
  6241. in_subprocess_for_death_test);
  6242. // Compares the full test names with the filter to decide which
  6243. // tests to run.
  6244. const bool has_tests_to_run = FilterTests(should_shard
  6245. ? HONOR_SHARDING_PROTOCOL
  6246. : IGNORE_SHARDING_PROTOCOL) > 0;
  6247. // Lists the tests and exits if the --gtest_list_tests flag was specified.
  6248. if (GTEST_FLAG(list_tests)) {
  6249. // This must be called *after* FilterTests() has been called.
  6250. ListTestsMatchingFilter();
  6251. return true;
  6252. }
  6253. random_seed_ = GTEST_FLAG(shuffle) ?
  6254. GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
  6255. // True if and only if at least one test has failed.
  6256. bool failed = false;
  6257. TestEventListener* repeater = listeners()->repeater();
  6258. start_timestamp_ = GetTimeInMillis();
  6259. repeater->OnTestProgramStart(*parent_);
  6260. // How many times to repeat the tests? We don't want to repeat them
  6261. // when we are inside the subprocess of a death test.
  6262. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
  6263. // Repeats forever if the repeat count is negative.
  6264. const bool gtest_repeat_forever = repeat < 0;
  6265. for (int i = 0; gtest_repeat_forever || i != repeat; i++) {
  6266. // We want to preserve failures generated by ad-hoc test
  6267. // assertions executed before RUN_ALL_TESTS().
  6268. ClearNonAdHocTestResult();
  6269. Timer timer;
  6270. // Shuffles test suites and tests if requested.
  6271. if (has_tests_to_run && GTEST_FLAG(shuffle)) {
  6272. random()->Reseed(static_cast<uint32_t>(random_seed_));
  6273. // This should be done before calling OnTestIterationStart(),
  6274. // such that a test event listener can see the actual test order
  6275. // in the event.
  6276. ShuffleTests();
  6277. }
  6278. // Tells the unit test event listeners that the tests are about to start.
  6279. repeater->OnTestIterationStart(*parent_, i);
  6280. // Runs each test suite if there is at least one test to run.
  6281. if (has_tests_to_run) {
  6282. // Sets up all environments beforehand.
  6283. repeater->OnEnvironmentsSetUpStart(*parent_);
  6284. ForEach(environments_, SetUpEnvironment);
  6285. repeater->OnEnvironmentsSetUpEnd(*parent_);
  6286. // Runs the tests only if there was no fatal failure or skip triggered
  6287. // during global set-up.
  6288. if (Test::IsSkipped()) {
  6289. // Emit diagnostics when global set-up calls skip, as it will not be
  6290. // emitted by default.
  6291. TestResult& test_result =
  6292. *internal::GetUnitTestImpl()->current_test_result();
  6293. for (int j = 0; j < test_result.total_part_count(); ++j) {
  6294. const TestPartResult& test_part_result =
  6295. test_result.GetTestPartResult(j);
  6296. if (test_part_result.type() == TestPartResult::kSkip) {
  6297. const std::string& result = test_part_result.message();
  6298. printf("%s\n", result.c_str());
  6299. }
  6300. }
  6301. fflush(stdout);
  6302. } else if (!Test::HasFatalFailure()) {
  6303. for (int test_index = 0; test_index < total_test_suite_count();
  6304. test_index++) {
  6305. GetMutableSuiteCase(test_index)->Run();
  6306. if (GTEST_FLAG(fail_fast) &&
  6307. GetMutableSuiteCase(test_index)->Failed()) {
  6308. for (int j = test_index + 1; j < total_test_suite_count(); j++) {
  6309. GetMutableSuiteCase(j)->Skip();
  6310. }
  6311. break;
  6312. }
  6313. }
  6314. } else if (Test::HasFatalFailure()) {
  6315. // If there was a fatal failure during the global setup then we know we
  6316. // aren't going to run any tests. Explicitly mark all of the tests as
  6317. // skipped to make this obvious in the output.
  6318. for (int test_index = 0; test_index < total_test_suite_count();
  6319. test_index++) {
  6320. GetMutableSuiteCase(test_index)->Skip();
  6321. }
  6322. }
  6323. // Tears down all environments in reverse order afterwards.
  6324. repeater->OnEnvironmentsTearDownStart(*parent_);
  6325. std::for_each(environments_.rbegin(), environments_.rend(),
  6326. TearDownEnvironment);
  6327. repeater->OnEnvironmentsTearDownEnd(*parent_);
  6328. }
  6329. elapsed_time_ = timer.Elapsed();
  6330. // Tells the unit test event listener that the tests have just finished.
  6331. repeater->OnTestIterationEnd(*parent_, i);
  6332. // Gets the result and clears it.
  6333. if (!Passed()) {
  6334. failed = true;
  6335. }
  6336. // Restores the original test order after the iteration. This
  6337. // allows the user to quickly repro a failure that happens in the
  6338. // N-th iteration without repeating the first (N - 1) iterations.
  6339. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
  6340. // case the user somehow changes the value of the flag somewhere
  6341. // (it's always safe to unshuffle the tests).
  6342. UnshuffleTests();
  6343. if (GTEST_FLAG(shuffle)) {
  6344. // Picks a new random seed for each iteration.
  6345. random_seed_ = GetNextRandomSeed(random_seed_);
  6346. }
  6347. }
  6348. repeater->OnTestProgramEnd(*parent_);
  6349. if (!gtest_is_initialized_before_run_all_tests) {
  6350. ColoredPrintf(
  6351. GTestColor::kRed,
  6352. "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
  6353. "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
  6354. "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
  6355. " will start to enforce the valid usage. "
  6356. "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
  6357. #if GTEST_FOR_GOOGLE_
  6358. ColoredPrintf(GTestColor::kRed,
  6359. "For more details, see http://wiki/Main/ValidGUnitMain.\n");
  6360. #endif // GTEST_FOR_GOOGLE_
  6361. }
  6362. return !failed;
  6363. }
  6364. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  6365. // if the variable is present. If a file already exists at this location, this
  6366. // function will write over it. If the variable is present, but the file cannot
  6367. // be created, prints an error and exits.
  6368. void WriteToShardStatusFileIfNeeded() {
  6369. const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
  6370. if (test_shard_file != nullptr) {
  6371. FILE* const file = posix::FOpen(test_shard_file, "w");
  6372. if (file == nullptr) {
  6373. ColoredPrintf(GTestColor::kRed,
  6374. "Could not write to the test shard status file \"%s\" "
  6375. "specified by the %s environment variable.\n",
  6376. test_shard_file, kTestShardStatusFile);
  6377. fflush(stdout);
  6378. exit(EXIT_FAILURE);
  6379. }
  6380. fclose(file);
  6381. }
  6382. }
  6383. // Checks whether sharding is enabled by examining the relevant
  6384. // environment variable values. If the variables are present,
  6385. // but inconsistent (i.e., shard_index >= total_shards), prints
  6386. // an error and exits. If in_subprocess_for_death_test, sharding is
  6387. // disabled because it must only be applied to the original test
  6388. // process. Otherwise, we could filter out death tests we intended to execute.
  6389. bool ShouldShard(const char* total_shards_env,
  6390. const char* shard_index_env,
  6391. bool in_subprocess_for_death_test) {
  6392. if (in_subprocess_for_death_test) {
  6393. return false;
  6394. }
  6395. const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1);
  6396. const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1);
  6397. if (total_shards == -1 && shard_index == -1) {
  6398. return false;
  6399. } else if (total_shards == -1 && shard_index != -1) {
  6400. const Message msg = Message()
  6401. << "Invalid environment variables: you have "
  6402. << kTestShardIndex << " = " << shard_index
  6403. << ", but have left " << kTestTotalShards << " unset.\n";
  6404. ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
  6405. fflush(stdout);
  6406. exit(EXIT_FAILURE);
  6407. } else if (total_shards != -1 && shard_index == -1) {
  6408. const Message msg = Message()
  6409. << "Invalid environment variables: you have "
  6410. << kTestTotalShards << " = " << total_shards
  6411. << ", but have left " << kTestShardIndex << " unset.\n";
  6412. ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
  6413. fflush(stdout);
  6414. exit(EXIT_FAILURE);
  6415. } else if (shard_index < 0 || shard_index >= total_shards) {
  6416. const Message msg = Message()
  6417. << "Invalid environment variables: we require 0 <= "
  6418. << kTestShardIndex << " < " << kTestTotalShards
  6419. << ", but you have " << kTestShardIndex << "=" << shard_index
  6420. << ", " << kTestTotalShards << "=" << total_shards << ".\n";
  6421. ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
  6422. fflush(stdout);
  6423. exit(EXIT_FAILURE);
  6424. }
  6425. return total_shards > 1;
  6426. }
  6427. // Parses the environment variable var as an Int32. If it is unset,
  6428. // returns default_val. If it is not an Int32, prints an error
  6429. // and aborts.
  6430. int32_t Int32FromEnvOrDie(const char* var, int32_t default_val) {
  6431. const char* str_val = posix::GetEnv(var);
  6432. if (str_val == nullptr) {
  6433. return default_val;
  6434. }
  6435. int32_t result;
  6436. if (!ParseInt32(Message() << "The value of environment variable " << var,
  6437. str_val, &result)) {
  6438. exit(EXIT_FAILURE);
  6439. }
  6440. return result;
  6441. }
  6442. // Given the total number of shards, the shard index, and the test id,
  6443. // returns true if and only if the test should be run on this shard. The test id
  6444. // is some arbitrary but unique non-negative integer assigned to each test
  6445. // method. Assumes that 0 <= shard_index < total_shards.
  6446. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
  6447. return (test_id % total_shards) == shard_index;
  6448. }
  6449. // Compares the name of each test with the user-specified filter to
  6450. // decide whether the test should be run, then records the result in
  6451. // each TestSuite and TestInfo object.
  6452. // If shard_tests == true, further filters tests based on sharding
  6453. // variables in the environment - see
  6454. // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
  6455. // . Returns the number of tests that should run.
  6456. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
  6457. const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
  6458. Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
  6459. const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
  6460. Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
  6461. // num_runnable_tests are the number of tests that will
  6462. // run across all shards (i.e., match filter and are not disabled).
  6463. // num_selected_tests are the number of tests to be run on
  6464. // this shard.
  6465. int num_runnable_tests = 0;
  6466. int num_selected_tests = 0;
  6467. for (auto* test_suite : test_suites_) {
  6468. const std::string& test_suite_name = test_suite->name();
  6469. test_suite->set_should_run(false);
  6470. for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
  6471. TestInfo* const test_info = test_suite->test_info_list()[j];
  6472. const std::string test_name(test_info->name());
  6473. // A test is disabled if test suite name or test name matches
  6474. // kDisableTestFilter.
  6475. const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
  6476. test_suite_name, kDisableTestFilter) ||
  6477. internal::UnitTestOptions::MatchesFilter(
  6478. test_name, kDisableTestFilter);
  6479. test_info->is_disabled_ = is_disabled;
  6480. const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
  6481. test_suite_name, test_name);
  6482. test_info->matches_filter_ = matches_filter;
  6483. const bool is_runnable =
  6484. (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
  6485. matches_filter;
  6486. const bool is_in_another_shard =
  6487. shard_tests != IGNORE_SHARDING_PROTOCOL &&
  6488. !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
  6489. test_info->is_in_another_shard_ = is_in_another_shard;
  6490. const bool is_selected = is_runnable && !is_in_another_shard;
  6491. num_runnable_tests += is_runnable;
  6492. num_selected_tests += is_selected;
  6493. test_info->should_run_ = is_selected;
  6494. test_suite->set_should_run(test_suite->should_run() || is_selected);
  6495. }
  6496. }
  6497. return num_selected_tests;
  6498. }
  6499. // Prints the given C-string on a single line by replacing all '\n'
  6500. // characters with string "\\n". If the output takes more than
  6501. // max_length characters, only prints the first max_length characters
  6502. // and "...".
  6503. static void PrintOnOneLine(const char* str, int max_length) {
  6504. if (str != nullptr) {
  6505. for (int i = 0; *str != '\0'; ++str) {
  6506. if (i >= max_length) {
  6507. printf("...");
  6508. break;
  6509. }
  6510. if (*str == '\n') {
  6511. printf("\\n");
  6512. i += 2;
  6513. } else {
  6514. printf("%c", *str);
  6515. ++i;
  6516. }
  6517. }
  6518. }
  6519. }
  6520. // Prints the names of the tests matching the user-specified filter flag.
  6521. void UnitTestImpl::ListTestsMatchingFilter() {
  6522. // Print at most this many characters for each type/value parameter.
  6523. const int kMaxParamLength = 250;
  6524. for (auto* test_suite : test_suites_) {
  6525. bool printed_test_suite_name = false;
  6526. for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
  6527. const TestInfo* const test_info = test_suite->test_info_list()[j];
  6528. if (test_info->matches_filter_) {
  6529. if (!printed_test_suite_name) {
  6530. printed_test_suite_name = true;
  6531. printf("%s.", test_suite->name());
  6532. if (test_suite->type_param() != nullptr) {
  6533. printf(" # %s = ", kTypeParamLabel);
  6534. // We print the type parameter on a single line to make
  6535. // the output easy to parse by a program.
  6536. PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
  6537. }
  6538. printf("\n");
  6539. }
  6540. printf(" %s", test_info->name());
  6541. if (test_info->value_param() != nullptr) {
  6542. printf(" # %s = ", kValueParamLabel);
  6543. // We print the value parameter on a single line to make the
  6544. // output easy to parse by a program.
  6545. PrintOnOneLine(test_info->value_param(), kMaxParamLength);
  6546. }
  6547. printf("\n");
  6548. }
  6549. }
  6550. }
  6551. fflush(stdout);
  6552. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  6553. if (output_format == "xml" || output_format == "json") {
  6554. FILE* fileout = OpenFileForWriting(
  6555. UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
  6556. std::stringstream stream;
  6557. if (output_format == "xml") {
  6558. XmlUnitTestResultPrinter(
  6559. UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  6560. .PrintXmlTestsList(&stream, test_suites_);
  6561. } else if (output_format == "json") {
  6562. JsonUnitTestResultPrinter(
  6563. UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  6564. .PrintJsonTestList(&stream, test_suites_);
  6565. }
  6566. fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
  6567. fclose(fileout);
  6568. }
  6569. }
  6570. // Sets the OS stack trace getter.
  6571. //
  6572. // Does nothing if the input and the current OS stack trace getter are
  6573. // the same; otherwise, deletes the old getter and makes the input the
  6574. // current getter.
  6575. void UnitTestImpl::set_os_stack_trace_getter(
  6576. OsStackTraceGetterInterface* getter) {
  6577. if (os_stack_trace_getter_ != getter) {
  6578. delete os_stack_trace_getter_;
  6579. os_stack_trace_getter_ = getter;
  6580. }
  6581. }
  6582. // Returns the current OS stack trace getter if it is not NULL;
  6583. // otherwise, creates an OsStackTraceGetter, makes it the current
  6584. // getter, and returns it.
  6585. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
  6586. if (os_stack_trace_getter_ == nullptr) {
  6587. #ifdef GTEST_OS_STACK_TRACE_GETTER_
  6588. os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
  6589. #else
  6590. os_stack_trace_getter_ = new OsStackTraceGetter;
  6591. #endif // GTEST_OS_STACK_TRACE_GETTER_
  6592. }
  6593. return os_stack_trace_getter_;
  6594. }
  6595. // Returns the most specific TestResult currently running.
  6596. TestResult* UnitTestImpl::current_test_result() {
  6597. if (current_test_info_ != nullptr) {
  6598. return &current_test_info_->result_;
  6599. }
  6600. if (current_test_suite_ != nullptr) {
  6601. return &current_test_suite_->ad_hoc_test_result_;
  6602. }
  6603. return &ad_hoc_test_result_;
  6604. }
  6605. // Shuffles all test suites, and the tests within each test suite,
  6606. // making sure that death tests are still run first.
  6607. void UnitTestImpl::ShuffleTests() {
  6608. // Shuffles the death test suites.
  6609. ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
  6610. // Shuffles the non-death test suites.
  6611. ShuffleRange(random(), last_death_test_suite_ + 1,
  6612. static_cast<int>(test_suites_.size()), &test_suite_indices_);
  6613. // Shuffles the tests inside each test suite.
  6614. for (auto& test_suite : test_suites_) {
  6615. test_suite->ShuffleTests(random());
  6616. }
  6617. }
  6618. // Restores the test suites and tests to their order before the first shuffle.
  6619. void UnitTestImpl::UnshuffleTests() {
  6620. for (size_t i = 0; i < test_suites_.size(); i++) {
  6621. // Unshuffles the tests in each test suite.
  6622. test_suites_[i]->UnshuffleTests();
  6623. // Resets the index of each test suite.
  6624. test_suite_indices_[i] = static_cast<int>(i);
  6625. }
  6626. }
  6627. // Returns the current OS stack trace as an std::string.
  6628. //
  6629. // The maximum number of stack frames to be included is specified by
  6630. // the gtest_stack_trace_depth flag. The skip_count parameter
  6631. // specifies the number of top frames to be skipped, which doesn't
  6632. // count against the number of frames to be included.
  6633. //
  6634. // For example, if Foo() calls Bar(), which in turn calls
  6635. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  6636. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  6637. std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
  6638. int skip_count) {
  6639. // We pass skip_count + 1 to skip this wrapper function in addition
  6640. // to what the user really wants to skip.
  6641. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
  6642. }
  6643. // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
  6644. // suppress unreachable code warnings.
  6645. namespace {
  6646. class ClassUniqueToAlwaysTrue {};
  6647. }
  6648. bool IsTrue(bool condition) { return condition; }
  6649. bool AlwaysTrue() {
  6650. #if GTEST_HAS_EXCEPTIONS
  6651. // This condition is always false so AlwaysTrue() never actually throws,
  6652. // but it makes the compiler think that it may throw.
  6653. if (IsTrue(false))
  6654. throw ClassUniqueToAlwaysTrue();
  6655. #endif // GTEST_HAS_EXCEPTIONS
  6656. return true;
  6657. }
  6658. // If *pstr starts with the given prefix, modifies *pstr to be right
  6659. // past the prefix and returns true; otherwise leaves *pstr unchanged
  6660. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  6661. bool SkipPrefix(const char* prefix, const char** pstr) {
  6662. const size_t prefix_len = strlen(prefix);
  6663. if (strncmp(*pstr, prefix, prefix_len) == 0) {
  6664. *pstr += prefix_len;
  6665. return true;
  6666. }
  6667. return false;
  6668. }
  6669. // Parses a string as a command line flag. The string should have
  6670. // the format "--flag=value". When def_optional is true, the "=value"
  6671. // part can be omitted.
  6672. //
  6673. // Returns the value of the flag, or NULL if the parsing failed.
  6674. static const char* ParseFlagValue(const char* str, const char* flag,
  6675. bool def_optional) {
  6676. // str and flag must not be NULL.
  6677. if (str == nullptr || flag == nullptr) return nullptr;
  6678. // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
  6679. const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
  6680. const size_t flag_len = flag_str.length();
  6681. if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
  6682. // Skips the flag name.
  6683. const char* flag_end = str + flag_len;
  6684. // When def_optional is true, it's OK to not have a "=value" part.
  6685. if (def_optional && (flag_end[0] == '\0')) {
  6686. return flag_end;
  6687. }
  6688. // If def_optional is true and there are more characters after the
  6689. // flag name, or if def_optional is false, there must be a '=' after
  6690. // the flag name.
  6691. if (flag_end[0] != '=') return nullptr;
  6692. // Returns the string after "=".
  6693. return flag_end + 1;
  6694. }
  6695. // Parses a string for a bool flag, in the form of either
  6696. // "--flag=value" or "--flag".
  6697. //
  6698. // In the former case, the value is taken as true as long as it does
  6699. // not start with '0', 'f', or 'F'.
  6700. //
  6701. // In the latter case, the value is taken as true.
  6702. //
  6703. // On success, stores the value of the flag in *value, and returns
  6704. // true. On failure, returns false without changing *value.
  6705. static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
  6706. // Gets the value of the flag as a string.
  6707. const char* const value_str = ParseFlagValue(str, flag, true);
  6708. // Aborts if the parsing failed.
  6709. if (value_str == nullptr) return false;
  6710. // Converts the string value to a bool.
  6711. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  6712. return true;
  6713. }
  6714. // Parses a string for an int32_t flag, in the form of "--flag=value".
  6715. //
  6716. // On success, stores the value of the flag in *value, and returns
  6717. // true. On failure, returns false without changing *value.
  6718. bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) {
  6719. // Gets the value of the flag as a string.
  6720. const char* const value_str = ParseFlagValue(str, flag, false);
  6721. // Aborts if the parsing failed.
  6722. if (value_str == nullptr) return false;
  6723. // Sets *value to the value of the flag.
  6724. return ParseInt32(Message() << "The value of flag --" << flag,
  6725. value_str, value);
  6726. }
  6727. // Parses a string for a string flag, in the form of "--flag=value".
  6728. //
  6729. // On success, stores the value of the flag in *value, and returns
  6730. // true. On failure, returns false without changing *value.
  6731. template <typename String>
  6732. static bool ParseStringFlag(const char* str, const char* flag, String* value) {
  6733. // Gets the value of the flag as a string.
  6734. const char* const value_str = ParseFlagValue(str, flag, false);
  6735. // Aborts if the parsing failed.
  6736. if (value_str == nullptr) return false;
  6737. // Sets *value to the value of the flag.
  6738. *value = value_str;
  6739. return true;
  6740. }
  6741. // Determines whether a string has a prefix that Google Test uses for its
  6742. // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
  6743. // If Google Test detects that a command line flag has its prefix but is not
  6744. // recognized, it will print its help message. Flags starting with
  6745. // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
  6746. // internal flags and do not trigger the help message.
  6747. static bool HasGoogleTestFlagPrefix(const char* str) {
  6748. return (SkipPrefix("--", &str) ||
  6749. SkipPrefix("-", &str) ||
  6750. SkipPrefix("/", &str)) &&
  6751. !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
  6752. (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
  6753. SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
  6754. }
  6755. // Prints a string containing code-encoded text. The following escape
  6756. // sequences can be used in the string to control the text color:
  6757. //
  6758. // @@ prints a single '@' character.
  6759. // @R changes the color to red.
  6760. // @G changes the color to green.
  6761. // @Y changes the color to yellow.
  6762. // @D changes to the default terminal text color.
  6763. //
  6764. static void PrintColorEncoded(const char* str) {
  6765. GTestColor color = GTestColor::kDefault; // The current color.
  6766. // Conceptually, we split the string into segments divided by escape
  6767. // sequences. Then we print one segment at a time. At the end of
  6768. // each iteration, the str pointer advances to the beginning of the
  6769. // next segment.
  6770. for (;;) {
  6771. const char* p = strchr(str, '@');
  6772. if (p == nullptr) {
  6773. ColoredPrintf(color, "%s", str);
  6774. return;
  6775. }
  6776. ColoredPrintf(color, "%s", std::string(str, p).c_str());
  6777. const char ch = p[1];
  6778. str = p + 2;
  6779. if (ch == '@') {
  6780. ColoredPrintf(color, "@");
  6781. } else if (ch == 'D') {
  6782. color = GTestColor::kDefault;
  6783. } else if (ch == 'R') {
  6784. color = GTestColor::kRed;
  6785. } else if (ch == 'G') {
  6786. color = GTestColor::kGreen;
  6787. } else if (ch == 'Y') {
  6788. color = GTestColor::kYellow;
  6789. } else {
  6790. --str;
  6791. }
  6792. }
  6793. }
  6794. static const char kColorEncodedHelpMessage[] =
  6795. "This program contains tests written using " GTEST_NAME_
  6796. ". You can use the\n"
  6797. "following command line flags to control its behavior:\n"
  6798. "\n"
  6799. "Test Selection:\n"
  6800. " @G--" GTEST_FLAG_PREFIX_
  6801. "list_tests@D\n"
  6802. " List the names of all tests instead of running them. The name of\n"
  6803. " TEST(Foo, Bar) is \"Foo.Bar\".\n"
  6804. " @G--" GTEST_FLAG_PREFIX_
  6805. "filter=@YPOSITIVE_PATTERNS"
  6806. "[@G-@YNEGATIVE_PATTERNS]@D\n"
  6807. " Run only the tests whose name matches one of the positive patterns "
  6808. "but\n"
  6809. " none of the negative patterns. '?' matches any single character; "
  6810. "'*'\n"
  6811. " matches any substring; ':' separates two patterns.\n"
  6812. " @G--" GTEST_FLAG_PREFIX_
  6813. "also_run_disabled_tests@D\n"
  6814. " Run all disabled tests too.\n"
  6815. "\n"
  6816. "Test Execution:\n"
  6817. " @G--" GTEST_FLAG_PREFIX_
  6818. "repeat=@Y[COUNT]@D\n"
  6819. " Run the tests repeatedly; use a negative count to repeat forever.\n"
  6820. " @G--" GTEST_FLAG_PREFIX_
  6821. "shuffle@D\n"
  6822. " Randomize tests' orders on every iteration.\n"
  6823. " @G--" GTEST_FLAG_PREFIX_
  6824. "random_seed=@Y[NUMBER]@D\n"
  6825. " Random number seed to use for shuffling test orders (between 1 and\n"
  6826. " 99999, or 0 to use a seed based on the current time).\n"
  6827. "\n"
  6828. "Test Output:\n"
  6829. " @G--" GTEST_FLAG_PREFIX_
  6830. "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
  6831. " Enable/disable colored output. The default is @Gauto@D.\n"
  6832. " @G--" GTEST_FLAG_PREFIX_
  6833. "brief=1@D\n"
  6834. " Only print test failures.\n"
  6835. " @G--" GTEST_FLAG_PREFIX_
  6836. "print_time=0@D\n"
  6837. " Don't print the elapsed time of each test.\n"
  6838. " @G--" GTEST_FLAG_PREFIX_
  6839. "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
  6840. "@Y|@G:@YFILE_PATH]@D\n"
  6841. " Generate a JSON or XML report in the given directory or with the "
  6842. "given\n"
  6843. " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
  6844. # if GTEST_CAN_STREAM_RESULTS_
  6845. " @G--" GTEST_FLAG_PREFIX_
  6846. "stream_result_to=@YHOST@G:@YPORT@D\n"
  6847. " Stream test results to the given server.\n"
  6848. # endif // GTEST_CAN_STREAM_RESULTS_
  6849. "\n"
  6850. "Assertion Behavior:\n"
  6851. # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  6852. " @G--" GTEST_FLAG_PREFIX_
  6853. "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
  6854. " Set the default death test style.\n"
  6855. # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  6856. " @G--" GTEST_FLAG_PREFIX_
  6857. "break_on_failure@D\n"
  6858. " Turn assertion failures into debugger break-points.\n"
  6859. " @G--" GTEST_FLAG_PREFIX_
  6860. "throw_on_failure@D\n"
  6861. " Turn assertion failures into C++ exceptions for use by an external\n"
  6862. " test framework.\n"
  6863. " @G--" GTEST_FLAG_PREFIX_
  6864. "catch_exceptions=0@D\n"
  6865. " Do not report exceptions as test failures. Instead, allow them\n"
  6866. " to crash the program or throw a pop-up (on Windows).\n"
  6867. "\n"
  6868. "Except for @G--" GTEST_FLAG_PREFIX_
  6869. "list_tests@D, you can alternatively set "
  6870. "the corresponding\n"
  6871. "environment variable of a flag (all letters in upper-case). For example, "
  6872. "to\n"
  6873. "disable colored text output, you can either specify "
  6874. "@G--" GTEST_FLAG_PREFIX_
  6875. "color=no@D or set\n"
  6876. "the @G" GTEST_FLAG_PREFIX_UPPER_
  6877. "COLOR@D environment variable to @Gno@D.\n"
  6878. "\n"
  6879. "For more information, please read the " GTEST_NAME_
  6880. " documentation at\n"
  6881. "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_
  6882. "\n"
  6883. "(not one in your own code or tests), please report it to\n"
  6884. "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
  6885. static bool ParseGoogleTestFlag(const char* const arg) {
  6886. return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
  6887. &GTEST_FLAG(also_run_disabled_tests)) ||
  6888. ParseBoolFlag(arg, kBreakOnFailureFlag,
  6889. &GTEST_FLAG(break_on_failure)) ||
  6890. ParseBoolFlag(arg, kCatchExceptionsFlag,
  6891. &GTEST_FLAG(catch_exceptions)) ||
  6892. ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
  6893. ParseStringFlag(arg, kDeathTestStyleFlag,
  6894. &GTEST_FLAG(death_test_style)) ||
  6895. ParseBoolFlag(arg, kDeathTestUseFork,
  6896. &GTEST_FLAG(death_test_use_fork)) ||
  6897. ParseBoolFlag(arg, kFailFast, &GTEST_FLAG(fail_fast)) ||
  6898. ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
  6899. ParseStringFlag(arg, kInternalRunDeathTestFlag,
  6900. &GTEST_FLAG(internal_run_death_test)) ||
  6901. ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
  6902. ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
  6903. ParseBoolFlag(arg, kBriefFlag, &GTEST_FLAG(brief)) ||
  6904. ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
  6905. ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
  6906. ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
  6907. ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
  6908. ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
  6909. ParseInt32Flag(arg, kStackTraceDepthFlag,
  6910. &GTEST_FLAG(stack_trace_depth)) ||
  6911. ParseStringFlag(arg, kStreamResultToFlag,
  6912. &GTEST_FLAG(stream_result_to)) ||
  6913. ParseBoolFlag(arg, kThrowOnFailureFlag, &GTEST_FLAG(throw_on_failure));
  6914. }
  6915. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  6916. static void LoadFlagsFromFile(const std::string& path) {
  6917. FILE* flagfile = posix::FOpen(path.c_str(), "r");
  6918. if (!flagfile) {
  6919. GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
  6920. << "\"";
  6921. }
  6922. std::string contents(ReadEntireFile(flagfile));
  6923. posix::FClose(flagfile);
  6924. std::vector<std::string> lines;
  6925. SplitString(contents, '\n', &lines);
  6926. for (size_t i = 0; i < lines.size(); ++i) {
  6927. if (lines[i].empty())
  6928. continue;
  6929. if (!ParseGoogleTestFlag(lines[i].c_str()))
  6930. g_help_flag = true;
  6931. }
  6932. }
  6933. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  6934. // Parses the command line for Google Test flags, without initializing
  6935. // other parts of Google Test. The type parameter CharType can be
  6936. // instantiated to either char or wchar_t.
  6937. template <typename CharType>
  6938. void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
  6939. for (int i = 1; i < *argc; i++) {
  6940. const std::string arg_string = StreamableToString(argv[i]);
  6941. const char* const arg = arg_string.c_str();
  6942. using internal::ParseBoolFlag;
  6943. using internal::ParseInt32Flag;
  6944. using internal::ParseStringFlag;
  6945. bool remove_flag = false;
  6946. if (ParseGoogleTestFlag(arg)) {
  6947. remove_flag = true;
  6948. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  6949. } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
  6950. LoadFlagsFromFile(GTEST_FLAG(flagfile));
  6951. remove_flag = true;
  6952. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  6953. } else if (arg_string == "--help" || arg_string == "-h" ||
  6954. arg_string == "-?" || arg_string == "/?" ||
  6955. HasGoogleTestFlagPrefix(arg)) {
  6956. // Both help flag and unrecognized Google Test flags (excluding
  6957. // internal ones) trigger help display.
  6958. g_help_flag = true;
  6959. }
  6960. if (remove_flag) {
  6961. // Shift the remainder of the argv list left by one. Note
  6962. // that argv has (*argc + 1) elements, the last one always being
  6963. // NULL. The following loop moves the trailing NULL element as
  6964. // well.
  6965. for (int j = i; j != *argc; j++) {
  6966. argv[j] = argv[j + 1];
  6967. }
  6968. // Decrements the argument count.
  6969. (*argc)--;
  6970. // We also need to decrement the iterator as we just removed
  6971. // an element.
  6972. i--;
  6973. }
  6974. }
  6975. if (g_help_flag) {
  6976. // We print the help here instead of in RUN_ALL_TESTS(), as the
  6977. // latter may not be called at all if the user is using Google
  6978. // Test with another testing framework.
  6979. PrintColorEncoded(kColorEncodedHelpMessage);
  6980. }
  6981. }
  6982. // Parses the command line for Google Test flags, without initializing
  6983. // other parts of Google Test.
  6984. void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
  6985. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  6986. // Fix the value of *_NSGetArgc() on macOS, but if and only if
  6987. // *_NSGetArgv() == argv
  6988. // Only applicable to char** version of argv
  6989. #if GTEST_OS_MAC
  6990. #ifndef GTEST_OS_IOS
  6991. if (*_NSGetArgv() == argv) {
  6992. *_NSGetArgc() = *argc;
  6993. }
  6994. #endif
  6995. #endif
  6996. }
  6997. void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
  6998. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  6999. }
  7000. // The internal implementation of InitGoogleTest().
  7001. //
  7002. // The type parameter CharType can be instantiated to either char or
  7003. // wchar_t.
  7004. template <typename CharType>
  7005. void InitGoogleTestImpl(int* argc, CharType** argv) {
  7006. // We don't want to run the initialization code twice.
  7007. if (GTestIsInitialized()) return;
  7008. if (*argc <= 0) return;
  7009. g_argvs.clear();
  7010. for (int i = 0; i != *argc; i++) {
  7011. g_argvs.push_back(StreamableToString(argv[i]));
  7012. }
  7013. #if GTEST_HAS_ABSL
  7014. absl::InitializeSymbolizer(g_argvs[0].c_str());
  7015. #endif // GTEST_HAS_ABSL
  7016. ParseGoogleTestFlagsOnly(argc, argv);
  7017. GetUnitTestImpl()->PostFlagParsingInit();
  7018. }
  7019. } // namespace internal
  7020. // Initializes Google Test. This must be called before calling
  7021. // RUN_ALL_TESTS(). In particular, it parses a command line for the
  7022. // flags that Google Test recognizes. Whenever a Google Test flag is
  7023. // seen, it is removed from argv, and *argc is decremented.
  7024. //
  7025. // No value is returned. Instead, the Google Test flag variables are
  7026. // updated.
  7027. //
  7028. // Calling the function for the second time has no user-visible effect.
  7029. void InitGoogleTest(int* argc, char** argv) {
  7030. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7031. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  7032. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7033. internal::InitGoogleTestImpl(argc, argv);
  7034. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7035. }
  7036. // This overloaded version can be used in Windows programs compiled in
  7037. // UNICODE mode.
  7038. void InitGoogleTest(int* argc, wchar_t** argv) {
  7039. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7040. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  7041. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7042. internal::InitGoogleTestImpl(argc, argv);
  7043. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7044. }
  7045. // This overloaded version can be used on Arduino/embedded platforms where
  7046. // there is no argc/argv.
  7047. void InitGoogleTest() {
  7048. // Since Arduino doesn't have a command line, fake out the argc/argv arguments
  7049. int argc = 1;
  7050. const auto arg0 = "dummy";
  7051. char* argv0 = const_cast<char*>(arg0);
  7052. char** argv = &argv0;
  7053. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7054. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
  7055. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7056. internal::InitGoogleTestImpl(&argc, argv);
  7057. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7058. }
  7059. std::string TempDir() {
  7060. #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
  7061. return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
  7062. #elif GTEST_OS_WINDOWS_MOBILE
  7063. return "\\temp\\";
  7064. #elif GTEST_OS_WINDOWS
  7065. const char* temp_dir = internal::posix::GetEnv("TEMP");
  7066. if (temp_dir == nullptr || temp_dir[0] == '\0') {
  7067. return "\\temp\\";
  7068. } else if (temp_dir[strlen(temp_dir) - 1] == '\\') {
  7069. return temp_dir;
  7070. } else {
  7071. return std::string(temp_dir) + "\\";
  7072. }
  7073. #elif GTEST_OS_LINUX_ANDROID
  7074. const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR");
  7075. if (temp_dir == nullptr || temp_dir[0] == '\0') {
  7076. return "/data/local/tmp/";
  7077. } else {
  7078. return temp_dir;
  7079. }
  7080. #elif GTEST_OS_LINUX
  7081. const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR");
  7082. if (temp_dir == nullptr || temp_dir[0] == '\0') {
  7083. return "/tmp/";
  7084. } else {
  7085. return temp_dir;
  7086. }
  7087. #else
  7088. return "/tmp/";
  7089. #endif // GTEST_OS_WINDOWS_MOBILE
  7090. }
  7091. // Class ScopedTrace
  7092. // Pushes the given source file location and message onto a per-thread
  7093. // trace stack maintained by Google Test.
  7094. void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
  7095. internal::TraceInfo trace;
  7096. trace.file = file;
  7097. trace.line = line;
  7098. trace.message.swap(message);
  7099. UnitTest::GetInstance()->PushGTestTrace(trace);
  7100. }
  7101. // Pops the info pushed by the c'tor.
  7102. ScopedTrace::~ScopedTrace()
  7103. GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
  7104. UnitTest::GetInstance()->PopGTestTrace();
  7105. }
  7106. } // namespace testing
  7107. // Copyright 2005, Google Inc.
  7108. // All rights reserved.
  7109. //
  7110. // Redistribution and use in source and binary forms, with or without
  7111. // modification, are permitted provided that the following conditions are
  7112. // met:
  7113. //
  7114. // * Redistributions of source code must retain the above copyright
  7115. // notice, this list of conditions and the following disclaimer.
  7116. // * Redistributions in binary form must reproduce the above
  7117. // copyright notice, this list of conditions and the following disclaimer
  7118. // in the documentation and/or other materials provided with the
  7119. // distribution.
  7120. // * Neither the name of Google Inc. nor the names of its
  7121. // contributors may be used to endorse or promote products derived from
  7122. // this software without specific prior written permission.
  7123. //
  7124. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7125. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7126. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7127. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7128. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7129. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7130. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7131. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7132. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7133. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7134. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7135. //
  7136. // This file implements death tests.
  7137. #include <functional>
  7138. #include <utility>
  7139. #if GTEST_HAS_DEATH_TEST
  7140. # if GTEST_OS_MAC
  7141. # include <crt_externs.h>
  7142. # endif // GTEST_OS_MAC
  7143. # include <errno.h>
  7144. # include <fcntl.h>
  7145. # include <limits.h>
  7146. # if GTEST_OS_LINUX
  7147. # include <signal.h>
  7148. # endif // GTEST_OS_LINUX
  7149. # include <stdarg.h>
  7150. # if GTEST_OS_WINDOWS
  7151. # include <windows.h>
  7152. # else
  7153. # include <sys/mman.h>
  7154. # include <sys/wait.h>
  7155. # endif // GTEST_OS_WINDOWS
  7156. # if GTEST_OS_QNX
  7157. # include <spawn.h>
  7158. # endif // GTEST_OS_QNX
  7159. # if GTEST_OS_FUCHSIA
  7160. # include <lib/fdio/fd.h>
  7161. # include <lib/fdio/io.h>
  7162. # include <lib/fdio/spawn.h>
  7163. # include <lib/zx/channel.h>
  7164. # include <lib/zx/port.h>
  7165. # include <lib/zx/process.h>
  7166. # include <lib/zx/socket.h>
  7167. # include <zircon/processargs.h>
  7168. # include <zircon/syscalls.h>
  7169. # include <zircon/syscalls/policy.h>
  7170. # include <zircon/syscalls/port.h>
  7171. # endif // GTEST_OS_FUCHSIA
  7172. #endif // GTEST_HAS_DEATH_TEST
  7173. namespace testing {
  7174. // Constants.
  7175. // The default death test style.
  7176. //
  7177. // This is defined in internal/gtest-port.h as "fast", but can be overridden by
  7178. // a definition in internal/custom/gtest-port.h. The recommended value, which is
  7179. // used internally at Google, is "threadsafe".
  7180. static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
  7181. GTEST_DEFINE_string_(
  7182. death_test_style,
  7183. internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
  7184. "Indicates how to run a death test in a forked child process: "
  7185. "\"threadsafe\" (child process re-executes the test binary "
  7186. "from the beginning, running only the specific death test) or "
  7187. "\"fast\" (child process runs the death test immediately "
  7188. "after forking).");
  7189. GTEST_DEFINE_bool_(
  7190. death_test_use_fork,
  7191. internal::BoolFromGTestEnv("death_test_use_fork", false),
  7192. "Instructs to use fork()/_exit() instead of clone() in death tests. "
  7193. "Ignored and always uses fork() on POSIX systems where clone() is not "
  7194. "implemented. Useful when running under valgrind or similar tools if "
  7195. "those do not support clone(). Valgrind 3.3.1 will just fail if "
  7196. "it sees an unsupported combination of clone() flags. "
  7197. "It is not recommended to use this flag w/o valgrind though it will "
  7198. "work in 99% of the cases. Once valgrind is fixed, this flag will "
  7199. "most likely be removed.");
  7200. namespace internal {
  7201. GTEST_DEFINE_string_(
  7202. internal_run_death_test, "",
  7203. "Indicates the file, line number, temporal index of "
  7204. "the single death test to run, and a file descriptor to "
  7205. "which a success code may be sent, all separated by "
  7206. "the '|' characters. This flag is specified if and only if the "
  7207. "current process is a sub-process launched for running a thread-safe "
  7208. "death test. FOR INTERNAL USE ONLY.");
  7209. } // namespace internal
  7210. #if GTEST_HAS_DEATH_TEST
  7211. namespace internal {
  7212. // Valid only for fast death tests. Indicates the code is running in the
  7213. // child process of a fast style death test.
  7214. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  7215. static bool g_in_fast_death_test_child = false;
  7216. # endif
  7217. // Returns a Boolean value indicating whether the caller is currently
  7218. // executing in the context of the death test child process. Tools such as
  7219. // Valgrind heap checkers may need this to modify their behavior in death
  7220. // tests. IMPORTANT: This is an internal utility. Using it may break the
  7221. // implementation of death tests. User code MUST NOT use it.
  7222. bool InDeathTestChild() {
  7223. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  7224. // On Windows and Fuchsia, death tests are thread-safe regardless of the value
  7225. // of the death_test_style flag.
  7226. return !GTEST_FLAG(internal_run_death_test).empty();
  7227. # else
  7228. if (GTEST_FLAG(death_test_style) == "threadsafe")
  7229. return !GTEST_FLAG(internal_run_death_test).empty();
  7230. else
  7231. return g_in_fast_death_test_child;
  7232. #endif
  7233. }
  7234. } // namespace internal
  7235. // ExitedWithCode constructor.
  7236. ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
  7237. }
  7238. // ExitedWithCode function-call operator.
  7239. bool ExitedWithCode::operator()(int exit_status) const {
  7240. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  7241. return exit_status == exit_code_;
  7242. # else
  7243. return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
  7244. # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  7245. }
  7246. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  7247. // KilledBySignal constructor.
  7248. KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
  7249. }
  7250. // KilledBySignal function-call operator.
  7251. bool KilledBySignal::operator()(int exit_status) const {
  7252. # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
  7253. {
  7254. bool result;
  7255. if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
  7256. return result;
  7257. }
  7258. }
  7259. # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
  7260. return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
  7261. }
  7262. # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  7263. namespace internal {
  7264. // Utilities needed for death tests.
  7265. // Generates a textual description of a given exit code, in the format
  7266. // specified by wait(2).
  7267. static std::string ExitSummary(int exit_code) {
  7268. Message m;
  7269. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  7270. m << "Exited with exit status " << exit_code;
  7271. # else
  7272. if (WIFEXITED(exit_code)) {
  7273. m << "Exited with exit status " << WEXITSTATUS(exit_code);
  7274. } else if (WIFSIGNALED(exit_code)) {
  7275. m << "Terminated by signal " << WTERMSIG(exit_code);
  7276. }
  7277. # ifdef WCOREDUMP
  7278. if (WCOREDUMP(exit_code)) {
  7279. m << " (core dumped)";
  7280. }
  7281. # endif
  7282. # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  7283. return m.GetString();
  7284. }
  7285. // Returns true if exit_status describes a process that was terminated
  7286. // by a signal, or exited normally with a nonzero exit code.
  7287. bool ExitedUnsuccessfully(int exit_status) {
  7288. return !ExitedWithCode(0)(exit_status);
  7289. }
  7290. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  7291. // Generates a textual failure message when a death test finds more than
  7292. // one thread running, or cannot determine the number of threads, prior
  7293. // to executing the given statement. It is the responsibility of the
  7294. // caller not to pass a thread_count of 1.
  7295. static std::string DeathTestThreadWarning(size_t thread_count) {
  7296. Message msg;
  7297. msg << "Death tests use fork(), which is unsafe particularly"
  7298. << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
  7299. if (thread_count == 0) {
  7300. msg << "couldn't detect the number of threads.";
  7301. } else {
  7302. msg << "detected " << thread_count << " threads.";
  7303. }
  7304. msg << " See "
  7305. "https://github.com/google/googletest/blob/master/docs/"
  7306. "advanced.md#death-tests-and-threads"
  7307. << " for more explanation and suggested solutions, especially if"
  7308. << " this is the last message you see before your test times out.";
  7309. return msg.GetString();
  7310. }
  7311. # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  7312. // Flag characters for reporting a death test that did not die.
  7313. static const char kDeathTestLived = 'L';
  7314. static const char kDeathTestReturned = 'R';
  7315. static const char kDeathTestThrew = 'T';
  7316. static const char kDeathTestInternalError = 'I';
  7317. #if GTEST_OS_FUCHSIA
  7318. // File descriptor used for the pipe in the child process.
  7319. static const int kFuchsiaReadPipeFd = 3;
  7320. #endif
  7321. // An enumeration describing all of the possible ways that a death test can
  7322. // conclude. DIED means that the process died while executing the test
  7323. // code; LIVED means that process lived beyond the end of the test code;
  7324. // RETURNED means that the test statement attempted to execute a return
  7325. // statement, which is not allowed; THREW means that the test statement
  7326. // returned control by throwing an exception. IN_PROGRESS means the test
  7327. // has not yet concluded.
  7328. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
  7329. // Routine for aborting the program which is safe to call from an
  7330. // exec-style death test child process, in which case the error
  7331. // message is propagated back to the parent process. Otherwise, the
  7332. // message is simply printed to stderr. In either case, the program
  7333. // then exits with status 1.
  7334. static void DeathTestAbort(const std::string& message) {
  7335. // On a POSIX system, this function may be called from a threadsafe-style
  7336. // death test child process, which operates on a very small stack. Use
  7337. // the heap for any additional non-minuscule memory requirements.
  7338. const InternalRunDeathTestFlag* const flag =
  7339. GetUnitTestImpl()->internal_run_death_test_flag();
  7340. if (flag != nullptr) {
  7341. FILE* parent = posix::FDOpen(flag->write_fd(), "w");
  7342. fputc(kDeathTestInternalError, parent);
  7343. fprintf(parent, "%s", message.c_str());
  7344. fflush(parent);
  7345. _exit(1);
  7346. } else {
  7347. fprintf(stderr, "%s", message.c_str());
  7348. fflush(stderr);
  7349. posix::Abort();
  7350. }
  7351. }
  7352. // A replacement for CHECK that calls DeathTestAbort if the assertion
  7353. // fails.
  7354. # define GTEST_DEATH_TEST_CHECK_(expression) \
  7355. do { \
  7356. if (!::testing::internal::IsTrue(expression)) { \
  7357. DeathTestAbort( \
  7358. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  7359. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  7360. + #expression); \
  7361. } \
  7362. } while (::testing::internal::AlwaysFalse())
  7363. // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
  7364. // evaluating any system call that fulfills two conditions: it must return
  7365. // -1 on failure, and set errno to EINTR when it is interrupted and
  7366. // should be tried again. The macro expands to a loop that repeatedly
  7367. // evaluates the expression as long as it evaluates to -1 and sets
  7368. // errno to EINTR. If the expression evaluates to -1 but errno is
  7369. // something other than EINTR, DeathTestAbort is called.
  7370. # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
  7371. do { \
  7372. int gtest_retval; \
  7373. do { \
  7374. gtest_retval = (expression); \
  7375. } while (gtest_retval == -1 && errno == EINTR); \
  7376. if (gtest_retval == -1) { \
  7377. DeathTestAbort( \
  7378. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  7379. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  7380. + #expression + " != -1"); \
  7381. } \
  7382. } while (::testing::internal::AlwaysFalse())
  7383. // Returns the message describing the last system error in errno.
  7384. std::string GetLastErrnoDescription() {
  7385. return errno == 0 ? "" : posix::StrError(errno);
  7386. }
  7387. // This is called from a death test parent process to read a failure
  7388. // message from the death test child process and log it with the FATAL
  7389. // severity. On Windows, the message is read from a pipe handle. On other
  7390. // platforms, it is read from a file descriptor.
  7391. static void FailFromInternalError(int fd) {
  7392. Message error;
  7393. char buffer[256];
  7394. int num_read;
  7395. do {
  7396. while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
  7397. buffer[num_read] = '\0';
  7398. error << buffer;
  7399. }
  7400. } while (num_read == -1 && errno == EINTR);
  7401. if (num_read == 0) {
  7402. GTEST_LOG_(FATAL) << error.GetString();
  7403. } else {
  7404. const int last_error = errno;
  7405. GTEST_LOG_(FATAL) << "Error while reading death test internal: "
  7406. << GetLastErrnoDescription() << " [" << last_error << "]";
  7407. }
  7408. }
  7409. // Death test constructor. Increments the running death test count
  7410. // for the current test.
  7411. DeathTest::DeathTest() {
  7412. TestInfo* const info = GetUnitTestImpl()->current_test_info();
  7413. if (info == nullptr) {
  7414. DeathTestAbort("Cannot run a death test outside of a TEST or "
  7415. "TEST_F construct");
  7416. }
  7417. }
  7418. // Creates and returns a death test by dispatching to the current
  7419. // death test factory.
  7420. bool DeathTest::Create(const char* statement,
  7421. Matcher<const std::string&> matcher, const char* file,
  7422. int line, DeathTest** test) {
  7423. return GetUnitTestImpl()->death_test_factory()->Create(
  7424. statement, std::move(matcher), file, line, test);
  7425. }
  7426. const char* DeathTest::LastMessage() {
  7427. return last_death_test_message_.c_str();
  7428. }
  7429. void DeathTest::set_last_death_test_message(const std::string& message) {
  7430. last_death_test_message_ = message;
  7431. }
  7432. std::string DeathTest::last_death_test_message_;
  7433. // Provides cross platform implementation for some death functionality.
  7434. class DeathTestImpl : public DeathTest {
  7435. protected:
  7436. DeathTestImpl(const char* a_statement, Matcher<const std::string&> matcher)
  7437. : statement_(a_statement),
  7438. matcher_(std::move(matcher)),
  7439. spawned_(false),
  7440. status_(-1),
  7441. outcome_(IN_PROGRESS),
  7442. read_fd_(-1),
  7443. write_fd_(-1) {}
  7444. // read_fd_ is expected to be closed and cleared by a derived class.
  7445. ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
  7446. void Abort(AbortReason reason) override;
  7447. bool Passed(bool status_ok) override;
  7448. const char* statement() const { return statement_; }
  7449. bool spawned() const { return spawned_; }
  7450. void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
  7451. int status() const { return status_; }
  7452. void set_status(int a_status) { status_ = a_status; }
  7453. DeathTestOutcome outcome() const { return outcome_; }
  7454. void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
  7455. int read_fd() const { return read_fd_; }
  7456. void set_read_fd(int fd) { read_fd_ = fd; }
  7457. int write_fd() const { return write_fd_; }
  7458. void set_write_fd(int fd) { write_fd_ = fd; }
  7459. // Called in the parent process only. Reads the result code of the death
  7460. // test child process via a pipe, interprets it to set the outcome_
  7461. // member, and closes read_fd_. Outputs diagnostics and terminates in
  7462. // case of unexpected codes.
  7463. void ReadAndInterpretStatusByte();
  7464. // Returns stderr output from the child process.
  7465. virtual std::string GetErrorLogs();
  7466. private:
  7467. // The textual content of the code this object is testing. This class
  7468. // doesn't own this string and should not attempt to delete it.
  7469. const char* const statement_;
  7470. // A matcher that's expected to match the stderr output by the child process.
  7471. Matcher<const std::string&> matcher_;
  7472. // True if the death test child process has been successfully spawned.
  7473. bool spawned_;
  7474. // The exit status of the child process.
  7475. int status_;
  7476. // How the death test concluded.
  7477. DeathTestOutcome outcome_;
  7478. // Descriptor to the read end of the pipe to the child process. It is
  7479. // always -1 in the child process. The child keeps its write end of the
  7480. // pipe in write_fd_.
  7481. int read_fd_;
  7482. // Descriptor to the child's write end of the pipe to the parent process.
  7483. // It is always -1 in the parent process. The parent keeps its end of the
  7484. // pipe in read_fd_.
  7485. int write_fd_;
  7486. };
  7487. // Called in the parent process only. Reads the result code of the death
  7488. // test child process via a pipe, interprets it to set the outcome_
  7489. // member, and closes read_fd_. Outputs diagnostics and terminates in
  7490. // case of unexpected codes.
  7491. void DeathTestImpl::ReadAndInterpretStatusByte() {
  7492. char flag;
  7493. int bytes_read;
  7494. // The read() here blocks until data is available (signifying the
  7495. // failure of the death test) or until the pipe is closed (signifying
  7496. // its success), so it's okay to call this in the parent before
  7497. // the child process has exited.
  7498. do {
  7499. bytes_read = posix::Read(read_fd(), &flag, 1);
  7500. } while (bytes_read == -1 && errno == EINTR);
  7501. if (bytes_read == 0) {
  7502. set_outcome(DIED);
  7503. } else if (bytes_read == 1) {
  7504. switch (flag) {
  7505. case kDeathTestReturned:
  7506. set_outcome(RETURNED);
  7507. break;
  7508. case kDeathTestThrew:
  7509. set_outcome(THREW);
  7510. break;
  7511. case kDeathTestLived:
  7512. set_outcome(LIVED);
  7513. break;
  7514. case kDeathTestInternalError:
  7515. FailFromInternalError(read_fd()); // Does not return.
  7516. break;
  7517. default:
  7518. GTEST_LOG_(FATAL) << "Death test child process reported "
  7519. << "unexpected status byte ("
  7520. << static_cast<unsigned int>(flag) << ")";
  7521. }
  7522. } else {
  7523. GTEST_LOG_(FATAL) << "Read from death test child process failed: "
  7524. << GetLastErrnoDescription();
  7525. }
  7526. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
  7527. set_read_fd(-1);
  7528. }
  7529. std::string DeathTestImpl::GetErrorLogs() {
  7530. return GetCapturedStderr();
  7531. }
  7532. // Signals that the death test code which should have exited, didn't.
  7533. // Should be called only in a death test child process.
  7534. // Writes a status byte to the child's status file descriptor, then
  7535. // calls _exit(1).
  7536. void DeathTestImpl::Abort(AbortReason reason) {
  7537. // The parent process considers the death test to be a failure if
  7538. // it finds any data in our pipe. So, here we write a single flag byte
  7539. // to the pipe, then exit.
  7540. const char status_ch =
  7541. reason == TEST_DID_NOT_DIE ? kDeathTestLived :
  7542. reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
  7543. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
  7544. // We are leaking the descriptor here because on some platforms (i.e.,
  7545. // when built as Windows DLL), destructors of global objects will still
  7546. // run after calling _exit(). On such systems, write_fd_ will be
  7547. // indirectly closed from the destructor of UnitTestImpl, causing double
  7548. // close if it is also closed here. On debug configurations, double close
  7549. // may assert. As there are no in-process buffers to flush here, we are
  7550. // relying on the OS to close the descriptor after the process terminates
  7551. // when the destructors are not run.
  7552. _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
  7553. }
  7554. // Returns an indented copy of stderr output for a death test.
  7555. // This makes distinguishing death test output lines from regular log lines
  7556. // much easier.
  7557. static ::std::string FormatDeathTestOutput(const ::std::string& output) {
  7558. ::std::string ret;
  7559. for (size_t at = 0; ; ) {
  7560. const size_t line_end = output.find('\n', at);
  7561. ret += "[ DEATH ] ";
  7562. if (line_end == ::std::string::npos) {
  7563. ret += output.substr(at);
  7564. break;
  7565. }
  7566. ret += output.substr(at, line_end + 1 - at);
  7567. at = line_end + 1;
  7568. }
  7569. return ret;
  7570. }
  7571. // Assesses the success or failure of a death test, using both private
  7572. // members which have previously been set, and one argument:
  7573. //
  7574. // Private data members:
  7575. // outcome: An enumeration describing how the death test
  7576. // concluded: DIED, LIVED, THREW, or RETURNED. The death test
  7577. // fails in the latter three cases.
  7578. // status: The exit status of the child process. On *nix, it is in the
  7579. // in the format specified by wait(2). On Windows, this is the
  7580. // value supplied to the ExitProcess() API or a numeric code
  7581. // of the exception that terminated the program.
  7582. // matcher_: A matcher that's expected to match the stderr output by the child
  7583. // process.
  7584. //
  7585. // Argument:
  7586. // status_ok: true if exit_status is acceptable in the context of
  7587. // this particular death test, which fails if it is false
  7588. //
  7589. // Returns true if and only if all of the above conditions are met. Otherwise,
  7590. // the first failing condition, in the order given above, is the one that is
  7591. // reported. Also sets the last death test message string.
  7592. bool DeathTestImpl::Passed(bool status_ok) {
  7593. if (!spawned())
  7594. return false;
  7595. const std::string error_message = GetErrorLogs();
  7596. bool success = false;
  7597. Message buffer;
  7598. buffer << "Death test: " << statement() << "\n";
  7599. switch (outcome()) {
  7600. case LIVED:
  7601. buffer << " Result: failed to die.\n"
  7602. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  7603. break;
  7604. case THREW:
  7605. buffer << " Result: threw an exception.\n"
  7606. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  7607. break;
  7608. case RETURNED:
  7609. buffer << " Result: illegal return in test statement.\n"
  7610. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  7611. break;
  7612. case DIED:
  7613. if (status_ok) {
  7614. if (matcher_.Matches(error_message)) {
  7615. success = true;
  7616. } else {
  7617. std::ostringstream stream;
  7618. matcher_.DescribeTo(&stream);
  7619. buffer << " Result: died but not with expected error.\n"
  7620. << " Expected: " << stream.str() << "\n"
  7621. << "Actual msg:\n"
  7622. << FormatDeathTestOutput(error_message);
  7623. }
  7624. } else {
  7625. buffer << " Result: died but not with expected exit code:\n"
  7626. << " " << ExitSummary(status()) << "\n"
  7627. << "Actual msg:\n" << FormatDeathTestOutput(error_message);
  7628. }
  7629. break;
  7630. case IN_PROGRESS:
  7631. default:
  7632. GTEST_LOG_(FATAL)
  7633. << "DeathTest::Passed somehow called before conclusion of test";
  7634. }
  7635. DeathTest::set_last_death_test_message(buffer.GetString());
  7636. return success;
  7637. }
  7638. # if GTEST_OS_WINDOWS
  7639. // WindowsDeathTest implements death tests on Windows. Due to the
  7640. // specifics of starting new processes on Windows, death tests there are
  7641. // always threadsafe, and Google Test considers the
  7642. // --gtest_death_test_style=fast setting to be equivalent to
  7643. // --gtest_death_test_style=threadsafe there.
  7644. //
  7645. // A few implementation notes: Like the Linux version, the Windows
  7646. // implementation uses pipes for child-to-parent communication. But due to
  7647. // the specifics of pipes on Windows, some extra steps are required:
  7648. //
  7649. // 1. The parent creates a communication pipe and stores handles to both
  7650. // ends of it.
  7651. // 2. The parent starts the child and provides it with the information
  7652. // necessary to acquire the handle to the write end of the pipe.
  7653. // 3. The child acquires the write end of the pipe and signals the parent
  7654. // using a Windows event.
  7655. // 4. Now the parent can release the write end of the pipe on its side. If
  7656. // this is done before step 3, the object's reference count goes down to
  7657. // 0 and it is destroyed, preventing the child from acquiring it. The
  7658. // parent now has to release it, or read operations on the read end of
  7659. // the pipe will not return when the child terminates.
  7660. // 5. The parent reads child's output through the pipe (outcome code and
  7661. // any possible error messages) from the pipe, and its stderr and then
  7662. // determines whether to fail the test.
  7663. //
  7664. // Note: to distinguish Win32 API calls from the local method and function
  7665. // calls, the former are explicitly resolved in the global namespace.
  7666. //
  7667. class WindowsDeathTest : public DeathTestImpl {
  7668. public:
  7669. WindowsDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
  7670. const char* file, int line)
  7671. : DeathTestImpl(a_statement, std::move(matcher)),
  7672. file_(file),
  7673. line_(line) {}
  7674. // All of these virtual functions are inherited from DeathTest.
  7675. virtual int Wait();
  7676. virtual TestRole AssumeRole();
  7677. private:
  7678. // The name of the file in which the death test is located.
  7679. const char* const file_;
  7680. // The line number on which the death test is located.
  7681. const int line_;
  7682. // Handle to the write end of the pipe to the child process.
  7683. AutoHandle write_handle_;
  7684. // Child process handle.
  7685. AutoHandle child_handle_;
  7686. // Event the child process uses to signal the parent that it has
  7687. // acquired the handle to the write end of the pipe. After seeing this
  7688. // event the parent can release its own handles to make sure its
  7689. // ReadFile() calls return when the child terminates.
  7690. AutoHandle event_handle_;
  7691. };
  7692. // Waits for the child in a death test to exit, returning its exit
  7693. // status, or 0 if no child process exists. As a side effect, sets the
  7694. // outcome data member.
  7695. int WindowsDeathTest::Wait() {
  7696. if (!spawned())
  7697. return 0;
  7698. // Wait until the child either signals that it has acquired the write end
  7699. // of the pipe or it dies.
  7700. const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
  7701. switch (::WaitForMultipleObjects(2,
  7702. wait_handles,
  7703. FALSE, // Waits for any of the handles.
  7704. INFINITE)) {
  7705. case WAIT_OBJECT_0:
  7706. case WAIT_OBJECT_0 + 1:
  7707. break;
  7708. default:
  7709. GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
  7710. }
  7711. // The child has acquired the write end of the pipe or exited.
  7712. // We release the handle on our side and continue.
  7713. write_handle_.Reset();
  7714. event_handle_.Reset();
  7715. ReadAndInterpretStatusByte();
  7716. // Waits for the child process to exit if it haven't already. This
  7717. // returns immediately if the child has already exited, regardless of
  7718. // whether previous calls to WaitForMultipleObjects synchronized on this
  7719. // handle or not.
  7720. GTEST_DEATH_TEST_CHECK_(
  7721. WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
  7722. INFINITE));
  7723. DWORD status_code;
  7724. GTEST_DEATH_TEST_CHECK_(
  7725. ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
  7726. child_handle_.Reset();
  7727. set_status(static_cast<int>(status_code));
  7728. return status();
  7729. }
  7730. // The AssumeRole process for a Windows death test. It creates a child
  7731. // process with the same executable as the current process to run the
  7732. // death test. The child process is given the --gtest_filter and
  7733. // --gtest_internal_run_death_test flags such that it knows to run the
  7734. // current death test only.
  7735. DeathTest::TestRole WindowsDeathTest::AssumeRole() {
  7736. const UnitTestImpl* const impl = GetUnitTestImpl();
  7737. const InternalRunDeathTestFlag* const flag =
  7738. impl->internal_run_death_test_flag();
  7739. const TestInfo* const info = impl->current_test_info();
  7740. const int death_test_index = info->result()->death_test_count();
  7741. if (flag != nullptr) {
  7742. // ParseInternalRunDeathTestFlag() has performed all the necessary
  7743. // processing.
  7744. set_write_fd(flag->write_fd());
  7745. return EXECUTE_TEST;
  7746. }
  7747. // WindowsDeathTest uses an anonymous pipe to communicate results of
  7748. // a death test.
  7749. SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
  7750. nullptr, TRUE};
  7751. HANDLE read_handle, write_handle;
  7752. GTEST_DEATH_TEST_CHECK_(
  7753. ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
  7754. 0) // Default buffer size.
  7755. != FALSE);
  7756. set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
  7757. O_RDONLY));
  7758. write_handle_.Reset(write_handle);
  7759. event_handle_.Reset(::CreateEvent(
  7760. &handles_are_inheritable,
  7761. TRUE, // The event will automatically reset to non-signaled state.
  7762. FALSE, // The initial state is non-signalled.
  7763. nullptr)); // The even is unnamed.
  7764. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr);
  7765. const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
  7766. kFilterFlag + "=" + info->test_suite_name() +
  7767. "." + info->name();
  7768. const std::string internal_flag =
  7769. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
  7770. "=" + file_ + "|" + StreamableToString(line_) + "|" +
  7771. StreamableToString(death_test_index) + "|" +
  7772. StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
  7773. // size_t has the same width as pointers on both 32-bit and 64-bit
  7774. // Windows platforms.
  7775. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
  7776. "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
  7777. "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
  7778. char executable_path[_MAX_PATH + 1]; // NOLINT
  7779. GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr,
  7780. executable_path,
  7781. _MAX_PATH));
  7782. std::string command_line =
  7783. std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
  7784. internal_flag + "\"";
  7785. DeathTest::set_last_death_test_message("");
  7786. CaptureStderr();
  7787. // Flush the log buffers since the log streams are shared with the child.
  7788. FlushInfoLog();
  7789. // The child process will share the standard handles with the parent.
  7790. STARTUPINFOA startup_info;
  7791. memset(&startup_info, 0, sizeof(STARTUPINFO));
  7792. startup_info.dwFlags = STARTF_USESTDHANDLES;
  7793. startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
  7794. startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
  7795. startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
  7796. PROCESS_INFORMATION process_info;
  7797. GTEST_DEATH_TEST_CHECK_(
  7798. ::CreateProcessA(
  7799. executable_path, const_cast<char*>(command_line.c_str()),
  7800. nullptr, // Retuned process handle is not inheritable.
  7801. nullptr, // Retuned thread handle is not inheritable.
  7802. TRUE, // Child inherits all inheritable handles (for write_handle_).
  7803. 0x0, // Default creation flags.
  7804. nullptr, // Inherit the parent's environment.
  7805. UnitTest::GetInstance()->original_working_dir(), &startup_info,
  7806. &process_info) != FALSE);
  7807. child_handle_.Reset(process_info.hProcess);
  7808. ::CloseHandle(process_info.hThread);
  7809. set_spawned(true);
  7810. return OVERSEE_TEST;
  7811. }
  7812. # elif GTEST_OS_FUCHSIA
  7813. class FuchsiaDeathTest : public DeathTestImpl {
  7814. public:
  7815. FuchsiaDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
  7816. const char* file, int line)
  7817. : DeathTestImpl(a_statement, std::move(matcher)),
  7818. file_(file),
  7819. line_(line) {}
  7820. // All of these virtual functions are inherited from DeathTest.
  7821. int Wait() override;
  7822. TestRole AssumeRole() override;
  7823. std::string GetErrorLogs() override;
  7824. private:
  7825. // The name of the file in which the death test is located.
  7826. const char* const file_;
  7827. // The line number on which the death test is located.
  7828. const int line_;
  7829. // The stderr data captured by the child process.
  7830. std::string captured_stderr_;
  7831. zx::process child_process_;
  7832. zx::channel exception_channel_;
  7833. zx::socket stderr_socket_;
  7834. };
  7835. // Utility class for accumulating command-line arguments.
  7836. class Arguments {
  7837. public:
  7838. Arguments() { args_.push_back(nullptr); }
  7839. ~Arguments() {
  7840. for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
  7841. ++i) {
  7842. free(*i);
  7843. }
  7844. }
  7845. void AddArgument(const char* argument) {
  7846. args_.insert(args_.end() - 1, posix::StrDup(argument));
  7847. }
  7848. template <typename Str>
  7849. void AddArguments(const ::std::vector<Str>& arguments) {
  7850. for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
  7851. i != arguments.end();
  7852. ++i) {
  7853. args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
  7854. }
  7855. }
  7856. char* const* Argv() {
  7857. return &args_[0];
  7858. }
  7859. int size() {
  7860. return static_cast<int>(args_.size()) - 1;
  7861. }
  7862. private:
  7863. std::vector<char*> args_;
  7864. };
  7865. // Waits for the child in a death test to exit, returning its exit
  7866. // status, or 0 if no child process exists. As a side effect, sets the
  7867. // outcome data member.
  7868. int FuchsiaDeathTest::Wait() {
  7869. const int kProcessKey = 0;
  7870. const int kSocketKey = 1;
  7871. const int kExceptionKey = 2;
  7872. if (!spawned())
  7873. return 0;
  7874. // Create a port to wait for socket/task/exception events.
  7875. zx_status_t status_zx;
  7876. zx::port port;
  7877. status_zx = zx::port::create(0, &port);
  7878. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7879. // Register to wait for the child process to terminate.
  7880. status_zx = child_process_.wait_async(
  7881. port, kProcessKey, ZX_PROCESS_TERMINATED, 0);
  7882. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7883. // Register to wait for the socket to be readable or closed.
  7884. status_zx = stderr_socket_.wait_async(
  7885. port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
  7886. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7887. // Register to wait for an exception.
  7888. status_zx = exception_channel_.wait_async(
  7889. port, kExceptionKey, ZX_CHANNEL_READABLE, 0);
  7890. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7891. bool process_terminated = false;
  7892. bool socket_closed = false;
  7893. do {
  7894. zx_port_packet_t packet = {};
  7895. status_zx = port.wait(zx::time::infinite(), &packet);
  7896. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7897. if (packet.key == kExceptionKey) {
  7898. // Process encountered an exception. Kill it directly rather than
  7899. // letting other handlers process the event. We will get a kProcessKey
  7900. // event when the process actually terminates.
  7901. status_zx = child_process_.kill();
  7902. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7903. } else if (packet.key == kProcessKey) {
  7904. // Process terminated.
  7905. GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
  7906. GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
  7907. process_terminated = true;
  7908. } else if (packet.key == kSocketKey) {
  7909. GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
  7910. if (packet.signal.observed & ZX_SOCKET_READABLE) {
  7911. // Read data from the socket.
  7912. constexpr size_t kBufferSize = 1024;
  7913. do {
  7914. size_t old_length = captured_stderr_.length();
  7915. size_t bytes_read = 0;
  7916. captured_stderr_.resize(old_length + kBufferSize);
  7917. status_zx = stderr_socket_.read(
  7918. 0, &captured_stderr_.front() + old_length, kBufferSize,
  7919. &bytes_read);
  7920. captured_stderr_.resize(old_length + bytes_read);
  7921. } while (status_zx == ZX_OK);
  7922. if (status_zx == ZX_ERR_PEER_CLOSED) {
  7923. socket_closed = true;
  7924. } else {
  7925. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);
  7926. status_zx = stderr_socket_.wait_async(
  7927. port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
  7928. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7929. }
  7930. } else {
  7931. GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);
  7932. socket_closed = true;
  7933. }
  7934. }
  7935. } while (!process_terminated && !socket_closed);
  7936. ReadAndInterpretStatusByte();
  7937. zx_info_process_t buffer;
  7938. status_zx = child_process_.get_info(ZX_INFO_PROCESS, &buffer, sizeof(buffer),
  7939. nullptr, nullptr);
  7940. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7941. GTEST_DEATH_TEST_CHECK_(buffer.flags & ZX_INFO_PROCESS_FLAG_EXITED);
  7942. set_status(static_cast<int>(buffer.return_code));
  7943. return status();
  7944. }
  7945. // The AssumeRole process for a Fuchsia death test. It creates a child
  7946. // process with the same executable as the current process to run the
  7947. // death test. The child process is given the --gtest_filter and
  7948. // --gtest_internal_run_death_test flags such that it knows to run the
  7949. // current death test only.
  7950. DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
  7951. const UnitTestImpl* const impl = GetUnitTestImpl();
  7952. const InternalRunDeathTestFlag* const flag =
  7953. impl->internal_run_death_test_flag();
  7954. const TestInfo* const info = impl->current_test_info();
  7955. const int death_test_index = info->result()->death_test_count();
  7956. if (flag != nullptr) {
  7957. // ParseInternalRunDeathTestFlag() has performed all the necessary
  7958. // processing.
  7959. set_write_fd(kFuchsiaReadPipeFd);
  7960. return EXECUTE_TEST;
  7961. }
  7962. // Flush the log buffers since the log streams are shared with the child.
  7963. FlushInfoLog();
  7964. // Build the child process command line.
  7965. const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
  7966. kFilterFlag + "=" + info->test_suite_name() +
  7967. "." + info->name();
  7968. const std::string internal_flag =
  7969. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
  7970. + file_ + "|"
  7971. + StreamableToString(line_) + "|"
  7972. + StreamableToString(death_test_index);
  7973. Arguments args;
  7974. args.AddArguments(GetInjectableArgvs());
  7975. args.AddArgument(filter_flag.c_str());
  7976. args.AddArgument(internal_flag.c_str());
  7977. // Build the pipe for communication with the child.
  7978. zx_status_t status;
  7979. zx_handle_t child_pipe_handle;
  7980. int child_pipe_fd;
  7981. status = fdio_pipe_half(&child_pipe_fd, &child_pipe_handle);
  7982. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7983. set_read_fd(child_pipe_fd);
  7984. // Set the pipe handle for the child.
  7985. fdio_spawn_action_t spawn_actions[2] = {};
  7986. fdio_spawn_action_t* add_handle_action = &spawn_actions[0];
  7987. add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;
  7988. add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd);
  7989. add_handle_action->h.handle = child_pipe_handle;
  7990. // Create a socket pair will be used to receive the child process' stderr.
  7991. zx::socket stderr_producer_socket;
  7992. status =
  7993. zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
  7994. GTEST_DEATH_TEST_CHECK_(status >= 0);
  7995. int stderr_producer_fd = -1;
  7996. status =
  7997. fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd);
  7998. GTEST_DEATH_TEST_CHECK_(status >= 0);
  7999. // Make the stderr socket nonblocking.
  8000. GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);
  8001. fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];
  8002. add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;
  8003. add_stderr_action->fd.local_fd = stderr_producer_fd;
  8004. add_stderr_action->fd.target_fd = STDERR_FILENO;
  8005. // Create a child job.
  8006. zx_handle_t child_job = ZX_HANDLE_INVALID;
  8007. status = zx_job_create(zx_job_default(), 0, & child_job);
  8008. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  8009. zx_policy_basic_t policy;
  8010. policy.condition = ZX_POL_NEW_ANY;
  8011. policy.policy = ZX_POL_ACTION_ALLOW;
  8012. status = zx_job_set_policy(
  8013. child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);
  8014. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  8015. // Create an exception channel attached to the |child_job|, to allow
  8016. // us to suppress the system default exception handler from firing.
  8017. status =
  8018. zx_task_create_exception_channel(
  8019. child_job, 0, exception_channel_.reset_and_get_address());
  8020. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  8021. // Spawn the child process.
  8022. status = fdio_spawn_etc(
  8023. child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr,
  8024. 2, spawn_actions, child_process_.reset_and_get_address(), nullptr);
  8025. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  8026. set_spawned(true);
  8027. return OVERSEE_TEST;
  8028. }
  8029. std::string FuchsiaDeathTest::GetErrorLogs() {
  8030. return captured_stderr_;
  8031. }
  8032. #else // We are neither on Windows, nor on Fuchsia.
  8033. // ForkingDeathTest provides implementations for most of the abstract
  8034. // methods of the DeathTest interface. Only the AssumeRole method is
  8035. // left undefined.
  8036. class ForkingDeathTest : public DeathTestImpl {
  8037. public:
  8038. ForkingDeathTest(const char* statement, Matcher<const std::string&> matcher);
  8039. // All of these virtual functions are inherited from DeathTest.
  8040. int Wait() override;
  8041. protected:
  8042. void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
  8043. private:
  8044. // PID of child process during death test; 0 in the child process itself.
  8045. pid_t child_pid_;
  8046. };
  8047. // Constructs a ForkingDeathTest.
  8048. ForkingDeathTest::ForkingDeathTest(const char* a_statement,
  8049. Matcher<const std::string&> matcher)
  8050. : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}
  8051. // Waits for the child in a death test to exit, returning its exit
  8052. // status, or 0 if no child process exists. As a side effect, sets the
  8053. // outcome data member.
  8054. int ForkingDeathTest::Wait() {
  8055. if (!spawned())
  8056. return 0;
  8057. ReadAndInterpretStatusByte();
  8058. int status_value;
  8059. GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
  8060. set_status(status_value);
  8061. return status_value;
  8062. }
  8063. // A concrete death test class that forks, then immediately runs the test
  8064. // in the child process.
  8065. class NoExecDeathTest : public ForkingDeathTest {
  8066. public:
  8067. NoExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher)
  8068. : ForkingDeathTest(a_statement, std::move(matcher)) {}
  8069. TestRole AssumeRole() override;
  8070. };
  8071. // The AssumeRole process for a fork-and-run death test. It implements a
  8072. // straightforward fork, with a simple pipe to transmit the status byte.
  8073. DeathTest::TestRole NoExecDeathTest::AssumeRole() {
  8074. const size_t thread_count = GetThreadCount();
  8075. if (thread_count != 1) {
  8076. GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
  8077. }
  8078. int pipe_fd[2];
  8079. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  8080. DeathTest::set_last_death_test_message("");
  8081. CaptureStderr();
  8082. // When we fork the process below, the log file buffers are copied, but the
  8083. // file descriptors are shared. We flush all log files here so that closing
  8084. // the file descriptors in the child process doesn't throw off the
  8085. // synchronization between descriptors and buffers in the parent process.
  8086. // This is as close to the fork as possible to avoid a race condition in case
  8087. // there are multiple threads running before the death test, and another
  8088. // thread writes to the log file.
  8089. FlushInfoLog();
  8090. const pid_t child_pid = fork();
  8091. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  8092. set_child_pid(child_pid);
  8093. if (child_pid == 0) {
  8094. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
  8095. set_write_fd(pipe_fd[1]);
  8096. // Redirects all logging to stderr in the child process to prevent
  8097. // concurrent writes to the log files. We capture stderr in the parent
  8098. // process and append the child process' output to a log.
  8099. LogToStderr();
  8100. // Event forwarding to the listeners of event listener API mush be shut
  8101. // down in death test subprocesses.
  8102. GetUnitTestImpl()->listeners()->SuppressEventForwarding();
  8103. g_in_fast_death_test_child = true;
  8104. return EXECUTE_TEST;
  8105. } else {
  8106. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  8107. set_read_fd(pipe_fd[0]);
  8108. set_spawned(true);
  8109. return OVERSEE_TEST;
  8110. }
  8111. }
  8112. // A concrete death test class that forks and re-executes the main
  8113. // program from the beginning, with command-line flags set that cause
  8114. // only this specific death test to be run.
  8115. class ExecDeathTest : public ForkingDeathTest {
  8116. public:
  8117. ExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
  8118. const char* file, int line)
  8119. : ForkingDeathTest(a_statement, std::move(matcher)),
  8120. file_(file),
  8121. line_(line) {}
  8122. TestRole AssumeRole() override;
  8123. private:
  8124. static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
  8125. ::std::vector<std::string> args = GetInjectableArgvs();
  8126. # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
  8127. ::std::vector<std::string> extra_args =
  8128. GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
  8129. args.insert(args.end(), extra_args.begin(), extra_args.end());
  8130. # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
  8131. return args;
  8132. }
  8133. // The name of the file in which the death test is located.
  8134. const char* const file_;
  8135. // The line number on which the death test is located.
  8136. const int line_;
  8137. };
  8138. // Utility class for accumulating command-line arguments.
  8139. class Arguments {
  8140. public:
  8141. Arguments() { args_.push_back(nullptr); }
  8142. ~Arguments() {
  8143. for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
  8144. ++i) {
  8145. free(*i);
  8146. }
  8147. }
  8148. void AddArgument(const char* argument) {
  8149. args_.insert(args_.end() - 1, posix::StrDup(argument));
  8150. }
  8151. template <typename Str>
  8152. void AddArguments(const ::std::vector<Str>& arguments) {
  8153. for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
  8154. i != arguments.end();
  8155. ++i) {
  8156. args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
  8157. }
  8158. }
  8159. char* const* Argv() {
  8160. return &args_[0];
  8161. }
  8162. private:
  8163. std::vector<char*> args_;
  8164. };
  8165. // A struct that encompasses the arguments to the child process of a
  8166. // threadsafe-style death test process.
  8167. struct ExecDeathTestArgs {
  8168. char* const* argv; // Command-line arguments for the child's call to exec
  8169. int close_fd; // File descriptor to close; the read end of a pipe
  8170. };
  8171. # if GTEST_OS_QNX
  8172. extern "C" char** environ;
  8173. # else // GTEST_OS_QNX
  8174. // The main function for a threadsafe-style death test child process.
  8175. // This function is called in a clone()-ed process and thus must avoid
  8176. // any potentially unsafe operations like malloc or libc functions.
  8177. static int ExecDeathTestChildMain(void* child_arg) {
  8178. ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
  8179. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
  8180. // We need to execute the test program in the same environment where
  8181. // it was originally invoked. Therefore we change to the original
  8182. // working directory first.
  8183. const char* const original_dir =
  8184. UnitTest::GetInstance()->original_working_dir();
  8185. // We can safely call chdir() as it's a direct system call.
  8186. if (chdir(original_dir) != 0) {
  8187. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  8188. GetLastErrnoDescription());
  8189. return EXIT_FAILURE;
  8190. }
  8191. // We can safely call execv() as it's almost a direct system call. We
  8192. // cannot use execvp() as it's a libc function and thus potentially
  8193. // unsafe. Since execv() doesn't search the PATH, the user must
  8194. // invoke the test program via a valid path that contains at least
  8195. // one path separator.
  8196. execv(args->argv[0], args->argv);
  8197. DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " +
  8198. original_dir + " failed: " +
  8199. GetLastErrnoDescription());
  8200. return EXIT_FAILURE;
  8201. }
  8202. # endif // GTEST_OS_QNX
  8203. # if GTEST_HAS_CLONE
  8204. // Two utility routines that together determine the direction the stack
  8205. // grows.
  8206. // This could be accomplished more elegantly by a single recursive
  8207. // function, but we want to guard against the unlikely possibility of
  8208. // a smart compiler optimizing the recursion away.
  8209. //
  8210. // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
  8211. // StackLowerThanAddress into StackGrowsDown, which then doesn't give
  8212. // correct answer.
  8213. static void StackLowerThanAddress(const void* ptr,
  8214. bool* result) GTEST_NO_INLINE_;
  8215. // Make sure sanitizers do not tamper with the stack here.
  8216. // Ideally, we want to use `__builtin_frame_address` instead of a local variable
  8217. // address with sanitizer disabled, but it does not work when the
  8218. // compiler optimizes the stack frame out, which happens on PowerPC targets.
  8219. // HWAddressSanitizer add a random tag to the MSB of the local variable address,
  8220. // making comparison result unpredictable.
  8221. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  8222. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  8223. static void StackLowerThanAddress(const void* ptr, bool* result) {
  8224. int dummy = 0;
  8225. *result = std::less<const void*>()(&dummy, ptr);
  8226. }
  8227. // Make sure AddressSanitizer does not tamper with the stack here.
  8228. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  8229. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  8230. static bool StackGrowsDown() {
  8231. int dummy = 0;
  8232. bool result;
  8233. StackLowerThanAddress(&dummy, &result);
  8234. return result;
  8235. }
  8236. # endif // GTEST_HAS_CLONE
  8237. // Spawns a child process with the same executable as the current process in
  8238. // a thread-safe manner and instructs it to run the death test. The
  8239. // implementation uses fork(2) + exec. On systems where clone(2) is
  8240. // available, it is used instead, being slightly more thread-safe. On QNX,
  8241. // fork supports only single-threaded environments, so this function uses
  8242. // spawn(2) there instead. The function dies with an error message if
  8243. // anything goes wrong.
  8244. static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
  8245. ExecDeathTestArgs args = { argv, close_fd };
  8246. pid_t child_pid = -1;
  8247. # if GTEST_OS_QNX
  8248. // Obtains the current directory and sets it to be closed in the child
  8249. // process.
  8250. const int cwd_fd = open(".", O_RDONLY);
  8251. GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
  8252. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
  8253. // We need to execute the test program in the same environment where
  8254. // it was originally invoked. Therefore we change to the original
  8255. // working directory first.
  8256. const char* const original_dir =
  8257. UnitTest::GetInstance()->original_working_dir();
  8258. // We can safely call chdir() as it's a direct system call.
  8259. if (chdir(original_dir) != 0) {
  8260. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  8261. GetLastErrnoDescription());
  8262. return EXIT_FAILURE;
  8263. }
  8264. int fd_flags;
  8265. // Set close_fd to be closed after spawn.
  8266. GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
  8267. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
  8268. fd_flags | FD_CLOEXEC));
  8269. struct inheritance inherit = {0};
  8270. // spawn is a system call.
  8271. child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ);
  8272. // Restores the current working directory.
  8273. GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
  8274. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
  8275. # else // GTEST_OS_QNX
  8276. # if GTEST_OS_LINUX
  8277. // When a SIGPROF signal is received while fork() or clone() are executing,
  8278. // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
  8279. // it after the call to fork()/clone() is complete.
  8280. struct sigaction saved_sigprof_action;
  8281. struct sigaction ignore_sigprof_action;
  8282. memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
  8283. sigemptyset(&ignore_sigprof_action.sa_mask);
  8284. ignore_sigprof_action.sa_handler = SIG_IGN;
  8285. GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
  8286. SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
  8287. # endif // GTEST_OS_LINUX
  8288. # if GTEST_HAS_CLONE
  8289. const bool use_fork = GTEST_FLAG(death_test_use_fork);
  8290. if (!use_fork) {
  8291. static const bool stack_grows_down = StackGrowsDown();
  8292. const auto stack_size = static_cast<size_t>(getpagesize() * 2);
  8293. // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
  8294. void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE,
  8295. MAP_ANON | MAP_PRIVATE, -1, 0);
  8296. GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
  8297. // Maximum stack alignment in bytes: For a downward-growing stack, this
  8298. // amount is subtracted from size of the stack space to get an address
  8299. // that is within the stack space and is aligned on all systems we care
  8300. // about. As far as I know there is no ABI with stack alignment greater
  8301. // than 64. We assume stack and stack_size already have alignment of
  8302. // kMaxStackAlignment.
  8303. const size_t kMaxStackAlignment = 64;
  8304. void* const stack_top =
  8305. static_cast<char*>(stack) +
  8306. (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
  8307. GTEST_DEATH_TEST_CHECK_(
  8308. static_cast<size_t>(stack_size) > kMaxStackAlignment &&
  8309. reinterpret_cast<uintptr_t>(stack_top) % kMaxStackAlignment == 0);
  8310. child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
  8311. GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
  8312. }
  8313. # else
  8314. const bool use_fork = true;
  8315. # endif // GTEST_HAS_CLONE
  8316. if (use_fork && (child_pid = fork()) == 0) {
  8317. ExecDeathTestChildMain(&args);
  8318. _exit(0);
  8319. }
  8320. # endif // GTEST_OS_QNX
  8321. # if GTEST_OS_LINUX
  8322. GTEST_DEATH_TEST_CHECK_SYSCALL_(
  8323. sigaction(SIGPROF, &saved_sigprof_action, nullptr));
  8324. # endif // GTEST_OS_LINUX
  8325. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  8326. return child_pid;
  8327. }
  8328. // The AssumeRole process for a fork-and-exec death test. It re-executes the
  8329. // main program from the beginning, setting the --gtest_filter
  8330. // and --gtest_internal_run_death_test flags to cause only the current
  8331. // death test to be re-run.
  8332. DeathTest::TestRole ExecDeathTest::AssumeRole() {
  8333. const UnitTestImpl* const impl = GetUnitTestImpl();
  8334. const InternalRunDeathTestFlag* const flag =
  8335. impl->internal_run_death_test_flag();
  8336. const TestInfo* const info = impl->current_test_info();
  8337. const int death_test_index = info->result()->death_test_count();
  8338. if (flag != nullptr) {
  8339. set_write_fd(flag->write_fd());
  8340. return EXECUTE_TEST;
  8341. }
  8342. int pipe_fd[2];
  8343. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  8344. // Clear the close-on-exec flag on the write end of the pipe, lest
  8345. // it be closed when the child process does an exec:
  8346. GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
  8347. const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
  8348. kFilterFlag + "=" + info->test_suite_name() +
  8349. "." + info->name();
  8350. const std::string internal_flag =
  8351. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
  8352. + file_ + "|" + StreamableToString(line_) + "|"
  8353. + StreamableToString(death_test_index) + "|"
  8354. + StreamableToString(pipe_fd[1]);
  8355. Arguments args;
  8356. args.AddArguments(GetArgvsForDeathTestChildProcess());
  8357. args.AddArgument(filter_flag.c_str());
  8358. args.AddArgument(internal_flag.c_str());
  8359. DeathTest::set_last_death_test_message("");
  8360. CaptureStderr();
  8361. // See the comment in NoExecDeathTest::AssumeRole for why the next line
  8362. // is necessary.
  8363. FlushInfoLog();
  8364. const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
  8365. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  8366. set_child_pid(child_pid);
  8367. set_read_fd(pipe_fd[0]);
  8368. set_spawned(true);
  8369. return OVERSEE_TEST;
  8370. }
  8371. # endif // !GTEST_OS_WINDOWS
  8372. // Creates a concrete DeathTest-derived class that depends on the
  8373. // --gtest_death_test_style flag, and sets the pointer pointed to
  8374. // by the "test" argument to its address. If the test should be
  8375. // skipped, sets that pointer to NULL. Returns true, unless the
  8376. // flag is set to an invalid value.
  8377. bool DefaultDeathTestFactory::Create(const char* statement,
  8378. Matcher<const std::string&> matcher,
  8379. const char* file, int line,
  8380. DeathTest** test) {
  8381. UnitTestImpl* const impl = GetUnitTestImpl();
  8382. const InternalRunDeathTestFlag* const flag =
  8383. impl->internal_run_death_test_flag();
  8384. const int death_test_index = impl->current_test_info()
  8385. ->increment_death_test_count();
  8386. if (flag != nullptr) {
  8387. if (death_test_index > flag->index()) {
  8388. DeathTest::set_last_death_test_message(
  8389. "Death test count (" + StreamableToString(death_test_index)
  8390. + ") somehow exceeded expected maximum ("
  8391. + StreamableToString(flag->index()) + ")");
  8392. return false;
  8393. }
  8394. if (!(flag->file() == file && flag->line() == line &&
  8395. flag->index() == death_test_index)) {
  8396. *test = nullptr;
  8397. return true;
  8398. }
  8399. }
  8400. # if GTEST_OS_WINDOWS
  8401. if (GTEST_FLAG(death_test_style) == "threadsafe" ||
  8402. GTEST_FLAG(death_test_style) == "fast") {
  8403. *test = new WindowsDeathTest(statement, std::move(matcher), file, line);
  8404. }
  8405. # elif GTEST_OS_FUCHSIA
  8406. if (GTEST_FLAG(death_test_style) == "threadsafe" ||
  8407. GTEST_FLAG(death_test_style) == "fast") {
  8408. *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);
  8409. }
  8410. # else
  8411. if (GTEST_FLAG(death_test_style) == "threadsafe") {
  8412. *test = new ExecDeathTest(statement, std::move(matcher), file, line);
  8413. } else if (GTEST_FLAG(death_test_style) == "fast") {
  8414. *test = new NoExecDeathTest(statement, std::move(matcher));
  8415. }
  8416. # endif // GTEST_OS_WINDOWS
  8417. else { // NOLINT - this is more readable than unbalanced brackets inside #if.
  8418. DeathTest::set_last_death_test_message(
  8419. "Unknown death test style \"" + GTEST_FLAG(death_test_style)
  8420. + "\" encountered");
  8421. return false;
  8422. }
  8423. return true;
  8424. }
  8425. # if GTEST_OS_WINDOWS
  8426. // Recreates the pipe and event handles from the provided parameters,
  8427. // signals the event, and returns a file descriptor wrapped around the pipe
  8428. // handle. This function is called in the child process only.
  8429. static int GetStatusFileDescriptor(unsigned int parent_process_id,
  8430. size_t write_handle_as_size_t,
  8431. size_t event_handle_as_size_t) {
  8432. AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
  8433. FALSE, // Non-inheritable.
  8434. parent_process_id));
  8435. if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
  8436. DeathTestAbort("Unable to open parent process " +
  8437. StreamableToString(parent_process_id));
  8438. }
  8439. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
  8440. const HANDLE write_handle =
  8441. reinterpret_cast<HANDLE>(write_handle_as_size_t);
  8442. HANDLE dup_write_handle;
  8443. // The newly initialized handle is accessible only in the parent
  8444. // process. To obtain one accessible within the child, we need to use
  8445. // DuplicateHandle.
  8446. if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
  8447. ::GetCurrentProcess(), &dup_write_handle,
  8448. 0x0, // Requested privileges ignored since
  8449. // DUPLICATE_SAME_ACCESS is used.
  8450. FALSE, // Request non-inheritable handler.
  8451. DUPLICATE_SAME_ACCESS)) {
  8452. DeathTestAbort("Unable to duplicate the pipe handle " +
  8453. StreamableToString(write_handle_as_size_t) +
  8454. " from the parent process " +
  8455. StreamableToString(parent_process_id));
  8456. }
  8457. const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
  8458. HANDLE dup_event_handle;
  8459. if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
  8460. ::GetCurrentProcess(), &dup_event_handle,
  8461. 0x0,
  8462. FALSE,
  8463. DUPLICATE_SAME_ACCESS)) {
  8464. DeathTestAbort("Unable to duplicate the event handle " +
  8465. StreamableToString(event_handle_as_size_t) +
  8466. " from the parent process " +
  8467. StreamableToString(parent_process_id));
  8468. }
  8469. const int write_fd =
  8470. ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
  8471. if (write_fd == -1) {
  8472. DeathTestAbort("Unable to convert pipe handle " +
  8473. StreamableToString(write_handle_as_size_t) +
  8474. " to a file descriptor");
  8475. }
  8476. // Signals the parent that the write end of the pipe has been acquired
  8477. // so the parent can release its own write end.
  8478. ::SetEvent(dup_event_handle);
  8479. return write_fd;
  8480. }
  8481. # endif // GTEST_OS_WINDOWS
  8482. // Returns a newly created InternalRunDeathTestFlag object with fields
  8483. // initialized from the GTEST_FLAG(internal_run_death_test) flag if
  8484. // the flag is specified; otherwise returns NULL.
  8485. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
  8486. if (GTEST_FLAG(internal_run_death_test) == "") return nullptr;
  8487. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
  8488. // can use it here.
  8489. int line = -1;
  8490. int index = -1;
  8491. ::std::vector< ::std::string> fields;
  8492. SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
  8493. int write_fd = -1;
  8494. # if GTEST_OS_WINDOWS
  8495. unsigned int parent_process_id = 0;
  8496. size_t write_handle_as_size_t = 0;
  8497. size_t event_handle_as_size_t = 0;
  8498. if (fields.size() != 6
  8499. || !ParseNaturalNumber(fields[1], &line)
  8500. || !ParseNaturalNumber(fields[2], &index)
  8501. || !ParseNaturalNumber(fields[3], &parent_process_id)
  8502. || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
  8503. || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
  8504. DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
  8505. GTEST_FLAG(internal_run_death_test));
  8506. }
  8507. write_fd = GetStatusFileDescriptor(parent_process_id,
  8508. write_handle_as_size_t,
  8509. event_handle_as_size_t);
  8510. # elif GTEST_OS_FUCHSIA
  8511. if (fields.size() != 3
  8512. || !ParseNaturalNumber(fields[1], &line)
  8513. || !ParseNaturalNumber(fields[2], &index)) {
  8514. DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
  8515. + GTEST_FLAG(internal_run_death_test));
  8516. }
  8517. # else
  8518. if (fields.size() != 4
  8519. || !ParseNaturalNumber(fields[1], &line)
  8520. || !ParseNaturalNumber(fields[2], &index)
  8521. || !ParseNaturalNumber(fields[3], &write_fd)) {
  8522. DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
  8523. + GTEST_FLAG(internal_run_death_test));
  8524. }
  8525. # endif // GTEST_OS_WINDOWS
  8526. return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
  8527. }
  8528. } // namespace internal
  8529. #endif // GTEST_HAS_DEATH_TEST
  8530. } // namespace testing
  8531. // Copyright 2008, Google Inc.
  8532. // All rights reserved.
  8533. //
  8534. // Redistribution and use in source and binary forms, with or without
  8535. // modification, are permitted provided that the following conditions are
  8536. // met:
  8537. //
  8538. // * Redistributions of source code must retain the above copyright
  8539. // notice, this list of conditions and the following disclaimer.
  8540. // * Redistributions in binary form must reproduce the above
  8541. // copyright notice, this list of conditions and the following disclaimer
  8542. // in the documentation and/or other materials provided with the
  8543. // distribution.
  8544. // * Neither the name of Google Inc. nor the names of its
  8545. // contributors may be used to endorse or promote products derived from
  8546. // this software without specific prior written permission.
  8547. //
  8548. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8549. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8550. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8551. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8552. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8553. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8554. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8555. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8556. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8557. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8558. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8559. #include <stdlib.h>
  8560. #if GTEST_OS_WINDOWS_MOBILE
  8561. # include <windows.h>
  8562. #elif GTEST_OS_WINDOWS
  8563. # include <direct.h>
  8564. # include <io.h>
  8565. #else
  8566. # include <limits.h>
  8567. # include <climits> // Some Linux distributions define PATH_MAX here.
  8568. #endif // GTEST_OS_WINDOWS_MOBILE
  8569. #if GTEST_OS_WINDOWS
  8570. # define GTEST_PATH_MAX_ _MAX_PATH
  8571. #elif defined(PATH_MAX)
  8572. # define GTEST_PATH_MAX_ PATH_MAX
  8573. #elif defined(_XOPEN_PATH_MAX)
  8574. # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
  8575. #else
  8576. # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
  8577. #endif // GTEST_OS_WINDOWS
  8578. namespace testing {
  8579. namespace internal {
  8580. #if GTEST_OS_WINDOWS
  8581. // On Windows, '\\' is the standard path separator, but many tools and the
  8582. // Windows API also accept '/' as an alternate path separator. Unless otherwise
  8583. // noted, a file path can contain either kind of path separators, or a mixture
  8584. // of them.
  8585. const char kPathSeparator = '\\';
  8586. const char kAlternatePathSeparator = '/';
  8587. const char kAlternatePathSeparatorString[] = "/";
  8588. # if GTEST_OS_WINDOWS_MOBILE
  8589. // Windows CE doesn't have a current directory. You should not use
  8590. // the current directory in tests on Windows CE, but this at least
  8591. // provides a reasonable fallback.
  8592. const char kCurrentDirectoryString[] = "\\";
  8593. // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
  8594. const DWORD kInvalidFileAttributes = 0xffffffff;
  8595. # else
  8596. const char kCurrentDirectoryString[] = ".\\";
  8597. # endif // GTEST_OS_WINDOWS_MOBILE
  8598. #else
  8599. const char kPathSeparator = '/';
  8600. const char kCurrentDirectoryString[] = "./";
  8601. #endif // GTEST_OS_WINDOWS
  8602. // Returns whether the given character is a valid path separator.
  8603. static bool IsPathSeparator(char c) {
  8604. #if GTEST_HAS_ALT_PATH_SEP_
  8605. return (c == kPathSeparator) || (c == kAlternatePathSeparator);
  8606. #else
  8607. return c == kPathSeparator;
  8608. #endif
  8609. }
  8610. // Returns the current working directory, or "" if unsuccessful.
  8611. FilePath FilePath::GetCurrentDir() {
  8612. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
  8613. GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \
  8614. GTEST_OS_XTENSA
  8615. // These platforms do not have a current directory, so we just return
  8616. // something reasonable.
  8617. return FilePath(kCurrentDirectoryString);
  8618. #elif GTEST_OS_WINDOWS
  8619. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  8620. return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
  8621. #else
  8622. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  8623. char* result = getcwd(cwd, sizeof(cwd));
  8624. # if GTEST_OS_NACL
  8625. // getcwd will likely fail in NaCl due to the sandbox, so return something
  8626. // reasonable. The user may have provided a shim implementation for getcwd,
  8627. // however, so fallback only when failure is detected.
  8628. return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
  8629. # endif // GTEST_OS_NACL
  8630. return FilePath(result == nullptr ? "" : cwd);
  8631. #endif // GTEST_OS_WINDOWS_MOBILE
  8632. }
  8633. // Returns a copy of the FilePath with the case-insensitive extension removed.
  8634. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
  8635. // FilePath("dir/file"). If a case-insensitive extension is not
  8636. // found, returns a copy of the original FilePath.
  8637. FilePath FilePath::RemoveExtension(const char* extension) const {
  8638. const std::string dot_extension = std::string(".") + extension;
  8639. if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
  8640. return FilePath(pathname_.substr(
  8641. 0, pathname_.length() - dot_extension.length()));
  8642. }
  8643. return *this;
  8644. }
  8645. // Returns a pointer to the last occurrence of a valid path separator in
  8646. // the FilePath. On Windows, for example, both '/' and '\' are valid path
  8647. // separators. Returns NULL if no path separator was found.
  8648. const char* FilePath::FindLastPathSeparator() const {
  8649. const char* const last_sep = strrchr(c_str(), kPathSeparator);
  8650. #if GTEST_HAS_ALT_PATH_SEP_
  8651. const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
  8652. // Comparing two pointers of which only one is NULL is undefined.
  8653. if (last_alt_sep != nullptr &&
  8654. (last_sep == nullptr || last_alt_sep > last_sep)) {
  8655. return last_alt_sep;
  8656. }
  8657. #endif
  8658. return last_sep;
  8659. }
  8660. // Returns a copy of the FilePath with the directory part removed.
  8661. // Example: FilePath("path/to/file").RemoveDirectoryName() returns
  8662. // FilePath("file"). If there is no directory part ("just_a_file"), it returns
  8663. // the FilePath unmodified. If there is no file part ("just_a_dir/") it
  8664. // returns an empty FilePath ("").
  8665. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  8666. FilePath FilePath::RemoveDirectoryName() const {
  8667. const char* const last_sep = FindLastPathSeparator();
  8668. return last_sep ? FilePath(last_sep + 1) : *this;
  8669. }
  8670. // RemoveFileName returns the directory path with the filename removed.
  8671. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
  8672. // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
  8673. // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
  8674. // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
  8675. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  8676. FilePath FilePath::RemoveFileName() const {
  8677. const char* const last_sep = FindLastPathSeparator();
  8678. std::string dir;
  8679. if (last_sep) {
  8680. dir = std::string(c_str(), static_cast<size_t>(last_sep + 1 - c_str()));
  8681. } else {
  8682. dir = kCurrentDirectoryString;
  8683. }
  8684. return FilePath(dir);
  8685. }
  8686. // Helper functions for naming files in a directory for xml output.
  8687. // Given directory = "dir", base_name = "test", number = 0,
  8688. // extension = "xml", returns "dir/test.xml". If number is greater
  8689. // than zero (e.g., 12), returns "dir/test_12.xml".
  8690. // On Windows platform, uses \ as the separator rather than /.
  8691. FilePath FilePath::MakeFileName(const FilePath& directory,
  8692. const FilePath& base_name,
  8693. int number,
  8694. const char* extension) {
  8695. std::string file;
  8696. if (number == 0) {
  8697. file = base_name.string() + "." + extension;
  8698. } else {
  8699. file = base_name.string() + "_" + StreamableToString(number)
  8700. + "." + extension;
  8701. }
  8702. return ConcatPaths(directory, FilePath(file));
  8703. }
  8704. // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
  8705. // On Windows, uses \ as the separator rather than /.
  8706. FilePath FilePath::ConcatPaths(const FilePath& directory,
  8707. const FilePath& relative_path) {
  8708. if (directory.IsEmpty())
  8709. return relative_path;
  8710. const FilePath dir(directory.RemoveTrailingPathSeparator());
  8711. return FilePath(dir.string() + kPathSeparator + relative_path.string());
  8712. }
  8713. // Returns true if pathname describes something findable in the file-system,
  8714. // either a file, directory, or whatever.
  8715. bool FilePath::FileOrDirectoryExists() const {
  8716. #if GTEST_OS_WINDOWS_MOBILE
  8717. LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
  8718. const DWORD attributes = GetFileAttributes(unicode);
  8719. delete [] unicode;
  8720. return attributes != kInvalidFileAttributes;
  8721. #else
  8722. posix::StatStruct file_stat{};
  8723. return posix::Stat(pathname_.c_str(), &file_stat) == 0;
  8724. #endif // GTEST_OS_WINDOWS_MOBILE
  8725. }
  8726. // Returns true if pathname describes a directory in the file-system
  8727. // that exists.
  8728. bool FilePath::DirectoryExists() const {
  8729. bool result = false;
  8730. #if GTEST_OS_WINDOWS
  8731. // Don't strip off trailing separator if path is a root directory on
  8732. // Windows (like "C:\\").
  8733. const FilePath& path(IsRootDirectory() ? *this :
  8734. RemoveTrailingPathSeparator());
  8735. #else
  8736. const FilePath& path(*this);
  8737. #endif
  8738. #if GTEST_OS_WINDOWS_MOBILE
  8739. LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
  8740. const DWORD attributes = GetFileAttributes(unicode);
  8741. delete [] unicode;
  8742. if ((attributes != kInvalidFileAttributes) &&
  8743. (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  8744. result = true;
  8745. }
  8746. #else
  8747. posix::StatStruct file_stat{};
  8748. result = posix::Stat(path.c_str(), &file_stat) == 0 &&
  8749. posix::IsDir(file_stat);
  8750. #endif // GTEST_OS_WINDOWS_MOBILE
  8751. return result;
  8752. }
  8753. // Returns true if pathname describes a root directory. (Windows has one
  8754. // root directory per disk drive.)
  8755. bool FilePath::IsRootDirectory() const {
  8756. #if GTEST_OS_WINDOWS
  8757. return pathname_.length() == 3 && IsAbsolutePath();
  8758. #else
  8759. return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
  8760. #endif
  8761. }
  8762. // Returns true if pathname describes an absolute path.
  8763. bool FilePath::IsAbsolutePath() const {
  8764. const char* const name = pathname_.c_str();
  8765. #if GTEST_OS_WINDOWS
  8766. return pathname_.length() >= 3 &&
  8767. ((name[0] >= 'a' && name[0] <= 'z') ||
  8768. (name[0] >= 'A' && name[0] <= 'Z')) &&
  8769. name[1] == ':' &&
  8770. IsPathSeparator(name[2]);
  8771. #else
  8772. return IsPathSeparator(name[0]);
  8773. #endif
  8774. }
  8775. // Returns a pathname for a file that does not currently exist. The pathname
  8776. // will be directory/base_name.extension or
  8777. // directory/base_name_<number>.extension if directory/base_name.extension
  8778. // already exists. The number will be incremented until a pathname is found
  8779. // that does not already exist.
  8780. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
  8781. // There could be a race condition if two or more processes are calling this
  8782. // function at the same time -- they could both pick the same filename.
  8783. FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
  8784. const FilePath& base_name,
  8785. const char* extension) {
  8786. FilePath full_pathname;
  8787. int number = 0;
  8788. do {
  8789. full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
  8790. } while (full_pathname.FileOrDirectoryExists());
  8791. return full_pathname;
  8792. }
  8793. // Returns true if FilePath ends with a path separator, which indicates that
  8794. // it is intended to represent a directory. Returns false otherwise.
  8795. // This does NOT check that a directory (or file) actually exists.
  8796. bool FilePath::IsDirectory() const {
  8797. return !pathname_.empty() &&
  8798. IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
  8799. }
  8800. // Create directories so that path exists. Returns true if successful or if
  8801. // the directories already exist; returns false if unable to create directories
  8802. // for any reason.
  8803. bool FilePath::CreateDirectoriesRecursively() const {
  8804. if (!this->IsDirectory()) {
  8805. return false;
  8806. }
  8807. if (pathname_.length() == 0 || this->DirectoryExists()) {
  8808. return true;
  8809. }
  8810. const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
  8811. return parent.CreateDirectoriesRecursively() && this->CreateFolder();
  8812. }
  8813. // Create the directory so that path exists. Returns true if successful or
  8814. // if the directory already exists; returns false if unable to create the
  8815. // directory for any reason, including if the parent directory does not
  8816. // exist. Not named "CreateDirectory" because that's a macro on Windows.
  8817. bool FilePath::CreateFolder() const {
  8818. #if GTEST_OS_WINDOWS_MOBILE
  8819. FilePath removed_sep(this->RemoveTrailingPathSeparator());
  8820. LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
  8821. int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
  8822. delete [] unicode;
  8823. #elif GTEST_OS_WINDOWS
  8824. int result = _mkdir(pathname_.c_str());
  8825. #elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA
  8826. // do nothing
  8827. int result = 0;
  8828. #else
  8829. int result = mkdir(pathname_.c_str(), 0777);
  8830. #endif // GTEST_OS_WINDOWS_MOBILE
  8831. if (result == -1) {
  8832. return this->DirectoryExists(); // An error is OK if the directory exists.
  8833. }
  8834. return true; // No error.
  8835. }
  8836. // If input name has a trailing separator character, remove it and return the
  8837. // name, otherwise return the name string unmodified.
  8838. // On Windows platform, uses \ as the separator, other platforms use /.
  8839. FilePath FilePath::RemoveTrailingPathSeparator() const {
  8840. return IsDirectory()
  8841. ? FilePath(pathname_.substr(0, pathname_.length() - 1))
  8842. : *this;
  8843. }
  8844. // Removes any redundant separators that might be in the pathname.
  8845. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
  8846. // redundancies that might be in a pathname involving "." or "..".
  8847. void FilePath::Normalize() {
  8848. auto out = pathname_.begin();
  8849. for (const char character : pathname_) {
  8850. if (!IsPathSeparator(character)) {
  8851. *(out++) = character;
  8852. } else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {
  8853. *(out++) = kPathSeparator;
  8854. } else {
  8855. continue;
  8856. }
  8857. }
  8858. pathname_.erase(out, pathname_.end());
  8859. }
  8860. } // namespace internal
  8861. } // namespace testing
  8862. // Copyright 2007, Google Inc.
  8863. // All rights reserved.
  8864. //
  8865. // Redistribution and use in source and binary forms, with or without
  8866. // modification, are permitted provided that the following conditions are
  8867. // met:
  8868. //
  8869. // * Redistributions of source code must retain the above copyright
  8870. // notice, this list of conditions and the following disclaimer.
  8871. // * Redistributions in binary form must reproduce the above
  8872. // copyright notice, this list of conditions and the following disclaimer
  8873. // in the documentation and/or other materials provided with the
  8874. // distribution.
  8875. // * Neither the name of Google Inc. nor the names of its
  8876. // contributors may be used to endorse or promote products derived from
  8877. // this software without specific prior written permission.
  8878. //
  8879. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8880. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8881. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8882. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8883. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8884. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8885. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8886. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8887. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8888. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8889. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8890. // The Google C++ Testing and Mocking Framework (Google Test)
  8891. //
  8892. // This file implements just enough of the matcher interface to allow
  8893. // EXPECT_DEATH and friends to accept a matcher argument.
  8894. #include <string>
  8895. namespace testing {
  8896. // Constructs a matcher that matches a const std::string& whose value is
  8897. // equal to s.
  8898. Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); }
  8899. // Constructs a matcher that matches a const std::string& whose value is
  8900. // equal to s.
  8901. Matcher<const std::string&>::Matcher(const char* s) {
  8902. *this = Eq(std::string(s));
  8903. }
  8904. // Constructs a matcher that matches a std::string whose value is equal to
  8905. // s.
  8906. Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }
  8907. // Constructs a matcher that matches a std::string whose value is equal to
  8908. // s.
  8909. Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }
  8910. #if GTEST_INTERNAL_HAS_STRING_VIEW
  8911. // Constructs a matcher that matches a const StringView& whose value is
  8912. // equal to s.
  8913. Matcher<const internal::StringView&>::Matcher(const std::string& s) {
  8914. *this = Eq(s);
  8915. }
  8916. // Constructs a matcher that matches a const StringView& whose value is
  8917. // equal to s.
  8918. Matcher<const internal::StringView&>::Matcher(const char* s) {
  8919. *this = Eq(std::string(s));
  8920. }
  8921. // Constructs a matcher that matches a const StringView& whose value is
  8922. // equal to s.
  8923. Matcher<const internal::StringView&>::Matcher(internal::StringView s) {
  8924. *this = Eq(std::string(s));
  8925. }
  8926. // Constructs a matcher that matches a StringView whose value is equal to
  8927. // s.
  8928. Matcher<internal::StringView>::Matcher(const std::string& s) { *this = Eq(s); }
  8929. // Constructs a matcher that matches a StringView whose value is equal to
  8930. // s.
  8931. Matcher<internal::StringView>::Matcher(const char* s) {
  8932. *this = Eq(std::string(s));
  8933. }
  8934. // Constructs a matcher that matches a StringView whose value is equal to
  8935. // s.
  8936. Matcher<internal::StringView>::Matcher(internal::StringView s) {
  8937. *this = Eq(std::string(s));
  8938. }
  8939. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  8940. } // namespace testing
  8941. // Copyright 2008, Google Inc.
  8942. // All rights reserved.
  8943. //
  8944. // Redistribution and use in source and binary forms, with or without
  8945. // modification, are permitted provided that the following conditions are
  8946. // met:
  8947. //
  8948. // * Redistributions of source code must retain the above copyright
  8949. // notice, this list of conditions and the following disclaimer.
  8950. // * Redistributions in binary form must reproduce the above
  8951. // copyright notice, this list of conditions and the following disclaimer
  8952. // in the documentation and/or other materials provided with the
  8953. // distribution.
  8954. // * Neither the name of Google Inc. nor the names of its
  8955. // contributors may be used to endorse or promote products derived from
  8956. // this software without specific prior written permission.
  8957. //
  8958. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8959. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8960. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8961. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8962. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8963. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8964. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8965. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8966. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8967. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8968. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8969. #include <limits.h>
  8970. #include <stdio.h>
  8971. #include <stdlib.h>
  8972. #include <string.h>
  8973. #include <cstdint>
  8974. #include <fstream>
  8975. #include <memory>
  8976. #if GTEST_OS_WINDOWS
  8977. # include <windows.h>
  8978. # include <io.h>
  8979. # include <sys/stat.h>
  8980. # include <map> // Used in ThreadLocal.
  8981. # ifdef _MSC_VER
  8982. # include <crtdbg.h>
  8983. # endif // _MSC_VER
  8984. #else
  8985. # include <unistd.h>
  8986. #endif // GTEST_OS_WINDOWS
  8987. #if GTEST_OS_MAC
  8988. # include <mach/mach_init.h>
  8989. # include <mach/task.h>
  8990. # include <mach/vm_map.h>
  8991. #endif // GTEST_OS_MAC
  8992. #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
  8993. GTEST_OS_NETBSD || GTEST_OS_OPENBSD
  8994. # include <sys/sysctl.h>
  8995. # if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
  8996. # include <sys/user.h>
  8997. # endif
  8998. #endif
  8999. #if GTEST_OS_QNX
  9000. # include <devctl.h>
  9001. # include <fcntl.h>
  9002. # include <sys/procfs.h>
  9003. #endif // GTEST_OS_QNX
  9004. #if GTEST_OS_AIX
  9005. # include <procinfo.h>
  9006. # include <sys/types.h>
  9007. #endif // GTEST_OS_AIX
  9008. #if GTEST_OS_FUCHSIA
  9009. # include <zircon/process.h>
  9010. # include <zircon/syscalls.h>
  9011. #endif // GTEST_OS_FUCHSIA
  9012. namespace testing {
  9013. namespace internal {
  9014. #if defined(_MSC_VER) || defined(__BORLANDC__)
  9015. // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
  9016. const int kStdOutFileno = 1;
  9017. const int kStdErrFileno = 2;
  9018. #else
  9019. const int kStdOutFileno = STDOUT_FILENO;
  9020. const int kStdErrFileno = STDERR_FILENO;
  9021. #endif // _MSC_VER
  9022. #if GTEST_OS_LINUX
  9023. namespace {
  9024. template <typename T>
  9025. T ReadProcFileField(const std::string& filename, int field) {
  9026. std::string dummy;
  9027. std::ifstream file(filename.c_str());
  9028. while (field-- > 0) {
  9029. file >> dummy;
  9030. }
  9031. T output = 0;
  9032. file >> output;
  9033. return output;
  9034. }
  9035. } // namespace
  9036. // Returns the number of active threads, or 0 when there is an error.
  9037. size_t GetThreadCount() {
  9038. const std::string filename =
  9039. (Message() << "/proc/" << getpid() << "/stat").GetString();
  9040. return ReadProcFileField<size_t>(filename, 19);
  9041. }
  9042. #elif GTEST_OS_MAC
  9043. size_t GetThreadCount() {
  9044. const task_t task = mach_task_self();
  9045. mach_msg_type_number_t thread_count;
  9046. thread_act_array_t thread_list;
  9047. const kern_return_t status = task_threads(task, &thread_list, &thread_count);
  9048. if (status == KERN_SUCCESS) {
  9049. // task_threads allocates resources in thread_list and we need to free them
  9050. // to avoid leaks.
  9051. vm_deallocate(task,
  9052. reinterpret_cast<vm_address_t>(thread_list),
  9053. sizeof(thread_t) * thread_count);
  9054. return static_cast<size_t>(thread_count);
  9055. } else {
  9056. return 0;
  9057. }
  9058. }
  9059. #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
  9060. GTEST_OS_NETBSD
  9061. #if GTEST_OS_NETBSD
  9062. #undef KERN_PROC
  9063. #define KERN_PROC KERN_PROC2
  9064. #define kinfo_proc kinfo_proc2
  9065. #endif
  9066. #if GTEST_OS_DRAGONFLY
  9067. #define KP_NLWP(kp) (kp.kp_nthreads)
  9068. #elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
  9069. #define KP_NLWP(kp) (kp.ki_numthreads)
  9070. #elif GTEST_OS_NETBSD
  9071. #define KP_NLWP(kp) (kp.p_nlwps)
  9072. #endif
  9073. // Returns the number of threads running in the process, or 0 to indicate that
  9074. // we cannot detect it.
  9075. size_t GetThreadCount() {
  9076. int mib[] = {
  9077. CTL_KERN,
  9078. KERN_PROC,
  9079. KERN_PROC_PID,
  9080. getpid(),
  9081. #if GTEST_OS_NETBSD
  9082. sizeof(struct kinfo_proc),
  9083. 1,
  9084. #endif
  9085. };
  9086. u_int miblen = sizeof(mib) / sizeof(mib[0]);
  9087. struct kinfo_proc info;
  9088. size_t size = sizeof(info);
  9089. if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
  9090. return 0;
  9091. }
  9092. return static_cast<size_t>(KP_NLWP(info));
  9093. }
  9094. #elif GTEST_OS_OPENBSD
  9095. // Returns the number of threads running in the process, or 0 to indicate that
  9096. // we cannot detect it.
  9097. size_t GetThreadCount() {
  9098. int mib[] = {
  9099. CTL_KERN,
  9100. KERN_PROC,
  9101. KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
  9102. getpid(),
  9103. sizeof(struct kinfo_proc),
  9104. 0,
  9105. };
  9106. u_int miblen = sizeof(mib) / sizeof(mib[0]);
  9107. // get number of structs
  9108. size_t size;
  9109. if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
  9110. return 0;
  9111. }
  9112. mib[5] = static_cast<int>(size / static_cast<size_t>(mib[4]));
  9113. // populate array of structs
  9114. struct kinfo_proc info[mib[5]];
  9115. if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
  9116. return 0;
  9117. }
  9118. // exclude empty members
  9119. size_t nthreads = 0;
  9120. for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) {
  9121. if (info[i].p_tid != -1)
  9122. nthreads++;
  9123. }
  9124. return nthreads;
  9125. }
  9126. #elif GTEST_OS_QNX
  9127. // Returns the number of threads running in the process, or 0 to indicate that
  9128. // we cannot detect it.
  9129. size_t GetThreadCount() {
  9130. const int fd = open("/proc/self/as", O_RDONLY);
  9131. if (fd < 0) {
  9132. return 0;
  9133. }
  9134. procfs_info process_info;
  9135. const int status =
  9136. devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);
  9137. close(fd);
  9138. if (status == EOK) {
  9139. return static_cast<size_t>(process_info.num_threads);
  9140. } else {
  9141. return 0;
  9142. }
  9143. }
  9144. #elif GTEST_OS_AIX
  9145. size_t GetThreadCount() {
  9146. struct procentry64 entry;
  9147. pid_t pid = getpid();
  9148. int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);
  9149. if (status == 1) {
  9150. return entry.pi_thcount;
  9151. } else {
  9152. return 0;
  9153. }
  9154. }
  9155. #elif GTEST_OS_FUCHSIA
  9156. size_t GetThreadCount() {
  9157. int dummy_buffer;
  9158. size_t avail;
  9159. zx_status_t status = zx_object_get_info(
  9160. zx_process_self(),
  9161. ZX_INFO_PROCESS_THREADS,
  9162. &dummy_buffer,
  9163. 0,
  9164. nullptr,
  9165. &avail);
  9166. if (status == ZX_OK) {
  9167. return avail;
  9168. } else {
  9169. return 0;
  9170. }
  9171. }
  9172. #else
  9173. size_t GetThreadCount() {
  9174. // There's no portable way to detect the number of threads, so we just
  9175. // return 0 to indicate that we cannot detect it.
  9176. return 0;
  9177. }
  9178. #endif // GTEST_OS_LINUX
  9179. #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
  9180. void SleepMilliseconds(int n) {
  9181. ::Sleep(static_cast<DWORD>(n));
  9182. }
  9183. AutoHandle::AutoHandle()
  9184. : handle_(INVALID_HANDLE_VALUE) {}
  9185. AutoHandle::AutoHandle(Handle handle)
  9186. : handle_(handle) {}
  9187. AutoHandle::~AutoHandle() {
  9188. Reset();
  9189. }
  9190. AutoHandle::Handle AutoHandle::Get() const {
  9191. return handle_;
  9192. }
  9193. void AutoHandle::Reset() {
  9194. Reset(INVALID_HANDLE_VALUE);
  9195. }
  9196. void AutoHandle::Reset(HANDLE handle) {
  9197. // Resetting with the same handle we already own is invalid.
  9198. if (handle_ != handle) {
  9199. if (IsCloseable()) {
  9200. ::CloseHandle(handle_);
  9201. }
  9202. handle_ = handle;
  9203. } else {
  9204. GTEST_CHECK_(!IsCloseable())
  9205. << "Resetting a valid handle to itself is likely a programmer error "
  9206. "and thus not allowed.";
  9207. }
  9208. }
  9209. bool AutoHandle::IsCloseable() const {
  9210. // Different Windows APIs may use either of these values to represent an
  9211. // invalid handle.
  9212. return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
  9213. }
  9214. Notification::Notification()
  9215. : event_(::CreateEvent(nullptr, // Default security attributes.
  9216. TRUE, // Do not reset automatically.
  9217. FALSE, // Initially unset.
  9218. nullptr)) { // Anonymous event.
  9219. GTEST_CHECK_(event_.Get() != nullptr);
  9220. }
  9221. void Notification::Notify() {
  9222. GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
  9223. }
  9224. void Notification::WaitForNotification() {
  9225. GTEST_CHECK_(
  9226. ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
  9227. }
  9228. Mutex::Mutex()
  9229. : owner_thread_id_(0),
  9230. type_(kDynamic),
  9231. critical_section_init_phase_(0),
  9232. critical_section_(new CRITICAL_SECTION) {
  9233. ::InitializeCriticalSection(critical_section_);
  9234. }
  9235. Mutex::~Mutex() {
  9236. // Static mutexes are leaked intentionally. It is not thread-safe to try
  9237. // to clean them up.
  9238. if (type_ == kDynamic) {
  9239. ::DeleteCriticalSection(critical_section_);
  9240. delete critical_section_;
  9241. critical_section_ = nullptr;
  9242. }
  9243. }
  9244. void Mutex::Lock() {
  9245. ThreadSafeLazyInit();
  9246. ::EnterCriticalSection(critical_section_);
  9247. owner_thread_id_ = ::GetCurrentThreadId();
  9248. }
  9249. void Mutex::Unlock() {
  9250. ThreadSafeLazyInit();
  9251. // We don't protect writing to owner_thread_id_ here, as it's the
  9252. // caller's responsibility to ensure that the current thread holds the
  9253. // mutex when this is called.
  9254. owner_thread_id_ = 0;
  9255. ::LeaveCriticalSection(critical_section_);
  9256. }
  9257. // Does nothing if the current thread holds the mutex. Otherwise, crashes
  9258. // with high probability.
  9259. void Mutex::AssertHeld() {
  9260. ThreadSafeLazyInit();
  9261. GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
  9262. << "The current thread is not holding the mutex @" << this;
  9263. }
  9264. namespace {
  9265. #ifdef _MSC_VER
  9266. // Use the RAII idiom to flag mem allocs that are intentionally never
  9267. // deallocated. The motivation is to silence the false positive mem leaks
  9268. // that are reported by the debug version of MS's CRT which can only detect
  9269. // if an alloc is missing a matching deallocation.
  9270. // Example:
  9271. // MemoryIsNotDeallocated memory_is_not_deallocated;
  9272. // critical_section_ = new CRITICAL_SECTION;
  9273. //
  9274. class MemoryIsNotDeallocated
  9275. {
  9276. public:
  9277. MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
  9278. old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  9279. // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
  9280. // doesn't report mem leak if there's no matching deallocation.
  9281. _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
  9282. }
  9283. ~MemoryIsNotDeallocated() {
  9284. // Restore the original _CRTDBG_ALLOC_MEM_DF flag
  9285. _CrtSetDbgFlag(old_crtdbg_flag_);
  9286. }
  9287. private:
  9288. int old_crtdbg_flag_;
  9289. GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
  9290. };
  9291. #endif // _MSC_VER
  9292. } // namespace
  9293. // Initializes owner_thread_id_ and critical_section_ in static mutexes.
  9294. void Mutex::ThreadSafeLazyInit() {
  9295. // Dynamic mutexes are initialized in the constructor.
  9296. if (type_ == kStatic) {
  9297. switch (
  9298. ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
  9299. case 0:
  9300. // If critical_section_init_phase_ was 0 before the exchange, we
  9301. // are the first to test it and need to perform the initialization.
  9302. owner_thread_id_ = 0;
  9303. {
  9304. // Use RAII to flag that following mem alloc is never deallocated.
  9305. #ifdef _MSC_VER
  9306. MemoryIsNotDeallocated memory_is_not_deallocated;
  9307. #endif // _MSC_VER
  9308. critical_section_ = new CRITICAL_SECTION;
  9309. }
  9310. ::InitializeCriticalSection(critical_section_);
  9311. // Updates the critical_section_init_phase_ to 2 to signal
  9312. // initialization complete.
  9313. GTEST_CHECK_(::InterlockedCompareExchange(
  9314. &critical_section_init_phase_, 2L, 1L) ==
  9315. 1L);
  9316. break;
  9317. case 1:
  9318. // Somebody else is already initializing the mutex; spin until they
  9319. // are done.
  9320. while (::InterlockedCompareExchange(&critical_section_init_phase_,
  9321. 2L,
  9322. 2L) != 2L) {
  9323. // Possibly yields the rest of the thread's time slice to other
  9324. // threads.
  9325. ::Sleep(0);
  9326. }
  9327. break;
  9328. case 2:
  9329. break; // The mutex is already initialized and ready for use.
  9330. default:
  9331. GTEST_CHECK_(false)
  9332. << "Unexpected value of critical_section_init_phase_ "
  9333. << "while initializing a static mutex.";
  9334. }
  9335. }
  9336. }
  9337. namespace {
  9338. class ThreadWithParamSupport : public ThreadWithParamBase {
  9339. public:
  9340. static HANDLE CreateThread(Runnable* runnable,
  9341. Notification* thread_can_start) {
  9342. ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
  9343. DWORD thread_id;
  9344. HANDLE thread_handle = ::CreateThread(
  9345. nullptr, // Default security.
  9346. 0, // Default stack size.
  9347. &ThreadWithParamSupport::ThreadMain,
  9348. param, // Parameter to ThreadMainStatic
  9349. 0x0, // Default creation flags.
  9350. &thread_id); // Need a valid pointer for the call to work under Win98.
  9351. GTEST_CHECK_(thread_handle != nullptr)
  9352. << "CreateThread failed with error " << ::GetLastError() << ".";
  9353. if (thread_handle == nullptr) {
  9354. delete param;
  9355. }
  9356. return thread_handle;
  9357. }
  9358. private:
  9359. struct ThreadMainParam {
  9360. ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
  9361. : runnable_(runnable),
  9362. thread_can_start_(thread_can_start) {
  9363. }
  9364. std::unique_ptr<Runnable> runnable_;
  9365. // Does not own.
  9366. Notification* thread_can_start_;
  9367. };
  9368. static DWORD WINAPI ThreadMain(void* ptr) {
  9369. // Transfers ownership.
  9370. std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
  9371. if (param->thread_can_start_ != nullptr)
  9372. param->thread_can_start_->WaitForNotification();
  9373. param->runnable_->Run();
  9374. return 0;
  9375. }
  9376. // Prohibit instantiation.
  9377. ThreadWithParamSupport();
  9378. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
  9379. };
  9380. } // namespace
  9381. ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
  9382. Notification* thread_can_start)
  9383. : thread_(ThreadWithParamSupport::CreateThread(runnable,
  9384. thread_can_start)) {
  9385. }
  9386. ThreadWithParamBase::~ThreadWithParamBase() {
  9387. Join();
  9388. }
  9389. void ThreadWithParamBase::Join() {
  9390. GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
  9391. << "Failed to join the thread with error " << ::GetLastError() << ".";
  9392. }
  9393. // Maps a thread to a set of ThreadIdToThreadLocals that have values
  9394. // instantiated on that thread and notifies them when the thread exits. A
  9395. // ThreadLocal instance is expected to persist until all threads it has
  9396. // values on have terminated.
  9397. class ThreadLocalRegistryImpl {
  9398. public:
  9399. // Registers thread_local_instance as having value on the current thread.
  9400. // Returns a value that can be used to identify the thread from other threads.
  9401. static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
  9402. const ThreadLocalBase* thread_local_instance) {
  9403. #ifdef _MSC_VER
  9404. MemoryIsNotDeallocated memory_is_not_deallocated;
  9405. #endif // _MSC_VER
  9406. DWORD current_thread = ::GetCurrentThreadId();
  9407. MutexLock lock(&mutex_);
  9408. ThreadIdToThreadLocals* const thread_to_thread_locals =
  9409. GetThreadLocalsMapLocked();
  9410. ThreadIdToThreadLocals::iterator thread_local_pos =
  9411. thread_to_thread_locals->find(current_thread);
  9412. if (thread_local_pos == thread_to_thread_locals->end()) {
  9413. thread_local_pos = thread_to_thread_locals->insert(
  9414. std::make_pair(current_thread, ThreadLocalValues())).first;
  9415. StartWatcherThreadFor(current_thread);
  9416. }
  9417. ThreadLocalValues& thread_local_values = thread_local_pos->second;
  9418. ThreadLocalValues::iterator value_pos =
  9419. thread_local_values.find(thread_local_instance);
  9420. if (value_pos == thread_local_values.end()) {
  9421. value_pos =
  9422. thread_local_values
  9423. .insert(std::make_pair(
  9424. thread_local_instance,
  9425. std::shared_ptr<ThreadLocalValueHolderBase>(
  9426. thread_local_instance->NewValueForCurrentThread())))
  9427. .first;
  9428. }
  9429. return value_pos->second.get();
  9430. }
  9431. static void OnThreadLocalDestroyed(
  9432. const ThreadLocalBase* thread_local_instance) {
  9433. std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
  9434. // Clean up the ThreadLocalValues data structure while holding the lock, but
  9435. // defer the destruction of the ThreadLocalValueHolderBases.
  9436. {
  9437. MutexLock lock(&mutex_);
  9438. ThreadIdToThreadLocals* const thread_to_thread_locals =
  9439. GetThreadLocalsMapLocked();
  9440. for (ThreadIdToThreadLocals::iterator it =
  9441. thread_to_thread_locals->begin();
  9442. it != thread_to_thread_locals->end();
  9443. ++it) {
  9444. ThreadLocalValues& thread_local_values = it->second;
  9445. ThreadLocalValues::iterator value_pos =
  9446. thread_local_values.find(thread_local_instance);
  9447. if (value_pos != thread_local_values.end()) {
  9448. value_holders.push_back(value_pos->second);
  9449. thread_local_values.erase(value_pos);
  9450. // This 'if' can only be successful at most once, so theoretically we
  9451. // could break out of the loop here, but we don't bother doing so.
  9452. }
  9453. }
  9454. }
  9455. // Outside the lock, let the destructor for 'value_holders' deallocate the
  9456. // ThreadLocalValueHolderBases.
  9457. }
  9458. static void OnThreadExit(DWORD thread_id) {
  9459. GTEST_CHECK_(thread_id != 0) << ::GetLastError();
  9460. std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
  9461. // Clean up the ThreadIdToThreadLocals data structure while holding the
  9462. // lock, but defer the destruction of the ThreadLocalValueHolderBases.
  9463. {
  9464. MutexLock lock(&mutex_);
  9465. ThreadIdToThreadLocals* const thread_to_thread_locals =
  9466. GetThreadLocalsMapLocked();
  9467. ThreadIdToThreadLocals::iterator thread_local_pos =
  9468. thread_to_thread_locals->find(thread_id);
  9469. if (thread_local_pos != thread_to_thread_locals->end()) {
  9470. ThreadLocalValues& thread_local_values = thread_local_pos->second;
  9471. for (ThreadLocalValues::iterator value_pos =
  9472. thread_local_values.begin();
  9473. value_pos != thread_local_values.end();
  9474. ++value_pos) {
  9475. value_holders.push_back(value_pos->second);
  9476. }
  9477. thread_to_thread_locals->erase(thread_local_pos);
  9478. }
  9479. }
  9480. // Outside the lock, let the destructor for 'value_holders' deallocate the
  9481. // ThreadLocalValueHolderBases.
  9482. }
  9483. private:
  9484. // In a particular thread, maps a ThreadLocal object to its value.
  9485. typedef std::map<const ThreadLocalBase*,
  9486. std::shared_ptr<ThreadLocalValueHolderBase> >
  9487. ThreadLocalValues;
  9488. // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
  9489. // thread's ID.
  9490. typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
  9491. // Holds the thread id and thread handle that we pass from
  9492. // StartWatcherThreadFor to WatcherThreadFunc.
  9493. typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
  9494. static void StartWatcherThreadFor(DWORD thread_id) {
  9495. // The returned handle will be kept in thread_map and closed by
  9496. // watcher_thread in WatcherThreadFunc.
  9497. HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
  9498. FALSE,
  9499. thread_id);
  9500. GTEST_CHECK_(thread != nullptr);
  9501. // We need to pass a valid thread ID pointer into CreateThread for it
  9502. // to work correctly under Win98.
  9503. DWORD watcher_thread_id;
  9504. HANDLE watcher_thread = ::CreateThread(
  9505. nullptr, // Default security.
  9506. 0, // Default stack size
  9507. &ThreadLocalRegistryImpl::WatcherThreadFunc,
  9508. reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
  9509. CREATE_SUSPENDED, &watcher_thread_id);
  9510. GTEST_CHECK_(watcher_thread != nullptr);
  9511. // Give the watcher thread the same priority as ours to avoid being
  9512. // blocked by it.
  9513. ::SetThreadPriority(watcher_thread,
  9514. ::GetThreadPriority(::GetCurrentThread()));
  9515. ::ResumeThread(watcher_thread);
  9516. ::CloseHandle(watcher_thread);
  9517. }
  9518. // Monitors exit from a given thread and notifies those
  9519. // ThreadIdToThreadLocals about thread termination.
  9520. static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
  9521. const ThreadIdAndHandle* tah =
  9522. reinterpret_cast<const ThreadIdAndHandle*>(param);
  9523. GTEST_CHECK_(
  9524. ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
  9525. OnThreadExit(tah->first);
  9526. ::CloseHandle(tah->second);
  9527. delete tah;
  9528. return 0;
  9529. }
  9530. // Returns map of thread local instances.
  9531. static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
  9532. mutex_.AssertHeld();
  9533. #ifdef _MSC_VER
  9534. MemoryIsNotDeallocated memory_is_not_deallocated;
  9535. #endif // _MSC_VER
  9536. static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
  9537. return map;
  9538. }
  9539. // Protects access to GetThreadLocalsMapLocked() and its return value.
  9540. static Mutex mutex_;
  9541. // Protects access to GetThreadMapLocked() and its return value.
  9542. static Mutex thread_map_mutex_;
  9543. };
  9544. Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); // NOLINT
  9545. Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); // NOLINT
  9546. ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
  9547. const ThreadLocalBase* thread_local_instance) {
  9548. return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
  9549. thread_local_instance);
  9550. }
  9551. void ThreadLocalRegistry::OnThreadLocalDestroyed(
  9552. const ThreadLocalBase* thread_local_instance) {
  9553. ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
  9554. }
  9555. #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
  9556. #if GTEST_USES_POSIX_RE
  9557. // Implements RE. Currently only needed for death tests.
  9558. RE::~RE() {
  9559. if (is_valid_) {
  9560. // regfree'ing an invalid regex might crash because the content
  9561. // of the regex is undefined. Since the regex's are essentially
  9562. // the same, one cannot be valid (or invalid) without the other
  9563. // being so too.
  9564. regfree(&partial_regex_);
  9565. regfree(&full_regex_);
  9566. }
  9567. free(const_cast<char*>(pattern_));
  9568. }
  9569. // Returns true if and only if regular expression re matches the entire str.
  9570. bool RE::FullMatch(const char* str, const RE& re) {
  9571. if (!re.is_valid_) return false;
  9572. regmatch_t match;
  9573. return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
  9574. }
  9575. // Returns true if and only if regular expression re matches a substring of
  9576. // str (including str itself).
  9577. bool RE::PartialMatch(const char* str, const RE& re) {
  9578. if (!re.is_valid_) return false;
  9579. regmatch_t match;
  9580. return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
  9581. }
  9582. // Initializes an RE from its string representation.
  9583. void RE::Init(const char* regex) {
  9584. pattern_ = posix::StrDup(regex);
  9585. // Reserves enough bytes to hold the regular expression used for a
  9586. // full match.
  9587. const size_t full_regex_len = strlen(regex) + 10;
  9588. char* const full_pattern = new char[full_regex_len];
  9589. snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
  9590. is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
  9591. // We want to call regcomp(&partial_regex_, ...) even if the
  9592. // previous expression returns false. Otherwise partial_regex_ may
  9593. // not be properly initialized can may cause trouble when it's
  9594. // freed.
  9595. //
  9596. // Some implementation of POSIX regex (e.g. on at least some
  9597. // versions of Cygwin) doesn't accept the empty string as a valid
  9598. // regex. We change it to an equivalent form "()" to be safe.
  9599. if (is_valid_) {
  9600. const char* const partial_regex = (*regex == '\0') ? "()" : regex;
  9601. is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
  9602. }
  9603. EXPECT_TRUE(is_valid_)
  9604. << "Regular expression \"" << regex
  9605. << "\" is not a valid POSIX Extended regular expression.";
  9606. delete[] full_pattern;
  9607. }
  9608. #elif GTEST_USES_SIMPLE_RE
  9609. // Returns true if and only if ch appears anywhere in str (excluding the
  9610. // terminating '\0' character).
  9611. bool IsInSet(char ch, const char* str) {
  9612. return ch != '\0' && strchr(str, ch) != nullptr;
  9613. }
  9614. // Returns true if and only if ch belongs to the given classification.
  9615. // Unlike similar functions in <ctype.h>, these aren't affected by the
  9616. // current locale.
  9617. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
  9618. bool IsAsciiPunct(char ch) {
  9619. return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
  9620. }
  9621. bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
  9622. bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
  9623. bool IsAsciiWordChar(char ch) {
  9624. return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
  9625. ('0' <= ch && ch <= '9') || ch == '_';
  9626. }
  9627. // Returns true if and only if "\\c" is a supported escape sequence.
  9628. bool IsValidEscape(char c) {
  9629. return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
  9630. }
  9631. // Returns true if and only if the given atom (specified by escaped and
  9632. // pattern) matches ch. The result is undefined if the atom is invalid.
  9633. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
  9634. if (escaped) { // "\\p" where p is pattern_char.
  9635. switch (pattern_char) {
  9636. case 'd': return IsAsciiDigit(ch);
  9637. case 'D': return !IsAsciiDigit(ch);
  9638. case 'f': return ch == '\f';
  9639. case 'n': return ch == '\n';
  9640. case 'r': return ch == '\r';
  9641. case 's': return IsAsciiWhiteSpace(ch);
  9642. case 'S': return !IsAsciiWhiteSpace(ch);
  9643. case 't': return ch == '\t';
  9644. case 'v': return ch == '\v';
  9645. case 'w': return IsAsciiWordChar(ch);
  9646. case 'W': return !IsAsciiWordChar(ch);
  9647. }
  9648. return IsAsciiPunct(pattern_char) && pattern_char == ch;
  9649. }
  9650. return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
  9651. }
  9652. // Helper function used by ValidateRegex() to format error messages.
  9653. static std::string FormatRegexSyntaxError(const char* regex, int index) {
  9654. return (Message() << "Syntax error at index " << index
  9655. << " in simple regular expression \"" << regex << "\": ").GetString();
  9656. }
  9657. // Generates non-fatal failures and returns false if regex is invalid;
  9658. // otherwise returns true.
  9659. bool ValidateRegex(const char* regex) {
  9660. if (regex == nullptr) {
  9661. ADD_FAILURE() << "NULL is not a valid simple regular expression.";
  9662. return false;
  9663. }
  9664. bool is_valid = true;
  9665. // True if and only if ?, *, or + can follow the previous atom.
  9666. bool prev_repeatable = false;
  9667. for (int i = 0; regex[i]; i++) {
  9668. if (regex[i] == '\\') { // An escape sequence
  9669. i++;
  9670. if (regex[i] == '\0') {
  9671. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  9672. << "'\\' cannot appear at the end.";
  9673. return false;
  9674. }
  9675. if (!IsValidEscape(regex[i])) {
  9676. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  9677. << "invalid escape sequence \"\\" << regex[i] << "\".";
  9678. is_valid = false;
  9679. }
  9680. prev_repeatable = true;
  9681. } else { // Not an escape sequence.
  9682. const char ch = regex[i];
  9683. if (ch == '^' && i > 0) {
  9684. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  9685. << "'^' can only appear at the beginning.";
  9686. is_valid = false;
  9687. } else if (ch == '$' && regex[i + 1] != '\0') {
  9688. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  9689. << "'$' can only appear at the end.";
  9690. is_valid = false;
  9691. } else if (IsInSet(ch, "()[]{}|")) {
  9692. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  9693. << "'" << ch << "' is unsupported.";
  9694. is_valid = false;
  9695. } else if (IsRepeat(ch) && !prev_repeatable) {
  9696. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  9697. << "'" << ch << "' can only follow a repeatable token.";
  9698. is_valid = false;
  9699. }
  9700. prev_repeatable = !IsInSet(ch, "^$?*+");
  9701. }
  9702. }
  9703. return is_valid;
  9704. }
  9705. // Matches a repeated regex atom followed by a valid simple regular
  9706. // expression. The regex atom is defined as c if escaped is false,
  9707. // or \c otherwise. repeat is the repetition meta character (?, *,
  9708. // or +). The behavior is undefined if str contains too many
  9709. // characters to be indexable by size_t, in which case the test will
  9710. // probably time out anyway. We are fine with this limitation as
  9711. // std::string has it too.
  9712. bool MatchRepetitionAndRegexAtHead(
  9713. bool escaped, char c, char repeat, const char* regex,
  9714. const char* str) {
  9715. const size_t min_count = (repeat == '+') ? 1 : 0;
  9716. const size_t max_count = (repeat == '?') ? 1 :
  9717. static_cast<size_t>(-1) - 1;
  9718. // We cannot call numeric_limits::max() as it conflicts with the
  9719. // max() macro on Windows.
  9720. for (size_t i = 0; i <= max_count; ++i) {
  9721. // We know that the atom matches each of the first i characters in str.
  9722. if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
  9723. // We have enough matches at the head, and the tail matches too.
  9724. // Since we only care about *whether* the pattern matches str
  9725. // (as opposed to *how* it matches), there is no need to find a
  9726. // greedy match.
  9727. return true;
  9728. }
  9729. if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
  9730. return false;
  9731. }
  9732. return false;
  9733. }
  9734. // Returns true if and only if regex matches a prefix of str. regex must
  9735. // be a valid simple regular expression and not start with "^", or the
  9736. // result is undefined.
  9737. bool MatchRegexAtHead(const char* regex, const char* str) {
  9738. if (*regex == '\0') // An empty regex matches a prefix of anything.
  9739. return true;
  9740. // "$" only matches the end of a string. Note that regex being
  9741. // valid guarantees that there's nothing after "$" in it.
  9742. if (*regex == '$')
  9743. return *str == '\0';
  9744. // Is the first thing in regex an escape sequence?
  9745. const bool escaped = *regex == '\\';
  9746. if (escaped)
  9747. ++regex;
  9748. if (IsRepeat(regex[1])) {
  9749. // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
  9750. // here's an indirect recursion. It terminates as the regex gets
  9751. // shorter in each recursion.
  9752. return MatchRepetitionAndRegexAtHead(
  9753. escaped, regex[0], regex[1], regex + 2, str);
  9754. } else {
  9755. // regex isn't empty, isn't "$", and doesn't start with a
  9756. // repetition. We match the first atom of regex with the first
  9757. // character of str and recurse.
  9758. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
  9759. MatchRegexAtHead(regex + 1, str + 1);
  9760. }
  9761. }
  9762. // Returns true if and only if regex matches any substring of str. regex must
  9763. // be a valid simple regular expression, or the result is undefined.
  9764. //
  9765. // The algorithm is recursive, but the recursion depth doesn't exceed
  9766. // the regex length, so we won't need to worry about running out of
  9767. // stack space normally. In rare cases the time complexity can be
  9768. // exponential with respect to the regex length + the string length,
  9769. // but usually it's must faster (often close to linear).
  9770. bool MatchRegexAnywhere(const char* regex, const char* str) {
  9771. if (regex == nullptr || str == nullptr) return false;
  9772. if (*regex == '^')
  9773. return MatchRegexAtHead(regex + 1, str);
  9774. // A successful match can be anywhere in str.
  9775. do {
  9776. if (MatchRegexAtHead(regex, str))
  9777. return true;
  9778. } while (*str++ != '\0');
  9779. return false;
  9780. }
  9781. // Implements the RE class.
  9782. RE::~RE() {
  9783. free(const_cast<char*>(pattern_));
  9784. free(const_cast<char*>(full_pattern_));
  9785. }
  9786. // Returns true if and only if regular expression re matches the entire str.
  9787. bool RE::FullMatch(const char* str, const RE& re) {
  9788. return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
  9789. }
  9790. // Returns true if and only if regular expression re matches a substring of
  9791. // str (including str itself).
  9792. bool RE::PartialMatch(const char* str, const RE& re) {
  9793. return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
  9794. }
  9795. // Initializes an RE from its string representation.
  9796. void RE::Init(const char* regex) {
  9797. pattern_ = full_pattern_ = nullptr;
  9798. if (regex != nullptr) {
  9799. pattern_ = posix::StrDup(regex);
  9800. }
  9801. is_valid_ = ValidateRegex(regex);
  9802. if (!is_valid_) {
  9803. // No need to calculate the full pattern when the regex is invalid.
  9804. return;
  9805. }
  9806. const size_t len = strlen(regex);
  9807. // Reserves enough bytes to hold the regular expression used for a
  9808. // full match: we need space to prepend a '^', append a '$', and
  9809. // terminate the string with '\0'.
  9810. char* buffer = static_cast<char*>(malloc(len + 3));
  9811. full_pattern_ = buffer;
  9812. if (*regex != '^')
  9813. *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
  9814. // We don't use snprintf or strncpy, as they trigger a warning when
  9815. // compiled with VC++ 8.0.
  9816. memcpy(buffer, regex, len);
  9817. buffer += len;
  9818. if (len == 0 || regex[len - 1] != '$')
  9819. *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
  9820. *buffer = '\0';
  9821. }
  9822. #endif // GTEST_USES_POSIX_RE
  9823. const char kUnknownFile[] = "unknown file";
  9824. // Formats a source file path and a line number as they would appear
  9825. // in an error message from the compiler used to compile this code.
  9826. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
  9827. const std::string file_name(file == nullptr ? kUnknownFile : file);
  9828. if (line < 0) {
  9829. return file_name + ":";
  9830. }
  9831. #ifdef _MSC_VER
  9832. return file_name + "(" + StreamableToString(line) + "):";
  9833. #else
  9834. return file_name + ":" + StreamableToString(line) + ":";
  9835. #endif // _MSC_VER
  9836. }
  9837. // Formats a file location for compiler-independent XML output.
  9838. // Although this function is not platform dependent, we put it next to
  9839. // FormatFileLocation in order to contrast the two functions.
  9840. // Note that FormatCompilerIndependentFileLocation() does NOT append colon
  9841. // to the file location it produces, unlike FormatFileLocation().
  9842. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
  9843. const char* file, int line) {
  9844. const std::string file_name(file == nullptr ? kUnknownFile : file);
  9845. if (line < 0)
  9846. return file_name;
  9847. else
  9848. return file_name + ":" + StreamableToString(line);
  9849. }
  9850. GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
  9851. : severity_(severity) {
  9852. const char* const marker =
  9853. severity == GTEST_INFO ? "[ INFO ]" :
  9854. severity == GTEST_WARNING ? "[WARNING]" :
  9855. severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
  9856. GetStream() << ::std::endl << marker << " "
  9857. << FormatFileLocation(file, line).c_str() << ": ";
  9858. }
  9859. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  9860. GTestLog::~GTestLog() {
  9861. GetStream() << ::std::endl;
  9862. if (severity_ == GTEST_FATAL) {
  9863. fflush(stderr);
  9864. posix::Abort();
  9865. }
  9866. }
  9867. // Disable Microsoft deprecation warnings for POSIX functions called from
  9868. // this class (creat, dup, dup2, and close)
  9869. GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
  9870. #if GTEST_HAS_STREAM_REDIRECTION
  9871. // Object that captures an output stream (stdout/stderr).
  9872. class CapturedStream {
  9873. public:
  9874. // The ctor redirects the stream to a temporary file.
  9875. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
  9876. # if GTEST_OS_WINDOWS
  9877. char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  9878. char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  9879. ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
  9880. const UINT success = ::GetTempFileNameA(temp_dir_path,
  9881. "gtest_redir",
  9882. 0, // Generate unique file name.
  9883. temp_file_path);
  9884. GTEST_CHECK_(success != 0)
  9885. << "Unable to create a temporary file in " << temp_dir_path;
  9886. const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
  9887. GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
  9888. << temp_file_path;
  9889. filename_ = temp_file_path;
  9890. # else
  9891. // There's no guarantee that a test has write access to the current
  9892. // directory, so we create the temporary file in a temporary directory.
  9893. std::string name_template;
  9894. # if GTEST_OS_LINUX_ANDROID
  9895. // Note: Android applications are expected to call the framework's
  9896. // Context.getExternalStorageDirectory() method through JNI to get
  9897. // the location of the world-writable SD Card directory. However,
  9898. // this requires a Context handle, which cannot be retrieved
  9899. // globally from native code. Doing so also precludes running the
  9900. // code as part of a regular standalone executable, which doesn't
  9901. // run in a Dalvik process (e.g. when running it through 'adb shell').
  9902. //
  9903. // The location /data/local/tmp is directly accessible from native code.
  9904. // '/sdcard' and other variants cannot be relied on, as they are not
  9905. // guaranteed to be mounted, or may have a delay in mounting.
  9906. name_template = "/data/local/tmp/";
  9907. # elif GTEST_OS_IOS
  9908. char user_temp_dir[PATH_MAX + 1];
  9909. // Documented alternative to NSTemporaryDirectory() (for obtaining creating
  9910. // a temporary directory) at
  9911. // https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html#//apple_ref/doc/uid/TP40002585-SW10
  9912. //
  9913. // _CS_DARWIN_USER_TEMP_DIR (as well as _CS_DARWIN_USER_CACHE_DIR) is not
  9914. // documented in the confstr() man page at
  9915. // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/confstr.3.html#//apple_ref/doc/man/3/confstr
  9916. // but are still available, according to the WebKit patches at
  9917. // https://trac.webkit.org/changeset/262004/webkit
  9918. // https://trac.webkit.org/changeset/263705/webkit
  9919. //
  9920. // The confstr() implementation falls back to getenv("TMPDIR"). See
  9921. // https://opensource.apple.com/source/Libc/Libc-1439.100.3/gen/confstr.c.auto.html
  9922. ::confstr(_CS_DARWIN_USER_TEMP_DIR, user_temp_dir, sizeof(user_temp_dir));
  9923. name_template = user_temp_dir;
  9924. if (name_template.back() != GTEST_PATH_SEP_[0])
  9925. name_template.push_back(GTEST_PATH_SEP_[0]);
  9926. # else
  9927. name_template = "/tmp/";
  9928. # endif
  9929. name_template.append("gtest_captured_stream.XXXXXX");
  9930. // mkstemp() modifies the string bytes in place, and does not go beyond the
  9931. // string's length. This results in well-defined behavior in C++17.
  9932. //
  9933. // The const_cast is needed below C++17. The constraints on std::string
  9934. // implementations in C++11 and above make assumption behind the const_cast
  9935. // fairly safe.
  9936. const int captured_fd = ::mkstemp(const_cast<char*>(name_template.data()));
  9937. if (captured_fd == -1) {
  9938. GTEST_LOG_(WARNING)
  9939. << "Failed to create tmp file " << name_template
  9940. << " for test; does the test have access to the /tmp directory?";
  9941. }
  9942. filename_ = std::move(name_template);
  9943. # endif // GTEST_OS_WINDOWS
  9944. fflush(nullptr);
  9945. dup2(captured_fd, fd_);
  9946. close(captured_fd);
  9947. }
  9948. ~CapturedStream() {
  9949. remove(filename_.c_str());
  9950. }
  9951. std::string GetCapturedString() {
  9952. if (uncaptured_fd_ != -1) {
  9953. // Restores the original stream.
  9954. fflush(nullptr);
  9955. dup2(uncaptured_fd_, fd_);
  9956. close(uncaptured_fd_);
  9957. uncaptured_fd_ = -1;
  9958. }
  9959. FILE* const file = posix::FOpen(filename_.c_str(), "r");
  9960. if (file == nullptr) {
  9961. GTEST_LOG_(FATAL) << "Failed to open tmp file " << filename_
  9962. << " for capturing stream.";
  9963. }
  9964. const std::string content = ReadEntireFile(file);
  9965. posix::FClose(file);
  9966. return content;
  9967. }
  9968. private:
  9969. const int fd_; // A stream to capture.
  9970. int uncaptured_fd_;
  9971. // Name of the temporary file holding the stderr output.
  9972. ::std::string filename_;
  9973. GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
  9974. };
  9975. GTEST_DISABLE_MSC_DEPRECATED_POP_()
  9976. static CapturedStream* g_captured_stderr = nullptr;
  9977. static CapturedStream* g_captured_stdout = nullptr;
  9978. // Starts capturing an output stream (stdout/stderr).
  9979. static void CaptureStream(int fd, const char* stream_name,
  9980. CapturedStream** stream) {
  9981. if (*stream != nullptr) {
  9982. GTEST_LOG_(FATAL) << "Only one " << stream_name
  9983. << " capturer can exist at a time.";
  9984. }
  9985. *stream = new CapturedStream(fd);
  9986. }
  9987. // Stops capturing the output stream and returns the captured string.
  9988. static std::string GetCapturedStream(CapturedStream** captured_stream) {
  9989. const std::string content = (*captured_stream)->GetCapturedString();
  9990. delete *captured_stream;
  9991. *captured_stream = nullptr;
  9992. return content;
  9993. }
  9994. // Starts capturing stdout.
  9995. void CaptureStdout() {
  9996. CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
  9997. }
  9998. // Starts capturing stderr.
  9999. void CaptureStderr() {
  10000. CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
  10001. }
  10002. // Stops capturing stdout and returns the captured string.
  10003. std::string GetCapturedStdout() {
  10004. return GetCapturedStream(&g_captured_stdout);
  10005. }
  10006. // Stops capturing stderr and returns the captured string.
  10007. std::string GetCapturedStderr() {
  10008. return GetCapturedStream(&g_captured_stderr);
  10009. }
  10010. #endif // GTEST_HAS_STREAM_REDIRECTION
  10011. size_t GetFileSize(FILE* file) {
  10012. fseek(file, 0, SEEK_END);
  10013. return static_cast<size_t>(ftell(file));
  10014. }
  10015. std::string ReadEntireFile(FILE* file) {
  10016. const size_t file_size = GetFileSize(file);
  10017. char* const buffer = new char[file_size];
  10018. size_t bytes_last_read = 0; // # of bytes read in the last fread()
  10019. size_t bytes_read = 0; // # of bytes read so far
  10020. fseek(file, 0, SEEK_SET);
  10021. // Keeps reading the file until we cannot read further or the
  10022. // pre-determined file size is reached.
  10023. do {
  10024. bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
  10025. bytes_read += bytes_last_read;
  10026. } while (bytes_last_read > 0 && bytes_read < file_size);
  10027. const std::string content(buffer, bytes_read);
  10028. delete[] buffer;
  10029. return content;
  10030. }
  10031. #if GTEST_HAS_DEATH_TEST
  10032. static const std::vector<std::string>* g_injected_test_argvs =
  10033. nullptr; // Owned.
  10034. std::vector<std::string> GetInjectableArgvs() {
  10035. if (g_injected_test_argvs != nullptr) {
  10036. return *g_injected_test_argvs;
  10037. }
  10038. return GetArgvs();
  10039. }
  10040. void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
  10041. if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
  10042. g_injected_test_argvs = new_argvs;
  10043. }
  10044. void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
  10045. SetInjectableArgvs(
  10046. new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
  10047. }
  10048. void ClearInjectableArgvs() {
  10049. delete g_injected_test_argvs;
  10050. g_injected_test_argvs = nullptr;
  10051. }
  10052. #endif // GTEST_HAS_DEATH_TEST
  10053. #if GTEST_OS_WINDOWS_MOBILE
  10054. namespace posix {
  10055. void Abort() {
  10056. DebugBreak();
  10057. TerminateProcess(GetCurrentProcess(), 1);
  10058. }
  10059. } // namespace posix
  10060. #endif // GTEST_OS_WINDOWS_MOBILE
  10061. // Returns the name of the environment variable corresponding to the
  10062. // given flag. For example, FlagToEnvVar("foo") will return
  10063. // "GTEST_FOO" in the open-source version.
  10064. static std::string FlagToEnvVar(const char* flag) {
  10065. const std::string full_flag =
  10066. (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
  10067. Message env_var;
  10068. for (size_t i = 0; i != full_flag.length(); i++) {
  10069. env_var << ToUpper(full_flag.c_str()[i]);
  10070. }
  10071. return env_var.GetString();
  10072. }
  10073. // Parses 'str' for a 32-bit signed integer. If successful, writes
  10074. // the result to *value and returns true; otherwise leaves *value
  10075. // unchanged and returns false.
  10076. bool ParseInt32(const Message& src_text, const char* str, int32_t* value) {
  10077. // Parses the environment variable as a decimal integer.
  10078. char* end = nullptr;
  10079. const long long_value = strtol(str, &end, 10); // NOLINT
  10080. // Has strtol() consumed all characters in the string?
  10081. if (*end != '\0') {
  10082. // No - an invalid character was encountered.
  10083. Message msg;
  10084. msg << "WARNING: " << src_text
  10085. << " is expected to be a 32-bit integer, but actually"
  10086. << " has value \"" << str << "\".\n";
  10087. printf("%s", msg.GetString().c_str());
  10088. fflush(stdout);
  10089. return false;
  10090. }
  10091. // Is the parsed value in the range of an int32_t?
  10092. const auto result = static_cast<int32_t>(long_value);
  10093. if (long_value == LONG_MAX || long_value == LONG_MIN ||
  10094. // The parsed value overflows as a long. (strtol() returns
  10095. // LONG_MAX or LONG_MIN when the input overflows.)
  10096. result != long_value
  10097. // The parsed value overflows as an int32_t.
  10098. ) {
  10099. Message msg;
  10100. msg << "WARNING: " << src_text
  10101. << " is expected to be a 32-bit integer, but actually"
  10102. << " has value " << str << ", which overflows.\n";
  10103. printf("%s", msg.GetString().c_str());
  10104. fflush(stdout);
  10105. return false;
  10106. }
  10107. *value = result;
  10108. return true;
  10109. }
  10110. // Reads and returns the Boolean environment variable corresponding to
  10111. // the given flag; if it's not set, returns default_value.
  10112. //
  10113. // The value is considered true if and only if it's not "0".
  10114. bool BoolFromGTestEnv(const char* flag, bool default_value) {
  10115. #if defined(GTEST_GET_BOOL_FROM_ENV_)
  10116. return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
  10117. #else
  10118. const std::string env_var = FlagToEnvVar(flag);
  10119. const char* const string_value = posix::GetEnv(env_var.c_str());
  10120. return string_value == nullptr ? default_value
  10121. : strcmp(string_value, "0") != 0;
  10122. #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
  10123. }
  10124. // Reads and returns a 32-bit integer stored in the environment
  10125. // variable corresponding to the given flag; if it isn't set or
  10126. // doesn't represent a valid 32-bit integer, returns default_value.
  10127. int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {
  10128. #if defined(GTEST_GET_INT32_FROM_ENV_)
  10129. return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
  10130. #else
  10131. const std::string env_var = FlagToEnvVar(flag);
  10132. const char* const string_value = posix::GetEnv(env_var.c_str());
  10133. if (string_value == nullptr) {
  10134. // The environment variable is not set.
  10135. return default_value;
  10136. }
  10137. int32_t result = default_value;
  10138. if (!ParseInt32(Message() << "Environment variable " << env_var,
  10139. string_value, &result)) {
  10140. printf("The default value %s is used.\n",
  10141. (Message() << default_value).GetString().c_str());
  10142. fflush(stdout);
  10143. return default_value;
  10144. }
  10145. return result;
  10146. #endif // defined(GTEST_GET_INT32_FROM_ENV_)
  10147. }
  10148. // As a special case for the 'output' flag, if GTEST_OUTPUT is not
  10149. // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
  10150. // system. The value of XML_OUTPUT_FILE is a filename without the
  10151. // "xml:" prefix of GTEST_OUTPUT.
  10152. // Note that this is meant to be called at the call site so it does
  10153. // not check that the flag is 'output'
  10154. // In essence this checks an env variable called XML_OUTPUT_FILE
  10155. // and if it is set we prepend "xml:" to its value, if it not set we return ""
  10156. std::string OutputFlagAlsoCheckEnvVar(){
  10157. std::string default_value_for_output_flag = "";
  10158. const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
  10159. if (nullptr != xml_output_file_env) {
  10160. default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
  10161. }
  10162. return default_value_for_output_flag;
  10163. }
  10164. // Reads and returns the string environment variable corresponding to
  10165. // the given flag; if it's not set, returns default_value.
  10166. const char* StringFromGTestEnv(const char* flag, const char* default_value) {
  10167. #if defined(GTEST_GET_STRING_FROM_ENV_)
  10168. return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
  10169. #else
  10170. const std::string env_var = FlagToEnvVar(flag);
  10171. const char* const value = posix::GetEnv(env_var.c_str());
  10172. return value == nullptr ? default_value : value;
  10173. #endif // defined(GTEST_GET_STRING_FROM_ENV_)
  10174. }
  10175. } // namespace internal
  10176. } // namespace testing
  10177. // Copyright 2007, Google Inc.
  10178. // All rights reserved.
  10179. //
  10180. // Redistribution and use in source and binary forms, with or without
  10181. // modification, are permitted provided that the following conditions are
  10182. // met:
  10183. //
  10184. // * Redistributions of source code must retain the above copyright
  10185. // notice, this list of conditions and the following disclaimer.
  10186. // * Redistributions in binary form must reproduce the above
  10187. // copyright notice, this list of conditions and the following disclaimer
  10188. // in the documentation and/or other materials provided with the
  10189. // distribution.
  10190. // * Neither the name of Google Inc. nor the names of its
  10191. // contributors may be used to endorse or promote products derived from
  10192. // this software without specific prior written permission.
  10193. //
  10194. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  10195. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  10196. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  10197. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  10198. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10199. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  10200. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10201. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10202. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  10203. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  10204. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  10205. // Google Test - The Google C++ Testing and Mocking Framework
  10206. //
  10207. // This file implements a universal value printer that can print a
  10208. // value of any type T:
  10209. //
  10210. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  10211. //
  10212. // It uses the << operator when possible, and prints the bytes in the
  10213. // object otherwise. A user can override its behavior for a class
  10214. // type Foo by defining either operator<<(::std::ostream&, const Foo&)
  10215. // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
  10216. // defines Foo.
  10217. #include <stdio.h>
  10218. #include <cctype>
  10219. #include <cstdint>
  10220. #include <cwchar>
  10221. #include <ostream> // NOLINT
  10222. #include <string>
  10223. #include <type_traits>
  10224. namespace testing {
  10225. namespace {
  10226. using ::std::ostream;
  10227. // Prints a segment of bytes in the given object.
  10228. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  10229. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  10230. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  10231. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  10232. void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
  10233. size_t count, ostream* os) {
  10234. char text[5] = "";
  10235. for (size_t i = 0; i != count; i++) {
  10236. const size_t j = start + i;
  10237. if (i != 0) {
  10238. // Organizes the bytes into groups of 2 for easy parsing by
  10239. // human.
  10240. if ((j % 2) == 0)
  10241. *os << ' ';
  10242. else
  10243. *os << '-';
  10244. }
  10245. GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
  10246. *os << text;
  10247. }
  10248. }
  10249. // Prints the bytes in the given value to the given ostream.
  10250. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
  10251. ostream* os) {
  10252. // Tells the user how big the object is.
  10253. *os << count << "-byte object <";
  10254. const size_t kThreshold = 132;
  10255. const size_t kChunkSize = 64;
  10256. // If the object size is bigger than kThreshold, we'll have to omit
  10257. // some details by printing only the first and the last kChunkSize
  10258. // bytes.
  10259. if (count < kThreshold) {
  10260. PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
  10261. } else {
  10262. PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
  10263. *os << " ... ";
  10264. // Rounds up to 2-byte boundary.
  10265. const size_t resume_pos = (count - kChunkSize + 1)/2*2;
  10266. PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
  10267. }
  10268. *os << ">";
  10269. }
  10270. // Helpers for widening a character to char32_t. Since the standard does not
  10271. // specify if char / wchar_t is signed or unsigned, it is important to first
  10272. // convert it to the unsigned type of the same width before widening it to
  10273. // char32_t.
  10274. template <typename CharType>
  10275. char32_t ToChar32(CharType in) {
  10276. return static_cast<char32_t>(
  10277. static_cast<typename std::make_unsigned<CharType>::type>(in));
  10278. }
  10279. } // namespace
  10280. namespace internal {
  10281. // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
  10282. // given object. The delegation simplifies the implementation, which
  10283. // uses the << operator and thus is easier done outside of the
  10284. // ::testing::internal namespace, which contains a << operator that
  10285. // sometimes conflicts with the one in STL.
  10286. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
  10287. ostream* os) {
  10288. PrintBytesInObjectToImpl(obj_bytes, count, os);
  10289. }
  10290. // Depending on the value of a char (or wchar_t), we print it in one
  10291. // of three formats:
  10292. // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
  10293. // - as a hexadecimal escape sequence (e.g. '\x7F'), or
  10294. // - as a special escape sequence (e.g. '\r', '\n').
  10295. enum CharFormat {
  10296. kAsIs,
  10297. kHexEscape,
  10298. kSpecialEscape
  10299. };
  10300. // Returns true if c is a printable ASCII character. We test the
  10301. // value of c directly instead of calling isprint(), which is buggy on
  10302. // Windows Mobile.
  10303. inline bool IsPrintableAscii(char32_t c) { return 0x20 <= c && c <= 0x7E; }
  10304. // Prints c (of type char, char8_t, char16_t, char32_t, or wchar_t) as a
  10305. // character literal without the quotes, escaping it when necessary; returns how
  10306. // c was formatted.
  10307. template <typename Char>
  10308. static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
  10309. const char32_t u_c = ToChar32(c);
  10310. switch (u_c) {
  10311. case L'\0':
  10312. *os << "\\0";
  10313. break;
  10314. case L'\'':
  10315. *os << "\\'";
  10316. break;
  10317. case L'\\':
  10318. *os << "\\\\";
  10319. break;
  10320. case L'\a':
  10321. *os << "\\a";
  10322. break;
  10323. case L'\b':
  10324. *os << "\\b";
  10325. break;
  10326. case L'\f':
  10327. *os << "\\f";
  10328. break;
  10329. case L'\n':
  10330. *os << "\\n";
  10331. break;
  10332. case L'\r':
  10333. *os << "\\r";
  10334. break;
  10335. case L'\t':
  10336. *os << "\\t";
  10337. break;
  10338. case L'\v':
  10339. *os << "\\v";
  10340. break;
  10341. default:
  10342. if (IsPrintableAscii(u_c)) {
  10343. *os << static_cast<char>(c);
  10344. return kAsIs;
  10345. } else {
  10346. ostream::fmtflags flags = os->flags();
  10347. *os << "\\x" << std::hex << std::uppercase << static_cast<int>(u_c);
  10348. os->flags(flags);
  10349. return kHexEscape;
  10350. }
  10351. }
  10352. return kSpecialEscape;
  10353. }
  10354. // Prints a char32_t c as if it's part of a string literal, escaping it when
  10355. // necessary; returns how c was formatted.
  10356. static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {
  10357. switch (c) {
  10358. case L'\'':
  10359. *os << "'";
  10360. return kAsIs;
  10361. case L'"':
  10362. *os << "\\\"";
  10363. return kSpecialEscape;
  10364. default:
  10365. return PrintAsCharLiteralTo(c, os);
  10366. }
  10367. }
  10368. static const char* GetCharWidthPrefix(char) {
  10369. return "";
  10370. }
  10371. static const char* GetCharWidthPrefix(signed char) {
  10372. return "";
  10373. }
  10374. static const char* GetCharWidthPrefix(unsigned char) {
  10375. return "";
  10376. }
  10377. #ifdef __cpp_char8_t
  10378. static const char* GetCharWidthPrefix(char8_t) {
  10379. return "u8";
  10380. }
  10381. #endif
  10382. static const char* GetCharWidthPrefix(char16_t) {
  10383. return "u";
  10384. }
  10385. static const char* GetCharWidthPrefix(char32_t) {
  10386. return "U";
  10387. }
  10388. static const char* GetCharWidthPrefix(wchar_t) {
  10389. return "L";
  10390. }
  10391. // Prints a char c as if it's part of a string literal, escaping it when
  10392. // necessary; returns how c was formatted.
  10393. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
  10394. return PrintAsStringLiteralTo(ToChar32(c), os);
  10395. }
  10396. #ifdef __cpp_char8_t
  10397. static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {
  10398. return PrintAsStringLiteralTo(ToChar32(c), os);
  10399. }
  10400. #endif
  10401. static CharFormat PrintAsStringLiteralTo(char16_t c, ostream* os) {
  10402. return PrintAsStringLiteralTo(ToChar32(c), os);
  10403. }
  10404. static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
  10405. return PrintAsStringLiteralTo(ToChar32(c), os);
  10406. }
  10407. // Prints a character c (of type char, char8_t, char16_t, char32_t, or wchar_t)
  10408. // and its code. '\0' is printed as "'\\0'", other unprintable characters are
  10409. // also properly escaped using the standard C++ escape sequence.
  10410. template <typename Char>
  10411. void PrintCharAndCodeTo(Char c, ostream* os) {
  10412. // First, print c as a literal in the most readable form we can find.
  10413. *os << GetCharWidthPrefix(c) << "'";
  10414. const CharFormat format = PrintAsCharLiteralTo(c, os);
  10415. *os << "'";
  10416. // To aid user debugging, we also print c's code in decimal, unless
  10417. // it's 0 (in which case c was printed as '\\0', making the code
  10418. // obvious).
  10419. if (c == 0)
  10420. return;
  10421. *os << " (" << static_cast<int>(c);
  10422. // For more convenience, we print c's code again in hexadecimal,
  10423. // unless c was already printed in the form '\x##' or the code is in
  10424. // [1, 9].
  10425. if (format == kHexEscape || (1 <= c && c <= 9)) {
  10426. // Do nothing.
  10427. } else {
  10428. *os << ", 0x" << String::FormatHexInt(static_cast<int>(c));
  10429. }
  10430. *os << ")";
  10431. }
  10432. void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
  10433. void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
  10434. // Prints a wchar_t as a symbol if it is printable or as its internal
  10435. // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
  10436. void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); }
  10437. // TODO(dcheng): Consider making this delegate to PrintCharAndCodeTo() as well.
  10438. void PrintTo(char32_t c, ::std::ostream* os) {
  10439. *os << std::hex << "U+" << std::uppercase << std::setfill('0') << std::setw(4)
  10440. << static_cast<uint32_t>(c);
  10441. }
  10442. // Prints the given array of characters to the ostream. CharType must be either
  10443. // char, char8_t, char16_t, char32_t, or wchar_t.
  10444. // The array starts at begin, the length is len, it may include '\0' characters
  10445. // and may not be NUL-terminated.
  10446. template <typename CharType>
  10447. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  10448. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  10449. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  10450. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  10451. static CharFormat PrintCharsAsStringTo(
  10452. const CharType* begin, size_t len, ostream* os) {
  10453. const char* const quote_prefix = GetCharWidthPrefix(*begin);
  10454. *os << quote_prefix << "\"";
  10455. bool is_previous_hex = false;
  10456. CharFormat print_format = kAsIs;
  10457. for (size_t index = 0; index < len; ++index) {
  10458. const CharType cur = begin[index];
  10459. if (is_previous_hex && IsXDigit(cur)) {
  10460. // Previous character is of '\x..' form and this character can be
  10461. // interpreted as another hexadecimal digit in its number. Break string to
  10462. // disambiguate.
  10463. *os << "\" " << quote_prefix << "\"";
  10464. }
  10465. is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
  10466. // Remember if any characters required hex escaping.
  10467. if (is_previous_hex) {
  10468. print_format = kHexEscape;
  10469. }
  10470. }
  10471. *os << "\"";
  10472. return print_format;
  10473. }
  10474. // Prints a (const) char/wchar_t array of 'len' elements, starting at address
  10475. // 'begin'. CharType must be either char or wchar_t.
  10476. template <typename CharType>
  10477. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  10478. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  10479. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  10480. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  10481. static void UniversalPrintCharArray(
  10482. const CharType* begin, size_t len, ostream* os) {
  10483. // The code
  10484. // const char kFoo[] = "foo";
  10485. // generates an array of 4, not 3, elements, with the last one being '\0'.
  10486. //
  10487. // Therefore when printing a char array, we don't print the last element if
  10488. // it's '\0', such that the output matches the string literal as it's
  10489. // written in the source code.
  10490. if (len > 0 && begin[len - 1] == '\0') {
  10491. PrintCharsAsStringTo(begin, len - 1, os);
  10492. return;
  10493. }
  10494. // If, however, the last element in the array is not '\0', e.g.
  10495. // const char kFoo[] = { 'f', 'o', 'o' };
  10496. // we must print the entire array. We also print a message to indicate
  10497. // that the array is not NUL-terminated.
  10498. PrintCharsAsStringTo(begin, len, os);
  10499. *os << " (no terminating NUL)";
  10500. }
  10501. // Prints a (const) char array of 'len' elements, starting at address 'begin'.
  10502. void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
  10503. UniversalPrintCharArray(begin, len, os);
  10504. }
  10505. #ifdef __cpp_char8_t
  10506. // Prints a (const) char8_t array of 'len' elements, starting at address
  10507. // 'begin'.
  10508. void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {
  10509. UniversalPrintCharArray(begin, len, os);
  10510. }
  10511. #endif
  10512. // Prints a (const) char16_t array of 'len' elements, starting at address
  10513. // 'begin'.
  10514. void UniversalPrintArray(const char16_t* begin, size_t len, ostream* os) {
  10515. UniversalPrintCharArray(begin, len, os);
  10516. }
  10517. // Prints a (const) char32_t array of 'len' elements, starting at address
  10518. // 'begin'.
  10519. void UniversalPrintArray(const char32_t* begin, size_t len, ostream* os) {
  10520. UniversalPrintCharArray(begin, len, os);
  10521. }
  10522. // Prints a (const) wchar_t array of 'len' elements, starting at address
  10523. // 'begin'.
  10524. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
  10525. UniversalPrintCharArray(begin, len, os);
  10526. }
  10527. namespace {
  10528. // Prints a null-terminated C-style string to the ostream.
  10529. template <typename Char>
  10530. void PrintCStringTo(const Char* s, ostream* os) {
  10531. if (s == nullptr) {
  10532. *os << "NULL";
  10533. } else {
  10534. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  10535. PrintCharsAsStringTo(s, std::char_traits<Char>::length(s), os);
  10536. }
  10537. }
  10538. } // anonymous namespace
  10539. void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }
  10540. #ifdef __cpp_char8_t
  10541. void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }
  10542. #endif
  10543. void PrintTo(const char16_t* s, ostream* os) { PrintCStringTo(s, os); }
  10544. void PrintTo(const char32_t* s, ostream* os) { PrintCStringTo(s, os); }
  10545. // MSVC compiler can be configured to define whar_t as a typedef
  10546. // of unsigned short. Defining an overload for const wchar_t* in that case
  10547. // would cause pointers to unsigned shorts be printed as wide strings,
  10548. // possibly accessing more memory than intended and causing invalid
  10549. // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
  10550. // wchar_t is implemented as a native type.
  10551. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  10552. // Prints the given wide C string to the ostream.
  10553. void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }
  10554. #endif // wchar_t is native
  10555. namespace {
  10556. bool ContainsUnprintableControlCodes(const char* str, size_t length) {
  10557. const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
  10558. for (size_t i = 0; i < length; i++) {
  10559. unsigned char ch = *s++;
  10560. if (std::iscntrl(ch)) {
  10561. switch (ch) {
  10562. case '\t':
  10563. case '\n':
  10564. case '\r':
  10565. break;
  10566. default:
  10567. return true;
  10568. }
  10569. }
  10570. }
  10571. return false;
  10572. }
  10573. bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
  10574. bool IsValidUTF8(const char* str, size_t length) {
  10575. const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
  10576. for (size_t i = 0; i < length;) {
  10577. unsigned char lead = s[i++];
  10578. if (lead <= 0x7f) {
  10579. continue; // single-byte character (ASCII) 0..7F
  10580. }
  10581. if (lead < 0xc2) {
  10582. return false; // trail byte or non-shortest form
  10583. } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
  10584. ++i; // 2-byte character
  10585. } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
  10586. IsUTF8TrailByte(s[i]) &&
  10587. IsUTF8TrailByte(s[i + 1]) &&
  10588. // check for non-shortest form and surrogate
  10589. (lead != 0xe0 || s[i] >= 0xa0) &&
  10590. (lead != 0xed || s[i] < 0xa0)) {
  10591. i += 2; // 3-byte character
  10592. } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
  10593. IsUTF8TrailByte(s[i]) &&
  10594. IsUTF8TrailByte(s[i + 1]) &&
  10595. IsUTF8TrailByte(s[i + 2]) &&
  10596. // check for non-shortest form
  10597. (lead != 0xf0 || s[i] >= 0x90) &&
  10598. (lead != 0xf4 || s[i] < 0x90)) {
  10599. i += 3; // 4-byte character
  10600. } else {
  10601. return false;
  10602. }
  10603. }
  10604. return true;
  10605. }
  10606. void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
  10607. if (!ContainsUnprintableControlCodes(str, length) &&
  10608. IsValidUTF8(str, length)) {
  10609. *os << "\n As Text: \"" << str << "\"";
  10610. }
  10611. }
  10612. } // anonymous namespace
  10613. void PrintStringTo(const ::std::string& s, ostream* os) {
  10614. if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
  10615. if (GTEST_FLAG(print_utf8)) {
  10616. ConditionalPrintAsText(s.data(), s.size(), os);
  10617. }
  10618. }
  10619. }
  10620. #ifdef __cpp_char8_t
  10621. void PrintU8StringTo(const ::std::u8string& s, ostream* os) {
  10622. PrintCharsAsStringTo(s.data(), s.size(), os);
  10623. }
  10624. #endif
  10625. void PrintU16StringTo(const ::std::u16string& s, ostream* os) {
  10626. PrintCharsAsStringTo(s.data(), s.size(), os);
  10627. }
  10628. void PrintU32StringTo(const ::std::u32string& s, ostream* os) {
  10629. PrintCharsAsStringTo(s.data(), s.size(), os);
  10630. }
  10631. #if GTEST_HAS_STD_WSTRING
  10632. void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
  10633. PrintCharsAsStringTo(s.data(), s.size(), os);
  10634. }
  10635. #endif // GTEST_HAS_STD_WSTRING
  10636. } // namespace internal
  10637. } // namespace testing
  10638. // Copyright 2008, Google Inc.
  10639. // All rights reserved.
  10640. //
  10641. // Redistribution and use in source and binary forms, with or without
  10642. // modification, are permitted provided that the following conditions are
  10643. // met:
  10644. //
  10645. // * Redistributions of source code must retain the above copyright
  10646. // notice, this list of conditions and the following disclaimer.
  10647. // * Redistributions in binary form must reproduce the above
  10648. // copyright notice, this list of conditions and the following disclaimer
  10649. // in the documentation and/or other materials provided with the
  10650. // distribution.
  10651. // * Neither the name of Google Inc. nor the names of its
  10652. // contributors may be used to endorse or promote products derived from
  10653. // this software without specific prior written permission.
  10654. //
  10655. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  10656. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  10657. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  10658. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  10659. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10660. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  10661. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10662. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10663. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  10664. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  10665. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  10666. //
  10667. // The Google C++ Testing and Mocking Framework (Google Test)
  10668. namespace testing {
  10669. using internal::GetUnitTestImpl;
  10670. // Gets the summary of the failure message by omitting the stack trace
  10671. // in it.
  10672. std::string TestPartResult::ExtractSummary(const char* message) {
  10673. const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
  10674. return stack_trace == nullptr ? message : std::string(message, stack_trace);
  10675. }
  10676. // Prints a TestPartResult object.
  10677. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
  10678. return os << internal::FormatFileLocation(result.file_name(),
  10679. result.line_number())
  10680. << " "
  10681. << (result.type() == TestPartResult::kSuccess
  10682. ? "Success"
  10683. : result.type() == TestPartResult::kSkip
  10684. ? "Skipped"
  10685. : result.type() == TestPartResult::kFatalFailure
  10686. ? "Fatal failure"
  10687. : "Non-fatal failure")
  10688. << ":\n"
  10689. << result.message() << std::endl;
  10690. }
  10691. // Appends a TestPartResult to the array.
  10692. void TestPartResultArray::Append(const TestPartResult& result) {
  10693. array_.push_back(result);
  10694. }
  10695. // Returns the TestPartResult at the given index (0-based).
  10696. const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
  10697. if (index < 0 || index >= size()) {
  10698. printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
  10699. internal::posix::Abort();
  10700. }
  10701. return array_[static_cast<size_t>(index)];
  10702. }
  10703. // Returns the number of TestPartResult objects in the array.
  10704. int TestPartResultArray::size() const {
  10705. return static_cast<int>(array_.size());
  10706. }
  10707. namespace internal {
  10708. HasNewFatalFailureHelper::HasNewFatalFailureHelper()
  10709. : has_new_fatal_failure_(false),
  10710. original_reporter_(GetUnitTestImpl()->
  10711. GetTestPartResultReporterForCurrentThread()) {
  10712. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
  10713. }
  10714. HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
  10715. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
  10716. original_reporter_);
  10717. }
  10718. void HasNewFatalFailureHelper::ReportTestPartResult(
  10719. const TestPartResult& result) {
  10720. if (result.fatally_failed())
  10721. has_new_fatal_failure_ = true;
  10722. original_reporter_->ReportTestPartResult(result);
  10723. }
  10724. } // namespace internal
  10725. } // namespace testing
  10726. // Copyright 2023 Google Inc.
  10727. // All Rights Reserved.
  10728. //
  10729. // Redistribution and use in source and binary forms, with or without
  10730. // modification, are permitted provided that the following conditions are
  10731. // met:
  10732. //
  10733. // * Redistributions of source code must retain the above copyright
  10734. // notice, this list of conditions and the following disclaimer.
  10735. // * Redistributions in binary form must reproduce the above
  10736. // copyright notice, this list of conditions and the following disclaimer
  10737. // in the documentation and/or other materials provided with the
  10738. // distribution.
  10739. // * Neither the name of Google Inc. nor the names of its
  10740. // contributors may be used to endorse or promote products derived from
  10741. // this software without specific prior written permission.
  10742. //
  10743. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  10744. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  10745. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  10746. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  10747. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10748. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  10749. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10750. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10751. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  10752. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  10753. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  10754. namespace testing {
  10755. namespace internal {
  10756. // Skips to the first non-space char in str. Returns an empty string if str
  10757. // contains only whitespace characters.
  10758. static const char* SkipSpaces(const char* str) {
  10759. while (IsSpace(*str))
  10760. str++;
  10761. return str;
  10762. }
  10763. static std::vector<std::string> SplitIntoTestNames(const char* src) {
  10764. std::vector<std::string> name_vec;
  10765. src = SkipSpaces(src);
  10766. for (; src != nullptr; src = SkipComma(src)) {
  10767. name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
  10768. }
  10769. return name_vec;
  10770. }
  10771. // Verifies that registered_tests match the test names in
  10772. // registered_tests_; returns registered_tests if successful, or
  10773. // aborts the program otherwise.
  10774. const char* TypedTestSuitePState::VerifyRegisteredTestNames(
  10775. const char* test_suite_name, const char* file, int line,
  10776. const char* registered_tests) {
  10777. RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line));
  10778. typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
  10779. registered_ = true;
  10780. std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
  10781. Message errors;
  10782. std::set<std::string> tests;
  10783. for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
  10784. name_it != name_vec.end(); ++name_it) {
  10785. const std::string& name = *name_it;
  10786. if (tests.count(name) != 0) {
  10787. errors << "Test " << name << " is listed more than once.\n";
  10788. continue;
  10789. }
  10790. if (registered_tests_.count(name) != 0) {
  10791. tests.insert(name);
  10792. } else {
  10793. errors << "No test named " << name
  10794. << " can be found in this test suite.\n";
  10795. }
  10796. }
  10797. for (RegisteredTestIter it = registered_tests_.begin();
  10798. it != registered_tests_.end();
  10799. ++it) {
  10800. if (tests.count(it->first) == 0) {
  10801. errors << "You forgot to list test " << it->first << ".\n";
  10802. }
  10803. }
  10804. const std::string& errors_str = errors.GetString();
  10805. if (errors_str != "") {
  10806. fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
  10807. errors_str.c_str());
  10808. fflush(stderr);
  10809. posix::Abort();
  10810. }
  10811. return registered_tests;
  10812. }
  10813. } // namespace internal
  10814. } // namespace testing
  10815. // Copyright 2008, Google Inc.
  10816. // All rights reserved.
  10817. //
  10818. // Redistribution and use in source and binary forms, with or without
  10819. // modification, are permitted provided that the following conditions are
  10820. // met:
  10821. //
  10822. // * Redistributions of source code must retain the above copyright
  10823. // notice, this list of conditions and the following disclaimer.
  10824. // * Redistributions in binary form must reproduce the above
  10825. // copyright notice, this list of conditions and the following disclaimer
  10826. // in the documentation and/or other materials provided with the
  10827. // distribution.
  10828. // * Neither the name of Google Inc. nor the names of its
  10829. // contributors may be used to endorse or promote products derived from
  10830. // this software without specific prior written permission.
  10831. //
  10832. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  10833. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  10834. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  10835. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  10836. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10837. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  10838. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10839. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10840. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  10841. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  10842. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  10843. //
  10844. // Google C++ Mocking Framework (Google Mock)
  10845. //
  10846. // This file #includes all Google Mock implementation .cc files. The
  10847. // purpose is to allow a user to build Google Mock by compiling this
  10848. // file alone.
  10849. // This line ensures that gmock.h can be compiled on its own, even
  10850. // when it's fused.
  10851. #include "gmock/gmock.h"
  10852. // The following lines pull in the real gmock *.cc files.
  10853. // Copyright 2007, Google Inc.
  10854. // All rights reserved.
  10855. //
  10856. // Redistribution and use in source and binary forms, with or without
  10857. // modification, are permitted provided that the following conditions are
  10858. // met:
  10859. //
  10860. // * Redistributions of source code must retain the above copyright
  10861. // notice, this list of conditions and the following disclaimer.
  10862. // * Redistributions in binary form must reproduce the above
  10863. // copyright notice, this list of conditions and the following disclaimer
  10864. // in the documentation and/or other materials provided with the
  10865. // distribution.
  10866. // * Neither the name of Google Inc. nor the names of its
  10867. // contributors may be used to endorse or promote products derived from
  10868. // this software without specific prior written permission.
  10869. //
  10870. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  10871. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  10872. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  10873. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  10874. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10875. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  10876. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10877. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10878. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  10879. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  10880. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  10881. // Google Mock - a framework for writing C++ mock classes.
  10882. //
  10883. // This file implements cardinalities.
  10884. #include <limits.h>
  10885. #include <ostream> // NOLINT
  10886. #include <sstream>
  10887. #include <string>
  10888. namespace testing {
  10889. namespace {
  10890. // Implements the Between(m, n) cardinality.
  10891. class BetweenCardinalityImpl : public CardinalityInterface {
  10892. public:
  10893. BetweenCardinalityImpl(int min, int max)
  10894. : min_(min >= 0 ? min : 0),
  10895. max_(max >= min_ ? max : min_) {
  10896. std::stringstream ss;
  10897. if (min < 0) {
  10898. ss << "The invocation lower bound must be >= 0, "
  10899. << "but is actually " << min << ".";
  10900. internal::Expect(false, __FILE__, __LINE__, ss.str());
  10901. } else if (max < 0) {
  10902. ss << "The invocation upper bound must be >= 0, "
  10903. << "but is actually " << max << ".";
  10904. internal::Expect(false, __FILE__, __LINE__, ss.str());
  10905. } else if (min > max) {
  10906. ss << "The invocation upper bound (" << max
  10907. << ") must be >= the invocation lower bound (" << min
  10908. << ").";
  10909. internal::Expect(false, __FILE__, __LINE__, ss.str());
  10910. }
  10911. }
  10912. // Conservative estimate on the lower/upper bound of the number of
  10913. // calls allowed.
  10914. int ConservativeLowerBound() const override { return min_; }
  10915. int ConservativeUpperBound() const override { return max_; }
  10916. bool IsSatisfiedByCallCount(int call_count) const override {
  10917. return min_ <= call_count && call_count <= max_;
  10918. }
  10919. bool IsSaturatedByCallCount(int call_count) const override {
  10920. return call_count >= max_;
  10921. }
  10922. void DescribeTo(::std::ostream* os) const override;
  10923. private:
  10924. const int min_;
  10925. const int max_;
  10926. GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
  10927. };
  10928. // Formats "n times" in a human-friendly way.
  10929. inline std::string FormatTimes(int n) {
  10930. if (n == 1) {
  10931. return "once";
  10932. } else if (n == 2) {
  10933. return "twice";
  10934. } else {
  10935. std::stringstream ss;
  10936. ss << n << " times";
  10937. return ss.str();
  10938. }
  10939. }
  10940. // Describes the Between(m, n) cardinality in human-friendly text.
  10941. void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
  10942. if (min_ == 0) {
  10943. if (max_ == 0) {
  10944. *os << "never called";
  10945. } else if (max_ == INT_MAX) {
  10946. *os << "called any number of times";
  10947. } else {
  10948. *os << "called at most " << FormatTimes(max_);
  10949. }
  10950. } else if (min_ == max_) {
  10951. *os << "called " << FormatTimes(min_);
  10952. } else if (max_ == INT_MAX) {
  10953. *os << "called at least " << FormatTimes(min_);
  10954. } else {
  10955. // 0 < min_ < max_ < INT_MAX
  10956. *os << "called between " << min_ << " and " << max_ << " times";
  10957. }
  10958. }
  10959. } // Unnamed namespace
  10960. // Describes the given call count to an ostream.
  10961. void Cardinality::DescribeActualCallCountTo(int actual_call_count,
  10962. ::std::ostream* os) {
  10963. if (actual_call_count > 0) {
  10964. *os << "called " << FormatTimes(actual_call_count);
  10965. } else {
  10966. *os << "never called";
  10967. }
  10968. }
  10969. // Creates a cardinality that allows at least n calls.
  10970. GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
  10971. // Creates a cardinality that allows at most n calls.
  10972. GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
  10973. // Creates a cardinality that allows any number of calls.
  10974. GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }
  10975. // Creates a cardinality that allows between min and max calls.
  10976. GTEST_API_ Cardinality Between(int min, int max) {
  10977. return Cardinality(new BetweenCardinalityImpl(min, max));
  10978. }
  10979. // Creates a cardinality that allows exactly n calls.
  10980. GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
  10981. } // namespace testing
  10982. // Copyright 2007, Google Inc.
  10983. // All rights reserved.
  10984. //
  10985. // Redistribution and use in source and binary forms, with or without
  10986. // modification, are permitted provided that the following conditions are
  10987. // met:
  10988. //
  10989. // * Redistributions of source code must retain the above copyright
  10990. // notice, this list of conditions and the following disclaimer.
  10991. // * Redistributions in binary form must reproduce the above
  10992. // copyright notice, this list of conditions and the following disclaimer
  10993. // in the documentation and/or other materials provided with the
  10994. // distribution.
  10995. // * Neither the name of Google Inc. nor the names of its
  10996. // contributors may be used to endorse or promote products derived from
  10997. // this software without specific prior written permission.
  10998. //
  10999. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  11000. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  11001. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  11002. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  11003. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  11004. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  11005. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  11006. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11007. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  11008. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  11009. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  11010. // Google Mock - a framework for writing C++ mock classes.
  11011. //
  11012. // This file defines some utilities useful for implementing Google
  11013. // Mock. They are subject to change without notice, so please DO NOT
  11014. // USE THEM IN USER CODE.
  11015. #include <ctype.h>
  11016. #include <ostream> // NOLINT
  11017. #include <string>
  11018. namespace testing {
  11019. namespace internal {
  11020. // Joins a vector of strings as if they are fields of a tuple; returns
  11021. // the joined string.
  11022. GTEST_API_ std::string JoinAsTuple(const Strings& fields) {
  11023. switch (fields.size()) {
  11024. case 0:
  11025. return "";
  11026. case 1:
  11027. return fields[0];
  11028. default:
  11029. std::string result = "(" + fields[0];
  11030. for (size_t i = 1; i < fields.size(); i++) {
  11031. result += ", ";
  11032. result += fields[i];
  11033. }
  11034. result += ")";
  11035. return result;
  11036. }
  11037. }
  11038. // Converts an identifier name to a space-separated list of lower-case
  11039. // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
  11040. // treated as one word. For example, both "FooBar123" and
  11041. // "foo_bar_123" are converted to "foo bar 123".
  11042. GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
  11043. std::string result;
  11044. char prev_char = '\0';
  11045. for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
  11046. // We don't care about the current locale as the input is
  11047. // guaranteed to be a valid C++ identifier name.
  11048. const bool starts_new_word = IsUpper(*p) ||
  11049. (!IsAlpha(prev_char) && IsLower(*p)) ||
  11050. (!IsDigit(prev_char) && IsDigit(*p));
  11051. if (IsAlNum(*p)) {
  11052. if (starts_new_word && result != "")
  11053. result += ' ';
  11054. result += ToLower(*p);
  11055. }
  11056. }
  11057. return result;
  11058. }
  11059. // This class reports Google Mock failures as Google Test failures. A
  11060. // user can define another class in a similar fashion if they intend to
  11061. // use Google Mock with a testing framework other than Google Test.
  11062. class GoogleTestFailureReporter : public FailureReporterInterface {
  11063. public:
  11064. void ReportFailure(FailureType type, const char* file, int line,
  11065. const std::string& message) override {
  11066. AssertHelper(type == kFatal ?
  11067. TestPartResult::kFatalFailure :
  11068. TestPartResult::kNonFatalFailure,
  11069. file,
  11070. line,
  11071. message.c_str()) = Message();
  11072. if (type == kFatal) {
  11073. posix::Abort();
  11074. }
  11075. }
  11076. };
  11077. // Returns the global failure reporter. Will create a
  11078. // GoogleTestFailureReporter and return it the first time called.
  11079. GTEST_API_ FailureReporterInterface* GetFailureReporter() {
  11080. // Points to the global failure reporter used by Google Mock. gcc
  11081. // guarantees that the following use of failure_reporter is
  11082. // thread-safe. We may need to add additional synchronization to
  11083. // protect failure_reporter if we port Google Mock to other
  11084. // compilers.
  11085. static FailureReporterInterface* const failure_reporter =
  11086. new GoogleTestFailureReporter();
  11087. return failure_reporter;
  11088. }
  11089. // Protects global resources (stdout in particular) used by Log().
  11090. static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
  11091. // Returns true if and only if a log with the given severity is visible
  11092. // according to the --gmock_verbose flag.
  11093. GTEST_API_ bool LogIsVisible(LogSeverity severity) {
  11094. if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
  11095. // Always show the log if --gmock_verbose=info.
  11096. return true;
  11097. } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
  11098. // Always hide it if --gmock_verbose=error.
  11099. return false;
  11100. } else {
  11101. // If --gmock_verbose is neither "info" nor "error", we treat it
  11102. // as "warning" (its default value).
  11103. return severity == kWarning;
  11104. }
  11105. }
  11106. // Prints the given message to stdout if and only if 'severity' >= the level
  11107. // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
  11108. // 0, also prints the stack trace excluding the top
  11109. // stack_frames_to_skip frames. In opt mode, any positive
  11110. // stack_frames_to_skip is treated as 0, since we don't know which
  11111. // function calls will be inlined by the compiler and need to be
  11112. // conservative.
  11113. GTEST_API_ void Log(LogSeverity severity, const std::string& message,
  11114. int stack_frames_to_skip) {
  11115. if (!LogIsVisible(severity))
  11116. return;
  11117. // Ensures that logs from different threads don't interleave.
  11118. MutexLock l(&g_log_mutex);
  11119. if (severity == kWarning) {
  11120. // Prints a GMOCK WARNING marker to make the warnings easily searchable.
  11121. std::cout << "\nGMOCK WARNING:";
  11122. }
  11123. // Pre-pends a new-line to message if it doesn't start with one.
  11124. if (message.empty() || message[0] != '\n') {
  11125. std::cout << "\n";
  11126. }
  11127. std::cout << message;
  11128. if (stack_frames_to_skip >= 0) {
  11129. #ifdef NDEBUG
  11130. // In opt mode, we have to be conservative and skip no stack frame.
  11131. const int actual_to_skip = 0;
  11132. #else
  11133. // In dbg mode, we can do what the caller tell us to do (plus one
  11134. // for skipping this function's stack frame).
  11135. const int actual_to_skip = stack_frames_to_skip + 1;
  11136. #endif // NDEBUG
  11137. // Appends a new-line to message if it doesn't end with one.
  11138. if (!message.empty() && *message.rbegin() != '\n') {
  11139. std::cout << "\n";
  11140. }
  11141. std::cout << "Stack trace:\n"
  11142. << ::testing::internal::GetCurrentOsStackTraceExceptTop(
  11143. ::testing::UnitTest::GetInstance(), actual_to_skip);
  11144. }
  11145. std::cout << ::std::flush;
  11146. }
  11147. GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
  11148. GTEST_API_ void IllegalDoDefault(const char* file, int line) {
  11149. internal::Assert(
  11150. false, file, line,
  11151. "You are using DoDefault() inside a composite action like "
  11152. "DoAll() or WithArgs(). This is not supported for technical "
  11153. "reasons. Please instead spell out the default action, or "
  11154. "assign the default action to an Action variable and use "
  11155. "the variable in various places.");
  11156. }
  11157. } // namespace internal
  11158. } // namespace testing
  11159. // Copyright 2007, Google Inc.
  11160. // All rights reserved.
  11161. //
  11162. // Redistribution and use in source and binary forms, with or without
  11163. // modification, are permitted provided that the following conditions are
  11164. // met:
  11165. //
  11166. // * Redistributions of source code must retain the above copyright
  11167. // notice, this list of conditions and the following disclaimer.
  11168. // * Redistributions in binary form must reproduce the above
  11169. // copyright notice, this list of conditions and the following disclaimer
  11170. // in the documentation and/or other materials provided with the
  11171. // distribution.
  11172. // * Neither the name of Google Inc. nor the names of its
  11173. // contributors may be used to endorse or promote products derived from
  11174. // this software without specific prior written permission.
  11175. //
  11176. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  11177. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  11178. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  11179. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  11180. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  11181. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  11182. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  11183. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11184. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  11185. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  11186. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  11187. // Google Mock - a framework for writing C++ mock classes.
  11188. //
  11189. // This file implements Matcher<const string&>, Matcher<string>, and
  11190. // utilities for defining matchers.
  11191. #include <string.h>
  11192. #include <iostream>
  11193. #include <sstream>
  11194. #include <string>
  11195. namespace testing {
  11196. namespace internal {
  11197. // Returns the description for a matcher defined using the MATCHER*()
  11198. // macro where the user-supplied description string is "", if
  11199. // 'negation' is false; otherwise returns the description of the
  11200. // negation of the matcher. 'param_values' contains a list of strings
  11201. // that are the print-out of the matcher's parameters.
  11202. GTEST_API_ std::string FormatMatcherDescription(bool negation,
  11203. const char* matcher_name,
  11204. const Strings& param_values) {
  11205. std::string result = ConvertIdentifierNameToWords(matcher_name);
  11206. if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values);
  11207. return negation ? "not (" + result + ")" : result;
  11208. }
  11209. // FindMaxBipartiteMatching and its helper class.
  11210. //
  11211. // Uses the well-known Ford-Fulkerson max flow method to find a maximum
  11212. // bipartite matching. Flow is considered to be from left to right.
  11213. // There is an implicit source node that is connected to all of the left
  11214. // nodes, and an implicit sink node that is connected to all of the
  11215. // right nodes. All edges have unit capacity.
  11216. //
  11217. // Neither the flow graph nor the residual flow graph are represented
  11218. // explicitly. Instead, they are implied by the information in 'graph' and
  11219. // a vector<int> called 'left_' whose elements are initialized to the
  11220. // value kUnused. This represents the initial state of the algorithm,
  11221. // where the flow graph is empty, and the residual flow graph has the
  11222. // following edges:
  11223. // - An edge from source to each left_ node
  11224. // - An edge from each right_ node to sink
  11225. // - An edge from each left_ node to each right_ node, if the
  11226. // corresponding edge exists in 'graph'.
  11227. //
  11228. // When the TryAugment() method adds a flow, it sets left_[l] = r for some
  11229. // nodes l and r. This induces the following changes:
  11230. // - The edges (source, l), (l, r), and (r, sink) are added to the
  11231. // flow graph.
  11232. // - The same three edges are removed from the residual flow graph.
  11233. // - The reverse edges (l, source), (r, l), and (sink, r) are added
  11234. // to the residual flow graph, which is a directional graph
  11235. // representing unused flow capacity.
  11236. //
  11237. // When the method augments a flow (moving left_[l] from some r1 to some
  11238. // other r2), this can be thought of as "undoing" the above steps with
  11239. // respect to r1 and "redoing" them with respect to r2.
  11240. //
  11241. // It bears repeating that the flow graph and residual flow graph are
  11242. // never represented explicitly, but can be derived by looking at the
  11243. // information in 'graph' and in left_.
  11244. //
  11245. // As an optimization, there is a second vector<int> called right_ which
  11246. // does not provide any new information. Instead, it enables more
  11247. // efficient queries about edges entering or leaving the right-side nodes
  11248. // of the flow or residual flow graphs. The following invariants are
  11249. // maintained:
  11250. //
  11251. // left[l] == kUnused or right[left[l]] == l
  11252. // right[r] == kUnused or left[right[r]] == r
  11253. //
  11254. // . [ source ] .
  11255. // . ||| .
  11256. // . ||| .
  11257. // . ||\--> left[0]=1 ---\ right[0]=-1 ----\ .
  11258. // . || | | .
  11259. // . |\---> left[1]=-1 \--> right[1]=0 ---\| .
  11260. // . | || .
  11261. // . \----> left[2]=2 ------> right[2]=2 --\|| .
  11262. // . ||| .
  11263. // . elements matchers vvv .
  11264. // . [ sink ] .
  11265. //
  11266. // See Also:
  11267. // [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
  11268. // "Introduction to Algorithms (Second ed.)", pp. 651-664.
  11269. // [2] "Ford-Fulkerson algorithm", Wikipedia,
  11270. // 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
  11271. class MaxBipartiteMatchState {
  11272. public:
  11273. explicit MaxBipartiteMatchState(const MatchMatrix& graph)
  11274. : graph_(&graph),
  11275. left_(graph_->LhsSize(), kUnused),
  11276. right_(graph_->RhsSize(), kUnused) {}
  11277. // Returns the edges of a maximal match, each in the form {left, right}.
  11278. ElementMatcherPairs Compute() {
  11279. // 'seen' is used for path finding { 0: unseen, 1: seen }.
  11280. ::std::vector<char> seen;
  11281. // Searches the residual flow graph for a path from each left node to
  11282. // the sink in the residual flow graph, and if one is found, add flow
  11283. // to the graph. It's okay to search through the left nodes once. The
  11284. // edge from the implicit source node to each previously-visited left
  11285. // node will have flow if that left node has any path to the sink
  11286. // whatsoever. Subsequent augmentations can only add flow to the
  11287. // network, and cannot take away that previous flow unit from the source.
  11288. // Since the source-to-left edge can only carry one flow unit (or,
  11289. // each element can be matched to only one matcher), there is no need
  11290. // to visit the left nodes more than once looking for augmented paths.
  11291. // The flow is known to be possible or impossible by looking at the
  11292. // node once.
  11293. for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
  11294. // Reset the path-marking vector and try to find a path from
  11295. // source to sink starting at the left_[ilhs] node.
  11296. GTEST_CHECK_(left_[ilhs] == kUnused)
  11297. << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
  11298. // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
  11299. seen.assign(graph_->RhsSize(), 0);
  11300. TryAugment(ilhs, &seen);
  11301. }
  11302. ElementMatcherPairs result;
  11303. for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
  11304. size_t irhs = left_[ilhs];
  11305. if (irhs == kUnused) continue;
  11306. result.push_back(ElementMatcherPair(ilhs, irhs));
  11307. }
  11308. return result;
  11309. }
  11310. private:
  11311. static const size_t kUnused = static_cast<size_t>(-1);
  11312. // Perform a depth-first search from left node ilhs to the sink. If a
  11313. // path is found, flow is added to the network by linking the left and
  11314. // right vector elements corresponding each segment of the path.
  11315. // Returns true if a path to sink was found, which means that a unit of
  11316. // flow was added to the network. The 'seen' vector elements correspond
  11317. // to right nodes and are marked to eliminate cycles from the search.
  11318. //
  11319. // Left nodes will only be explored at most once because they
  11320. // are accessible from at most one right node in the residual flow
  11321. // graph.
  11322. //
  11323. // Note that left_[ilhs] is the only element of left_ that TryAugment will
  11324. // potentially transition from kUnused to another value. Any other
  11325. // left_ element holding kUnused before TryAugment will be holding it
  11326. // when TryAugment returns.
  11327. //
  11328. bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
  11329. for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
  11330. if ((*seen)[irhs]) continue;
  11331. if (!graph_->HasEdge(ilhs, irhs)) continue;
  11332. // There's an available edge from ilhs to irhs.
  11333. (*seen)[irhs] = 1;
  11334. // Next a search is performed to determine whether
  11335. // this edge is a dead end or leads to the sink.
  11336. //
  11337. // right_[irhs] == kUnused means that there is residual flow from
  11338. // right node irhs to the sink, so we can use that to finish this
  11339. // flow path and return success.
  11340. //
  11341. // Otherwise there is residual flow to some ilhs. We push flow
  11342. // along that path and call ourselves recursively to see if this
  11343. // ultimately leads to sink.
  11344. if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
  11345. // Add flow from left_[ilhs] to right_[irhs].
  11346. left_[ilhs] = irhs;
  11347. right_[irhs] = ilhs;
  11348. return true;
  11349. }
  11350. }
  11351. return false;
  11352. }
  11353. const MatchMatrix* graph_; // not owned
  11354. // Each element of the left_ vector represents a left hand side node
  11355. // (i.e. an element) and each element of right_ is a right hand side
  11356. // node (i.e. a matcher). The values in the left_ vector indicate
  11357. // outflow from that node to a node on the right_ side. The values
  11358. // in the right_ indicate inflow, and specify which left_ node is
  11359. // feeding that right_ node, if any. For example, left_[3] == 1 means
  11360. // there's a flow from element #3 to matcher #1. Such a flow would also
  11361. // be redundantly represented in the right_ vector as right_[1] == 3.
  11362. // Elements of left_ and right_ are either kUnused or mutually
  11363. // referent. Mutually referent means that left_[right_[i]] = i and
  11364. // right_[left_[i]] = i.
  11365. ::std::vector<size_t> left_;
  11366. ::std::vector<size_t> right_;
  11367. };
  11368. const size_t MaxBipartiteMatchState::kUnused;
  11369. GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) {
  11370. return MaxBipartiteMatchState(g).Compute();
  11371. }
  11372. static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
  11373. ::std::ostream* stream) {
  11374. typedef ElementMatcherPairs::const_iterator Iter;
  11375. ::std::ostream& os = *stream;
  11376. os << "{";
  11377. const char* sep = "";
  11378. for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
  11379. os << sep << "\n ("
  11380. << "element #" << it->first << ", "
  11381. << "matcher #" << it->second << ")";
  11382. sep = ",";
  11383. }
  11384. os << "\n}";
  11385. }
  11386. bool MatchMatrix::NextGraph() {
  11387. for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
  11388. for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
  11389. char& b = matched_[SpaceIndex(ilhs, irhs)];
  11390. if (!b) {
  11391. b = 1;
  11392. return true;
  11393. }
  11394. b = 0;
  11395. }
  11396. }
  11397. return false;
  11398. }
  11399. void MatchMatrix::Randomize() {
  11400. for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
  11401. for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
  11402. char& b = matched_[SpaceIndex(ilhs, irhs)];
  11403. b = static_cast<char>(rand() & 1); // NOLINT
  11404. }
  11405. }
  11406. }
  11407. std::string MatchMatrix::DebugString() const {
  11408. ::std::stringstream ss;
  11409. const char* sep = "";
  11410. for (size_t i = 0; i < LhsSize(); ++i) {
  11411. ss << sep;
  11412. for (size_t j = 0; j < RhsSize(); ++j) {
  11413. ss << HasEdge(i, j);
  11414. }
  11415. sep = ";";
  11416. }
  11417. return ss.str();
  11418. }
  11419. void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
  11420. ::std::ostream* os) const {
  11421. switch (match_flags()) {
  11422. case UnorderedMatcherRequire::ExactMatch:
  11423. if (matcher_describers_.empty()) {
  11424. *os << "is empty";
  11425. return;
  11426. }
  11427. if (matcher_describers_.size() == 1) {
  11428. *os << "has " << Elements(1) << " and that element ";
  11429. matcher_describers_[0]->DescribeTo(os);
  11430. return;
  11431. }
  11432. *os << "has " << Elements(matcher_describers_.size())
  11433. << " and there exists some permutation of elements such that:\n";
  11434. break;
  11435. case UnorderedMatcherRequire::Superset:
  11436. *os << "a surjection from elements to requirements exists such that:\n";
  11437. break;
  11438. case UnorderedMatcherRequire::Subset:
  11439. *os << "an injection from elements to requirements exists such that:\n";
  11440. break;
  11441. }
  11442. const char* sep = "";
  11443. for (size_t i = 0; i != matcher_describers_.size(); ++i) {
  11444. *os << sep;
  11445. if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
  11446. *os << " - element #" << i << " ";
  11447. } else {
  11448. *os << " - an element ";
  11449. }
  11450. matcher_describers_[i]->DescribeTo(os);
  11451. if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
  11452. sep = ", and\n";
  11453. } else {
  11454. sep = "\n";
  11455. }
  11456. }
  11457. }
  11458. void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
  11459. ::std::ostream* os) const {
  11460. switch (match_flags()) {
  11461. case UnorderedMatcherRequire::ExactMatch:
  11462. if (matcher_describers_.empty()) {
  11463. *os << "isn't empty";
  11464. return;
  11465. }
  11466. if (matcher_describers_.size() == 1) {
  11467. *os << "doesn't have " << Elements(1) << ", or has " << Elements(1)
  11468. << " that ";
  11469. matcher_describers_[0]->DescribeNegationTo(os);
  11470. return;
  11471. }
  11472. *os << "doesn't have " << Elements(matcher_describers_.size())
  11473. << ", or there exists no permutation of elements such that:\n";
  11474. break;
  11475. case UnorderedMatcherRequire::Superset:
  11476. *os << "no surjection from elements to requirements exists such that:\n";
  11477. break;
  11478. case UnorderedMatcherRequire::Subset:
  11479. *os << "no injection from elements to requirements exists such that:\n";
  11480. break;
  11481. }
  11482. const char* sep = "";
  11483. for (size_t i = 0; i != matcher_describers_.size(); ++i) {
  11484. *os << sep;
  11485. if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
  11486. *os << " - element #" << i << " ";
  11487. } else {
  11488. *os << " - an element ";
  11489. }
  11490. matcher_describers_[i]->DescribeTo(os);
  11491. if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
  11492. sep = ", and\n";
  11493. } else {
  11494. sep = "\n";
  11495. }
  11496. }
  11497. }
  11498. // Checks that all matchers match at least one element, and that all
  11499. // elements match at least one matcher. This enables faster matching
  11500. // and better error reporting.
  11501. // Returns false, writing an explanation to 'listener', if and only
  11502. // if the success criteria are not met.
  11503. bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix(
  11504. const ::std::vector<std::string>& element_printouts,
  11505. const MatchMatrix& matrix, MatchResultListener* listener) const {
  11506. bool result = true;
  11507. ::std::vector<char> element_matched(matrix.LhsSize(), 0);
  11508. ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
  11509. for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
  11510. for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
  11511. char matched = matrix.HasEdge(ilhs, irhs);
  11512. element_matched[ilhs] |= matched;
  11513. matcher_matched[irhs] |= matched;
  11514. }
  11515. }
  11516. if (match_flags() & UnorderedMatcherRequire::Superset) {
  11517. const char* sep =
  11518. "where the following matchers don't match any elements:\n";
  11519. for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
  11520. if (matcher_matched[mi]) continue;
  11521. result = false;
  11522. if (listener->IsInterested()) {
  11523. *listener << sep << "matcher #" << mi << ": ";
  11524. matcher_describers_[mi]->DescribeTo(listener->stream());
  11525. sep = ",\n";
  11526. }
  11527. }
  11528. }
  11529. if (match_flags() & UnorderedMatcherRequire::Subset) {
  11530. const char* sep =
  11531. "where the following elements don't match any matchers:\n";
  11532. const char* outer_sep = "";
  11533. if (!result) {
  11534. outer_sep = "\nand ";
  11535. }
  11536. for (size_t ei = 0; ei < element_matched.size(); ++ei) {
  11537. if (element_matched[ei]) continue;
  11538. result = false;
  11539. if (listener->IsInterested()) {
  11540. *listener << outer_sep << sep << "element #" << ei << ": "
  11541. << element_printouts[ei];
  11542. sep = ",\n";
  11543. outer_sep = "";
  11544. }
  11545. }
  11546. }
  11547. return result;
  11548. }
  11549. bool UnorderedElementsAreMatcherImplBase::FindPairing(
  11550. const MatchMatrix& matrix, MatchResultListener* listener) const {
  11551. ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
  11552. size_t max_flow = matches.size();
  11553. if ((match_flags() & UnorderedMatcherRequire::Superset) &&
  11554. max_flow < matrix.RhsSize()) {
  11555. if (listener->IsInterested()) {
  11556. *listener << "where no permutation of the elements can satisfy all "
  11557. "matchers, and the closest match is "
  11558. << max_flow << " of " << matrix.RhsSize()
  11559. << " matchers with the pairings:\n";
  11560. LogElementMatcherPairVec(matches, listener->stream());
  11561. }
  11562. return false;
  11563. }
  11564. if ((match_flags() & UnorderedMatcherRequire::Subset) &&
  11565. max_flow < matrix.LhsSize()) {
  11566. if (listener->IsInterested()) {
  11567. *listener
  11568. << "where not all elements can be matched, and the closest match is "
  11569. << max_flow << " of " << matrix.RhsSize()
  11570. << " matchers with the pairings:\n";
  11571. LogElementMatcherPairVec(matches, listener->stream());
  11572. }
  11573. return false;
  11574. }
  11575. if (matches.size() > 1) {
  11576. if (listener->IsInterested()) {
  11577. const char* sep = "where:\n";
  11578. for (size_t mi = 0; mi < matches.size(); ++mi) {
  11579. *listener << sep << " - element #" << matches[mi].first
  11580. << " is matched by matcher #" << matches[mi].second;
  11581. sep = ",\n";
  11582. }
  11583. }
  11584. }
  11585. return true;
  11586. }
  11587. } // namespace internal
  11588. } // namespace testing
  11589. // Copyright 2007, Google Inc.
  11590. // All rights reserved.
  11591. //
  11592. // Redistribution and use in source and binary forms, with or without
  11593. // modification, are permitted provided that the following conditions are
  11594. // met:
  11595. //
  11596. // * Redistributions of source code must retain the above copyright
  11597. // notice, this list of conditions and the following disclaimer.
  11598. // * Redistributions in binary form must reproduce the above
  11599. // copyright notice, this list of conditions and the following disclaimer
  11600. // in the documentation and/or other materials provided with the
  11601. // distribution.
  11602. // * Neither the name of Google Inc. nor the names of its
  11603. // contributors may be used to endorse or promote products derived from
  11604. // this software without specific prior written permission.
  11605. //
  11606. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  11607. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  11608. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  11609. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  11610. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  11611. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  11612. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  11613. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11614. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  11615. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  11616. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  11617. // Google Mock - a framework for writing C++ mock classes.
  11618. //
  11619. // This file implements the spec builder syntax (ON_CALL and
  11620. // EXPECT_CALL).
  11621. #include <stdlib.h>
  11622. #include <iostream> // NOLINT
  11623. #include <map>
  11624. #include <memory>
  11625. #include <set>
  11626. #include <string>
  11627. #include <vector>
  11628. #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
  11629. # include <unistd.h> // NOLINT
  11630. #endif
  11631. // Silence C4800 (C4800: 'int *const ': forcing value
  11632. // to bool 'true' or 'false') for MSVC 15
  11633. #ifdef _MSC_VER
  11634. #if _MSC_VER == 1900
  11635. # pragma warning(push)
  11636. # pragma warning(disable:4800)
  11637. #endif
  11638. #endif
  11639. namespace testing {
  11640. namespace internal {
  11641. // Protects the mock object registry (in class Mock), all function
  11642. // mockers, and all expectations.
  11643. GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
  11644. // Logs a message including file and line number information.
  11645. GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
  11646. const char* file, int line,
  11647. const std::string& message) {
  11648. ::std::ostringstream s;
  11649. s << internal::FormatFileLocation(file, line) << " " << message
  11650. << ::std::endl;
  11651. Log(severity, s.str(), 0);
  11652. }
  11653. // Constructs an ExpectationBase object.
  11654. ExpectationBase::ExpectationBase(const char* a_file, int a_line,
  11655. const std::string& a_source_text)
  11656. : file_(a_file),
  11657. line_(a_line),
  11658. source_text_(a_source_text),
  11659. cardinality_specified_(false),
  11660. cardinality_(Exactly(1)),
  11661. call_count_(0),
  11662. retired_(false),
  11663. extra_matcher_specified_(false),
  11664. repeated_action_specified_(false),
  11665. retires_on_saturation_(false),
  11666. last_clause_(kNone),
  11667. action_count_checked_(false) {}
  11668. // Destructs an ExpectationBase object.
  11669. ExpectationBase::~ExpectationBase() {}
  11670. // Explicitly specifies the cardinality of this expectation. Used by
  11671. // the subclasses to implement the .Times() clause.
  11672. void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
  11673. cardinality_specified_ = true;
  11674. cardinality_ = a_cardinality;
  11675. }
  11676. // Retires all pre-requisites of this expectation.
  11677. void ExpectationBase::RetireAllPreRequisites()
  11678. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  11679. if (is_retired()) {
  11680. // We can take this short-cut as we never retire an expectation
  11681. // until we have retired all its pre-requisites.
  11682. return;
  11683. }
  11684. ::std::vector<ExpectationBase*> expectations(1, this);
  11685. while (!expectations.empty()) {
  11686. ExpectationBase* exp = expectations.back();
  11687. expectations.pop_back();
  11688. for (ExpectationSet::const_iterator it =
  11689. exp->immediate_prerequisites_.begin();
  11690. it != exp->immediate_prerequisites_.end(); ++it) {
  11691. ExpectationBase* next = it->expectation_base().get();
  11692. if (!next->is_retired()) {
  11693. next->Retire();
  11694. expectations.push_back(next);
  11695. }
  11696. }
  11697. }
  11698. }
  11699. // Returns true if and only if all pre-requisites of this expectation
  11700. // have been satisfied.
  11701. bool ExpectationBase::AllPrerequisitesAreSatisfied() const
  11702. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  11703. g_gmock_mutex.AssertHeld();
  11704. ::std::vector<const ExpectationBase*> expectations(1, this);
  11705. while (!expectations.empty()) {
  11706. const ExpectationBase* exp = expectations.back();
  11707. expectations.pop_back();
  11708. for (ExpectationSet::const_iterator it =
  11709. exp->immediate_prerequisites_.begin();
  11710. it != exp->immediate_prerequisites_.end(); ++it) {
  11711. const ExpectationBase* next = it->expectation_base().get();
  11712. if (!next->IsSatisfied()) return false;
  11713. expectations.push_back(next);
  11714. }
  11715. }
  11716. return true;
  11717. }
  11718. // Adds unsatisfied pre-requisites of this expectation to 'result'.
  11719. void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
  11720. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  11721. g_gmock_mutex.AssertHeld();
  11722. ::std::vector<const ExpectationBase*> expectations(1, this);
  11723. while (!expectations.empty()) {
  11724. const ExpectationBase* exp = expectations.back();
  11725. expectations.pop_back();
  11726. for (ExpectationSet::const_iterator it =
  11727. exp->immediate_prerequisites_.begin();
  11728. it != exp->immediate_prerequisites_.end(); ++it) {
  11729. const ExpectationBase* next = it->expectation_base().get();
  11730. if (next->IsSatisfied()) {
  11731. // If *it is satisfied and has a call count of 0, some of its
  11732. // pre-requisites may not be satisfied yet.
  11733. if (next->call_count_ == 0) {
  11734. expectations.push_back(next);
  11735. }
  11736. } else {
  11737. // Now that we know next is unsatisfied, we are not so interested
  11738. // in whether its pre-requisites are satisfied. Therefore we
  11739. // don't iterate into it here.
  11740. *result += *it;
  11741. }
  11742. }
  11743. }
  11744. }
  11745. // Describes how many times a function call matching this
  11746. // expectation has occurred.
  11747. void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
  11748. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  11749. g_gmock_mutex.AssertHeld();
  11750. // Describes how many times the function is expected to be called.
  11751. *os << " Expected: to be ";
  11752. cardinality().DescribeTo(os);
  11753. *os << "\n Actual: ";
  11754. Cardinality::DescribeActualCallCountTo(call_count(), os);
  11755. // Describes the state of the expectation (e.g. is it satisfied?
  11756. // is it active?).
  11757. *os << " - " << (IsOverSaturated() ? "over-saturated" :
  11758. IsSaturated() ? "saturated" :
  11759. IsSatisfied() ? "satisfied" : "unsatisfied")
  11760. << " and "
  11761. << (is_retired() ? "retired" : "active");
  11762. }
  11763. // Checks the action count (i.e. the number of WillOnce() and
  11764. // WillRepeatedly() clauses) against the cardinality if this hasn't
  11765. // been done before. Prints a warning if there are too many or too
  11766. // few actions.
  11767. void ExpectationBase::CheckActionCountIfNotDone() const
  11768. GTEST_LOCK_EXCLUDED_(mutex_) {
  11769. bool should_check = false;
  11770. {
  11771. MutexLock l(&mutex_);
  11772. if (!action_count_checked_) {
  11773. action_count_checked_ = true;
  11774. should_check = true;
  11775. }
  11776. }
  11777. if (should_check) {
  11778. if (!cardinality_specified_) {
  11779. // The cardinality was inferred - no need to check the action
  11780. // count against it.
  11781. return;
  11782. }
  11783. // The cardinality was explicitly specified.
  11784. const int action_count = static_cast<int>(untyped_actions_.size());
  11785. const int upper_bound = cardinality().ConservativeUpperBound();
  11786. const int lower_bound = cardinality().ConservativeLowerBound();
  11787. bool too_many; // True if there are too many actions, or false
  11788. // if there are too few.
  11789. if (action_count > upper_bound ||
  11790. (action_count == upper_bound && repeated_action_specified_)) {
  11791. too_many = true;
  11792. } else if (0 < action_count && action_count < lower_bound &&
  11793. !repeated_action_specified_) {
  11794. too_many = false;
  11795. } else {
  11796. return;
  11797. }
  11798. ::std::stringstream ss;
  11799. DescribeLocationTo(&ss);
  11800. ss << "Too " << (too_many ? "many" : "few")
  11801. << " actions specified in " << source_text() << "...\n"
  11802. << "Expected to be ";
  11803. cardinality().DescribeTo(&ss);
  11804. ss << ", but has " << (too_many ? "" : "only ")
  11805. << action_count << " WillOnce()"
  11806. << (action_count == 1 ? "" : "s");
  11807. if (repeated_action_specified_) {
  11808. ss << " and a WillRepeatedly()";
  11809. }
  11810. ss << ".";
  11811. Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".
  11812. }
  11813. }
  11814. // Implements the .Times() clause.
  11815. void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
  11816. if (last_clause_ == kTimes) {
  11817. ExpectSpecProperty(false,
  11818. ".Times() cannot appear "
  11819. "more than once in an EXPECT_CALL().");
  11820. } else {
  11821. ExpectSpecProperty(last_clause_ < kTimes,
  11822. ".Times() cannot appear after "
  11823. ".InSequence(), .WillOnce(), .WillRepeatedly(), "
  11824. "or .RetiresOnSaturation().");
  11825. }
  11826. last_clause_ = kTimes;
  11827. SpecifyCardinality(a_cardinality);
  11828. }
  11829. // Points to the implicit sequence introduced by a living InSequence
  11830. // object (if any) in the current thread or NULL.
  11831. GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
  11832. // Reports an uninteresting call (whose description is in msg) in the
  11833. // manner specified by 'reaction'.
  11834. void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
  11835. // Include a stack trace only if --gmock_verbose=info is specified.
  11836. const int stack_frames_to_skip =
  11837. GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
  11838. switch (reaction) {
  11839. case kAllow:
  11840. Log(kInfo, msg, stack_frames_to_skip);
  11841. break;
  11842. case kWarn:
  11843. Log(kWarning,
  11844. msg +
  11845. "\nNOTE: You can safely ignore the above warning unless this "
  11846. "call should not happen. Do not suppress it by blindly adding "
  11847. "an EXPECT_CALL() if you don't mean to enforce the call. "
  11848. "See "
  11849. "https://github.com/google/googletest/blob/master/docs/"
  11850. "gmock_cook_book.md#"
  11851. "knowing-when-to-expect for details.\n",
  11852. stack_frames_to_skip);
  11853. break;
  11854. default: // FAIL
  11855. Expect(false, nullptr, -1, msg);
  11856. }
  11857. }
  11858. UntypedFunctionMockerBase::UntypedFunctionMockerBase()
  11859. : mock_obj_(nullptr), name_("") {}
  11860. UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
  11861. // Sets the mock object this mock method belongs to, and registers
  11862. // this information in the global mock registry. Will be called
  11863. // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
  11864. // method.
  11865. void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
  11866. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  11867. {
  11868. MutexLock l(&g_gmock_mutex);
  11869. mock_obj_ = mock_obj;
  11870. }
  11871. Mock::Register(mock_obj, this);
  11872. }
  11873. // Sets the mock object this mock method belongs to, and sets the name
  11874. // of the mock function. Will be called upon each invocation of this
  11875. // mock function.
  11876. void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
  11877. const char* name)
  11878. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  11879. // We protect name_ under g_gmock_mutex in case this mock function
  11880. // is called from two threads concurrently.
  11881. MutexLock l(&g_gmock_mutex);
  11882. mock_obj_ = mock_obj;
  11883. name_ = name;
  11884. }
  11885. // Returns the name of the function being mocked. Must be called
  11886. // after RegisterOwner() or SetOwnerAndName() has been called.
  11887. const void* UntypedFunctionMockerBase::MockObject() const
  11888. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  11889. const void* mock_obj;
  11890. {
  11891. // We protect mock_obj_ under g_gmock_mutex in case this mock
  11892. // function is called from two threads concurrently.
  11893. MutexLock l(&g_gmock_mutex);
  11894. Assert(mock_obj_ != nullptr, __FILE__, __LINE__,
  11895. "MockObject() must not be called before RegisterOwner() or "
  11896. "SetOwnerAndName() has been called.");
  11897. mock_obj = mock_obj_;
  11898. }
  11899. return mock_obj;
  11900. }
  11901. // Returns the name of this mock method. Must be called after
  11902. // SetOwnerAndName() has been called.
  11903. const char* UntypedFunctionMockerBase::Name() const
  11904. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  11905. const char* name;
  11906. {
  11907. // We protect name_ under g_gmock_mutex in case this mock
  11908. // function is called from two threads concurrently.
  11909. MutexLock l(&g_gmock_mutex);
  11910. Assert(name_ != nullptr, __FILE__, __LINE__,
  11911. "Name() must not be called before SetOwnerAndName() has "
  11912. "been called.");
  11913. name = name_;
  11914. }
  11915. return name;
  11916. }
  11917. // Calculates the result of invoking this mock function with the given
  11918. // arguments, prints it, and returns it. The caller is responsible
  11919. // for deleting the result.
  11920. UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
  11921. void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  11922. // See the definition of untyped_expectations_ for why access to it
  11923. // is unprotected here.
  11924. if (untyped_expectations_.size() == 0) {
  11925. // No expectation is set on this mock method - we have an
  11926. // uninteresting call.
  11927. // We must get Google Mock's reaction on uninteresting calls
  11928. // made on this mock object BEFORE performing the action,
  11929. // because the action may DELETE the mock object and make the
  11930. // following expression meaningless.
  11931. const CallReaction reaction =
  11932. Mock::GetReactionOnUninterestingCalls(MockObject());
  11933. // True if and only if we need to print this call's arguments and return
  11934. // value. This definition must be kept in sync with
  11935. // the behavior of ReportUninterestingCall().
  11936. const bool need_to_report_uninteresting_call =
  11937. // If the user allows this uninteresting call, we print it
  11938. // only when they want informational messages.
  11939. reaction == kAllow ? LogIsVisible(kInfo) :
  11940. // If the user wants this to be a warning, we print
  11941. // it only when they want to see warnings.
  11942. reaction == kWarn
  11943. ? LogIsVisible(kWarning)
  11944. :
  11945. // Otherwise, the user wants this to be an error, and we
  11946. // should always print detailed information in the error.
  11947. true;
  11948. if (!need_to_report_uninteresting_call) {
  11949. // Perform the action without printing the call information.
  11950. return this->UntypedPerformDefaultAction(
  11951. untyped_args, "Function call: " + std::string(Name()));
  11952. }
  11953. // Warns about the uninteresting call.
  11954. ::std::stringstream ss;
  11955. this->UntypedDescribeUninterestingCall(untyped_args, &ss);
  11956. // Calculates the function result.
  11957. UntypedActionResultHolderBase* const result =
  11958. this->UntypedPerformDefaultAction(untyped_args, ss.str());
  11959. // Prints the function result.
  11960. if (result != nullptr) result->PrintAsActionResult(&ss);
  11961. ReportUninterestingCall(reaction, ss.str());
  11962. return result;
  11963. }
  11964. bool is_excessive = false;
  11965. ::std::stringstream ss;
  11966. ::std::stringstream why;
  11967. ::std::stringstream loc;
  11968. const void* untyped_action = nullptr;
  11969. // The UntypedFindMatchingExpectation() function acquires and
  11970. // releases g_gmock_mutex.
  11971. const ExpectationBase* const untyped_expectation =
  11972. this->UntypedFindMatchingExpectation(untyped_args, &untyped_action,
  11973. &is_excessive, &ss, &why);
  11974. const bool found = untyped_expectation != nullptr;
  11975. // True if and only if we need to print the call's arguments
  11976. // and return value.
  11977. // This definition must be kept in sync with the uses of Expect()
  11978. // and Log() in this function.
  11979. const bool need_to_report_call =
  11980. !found || is_excessive || LogIsVisible(kInfo);
  11981. if (!need_to_report_call) {
  11982. // Perform the action without printing the call information.
  11983. return untyped_action == nullptr
  11984. ? this->UntypedPerformDefaultAction(untyped_args, "")
  11985. : this->UntypedPerformAction(untyped_action, untyped_args);
  11986. }
  11987. ss << " Function call: " << Name();
  11988. this->UntypedPrintArgs(untyped_args, &ss);
  11989. // In case the action deletes a piece of the expectation, we
  11990. // generate the message beforehand.
  11991. if (found && !is_excessive) {
  11992. untyped_expectation->DescribeLocationTo(&loc);
  11993. }
  11994. UntypedActionResultHolderBase* result = nullptr;
  11995. auto perform_action = [&] {
  11996. return untyped_action == nullptr
  11997. ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
  11998. : this->UntypedPerformAction(untyped_action, untyped_args);
  11999. };
  12000. auto handle_failures = [&] {
  12001. ss << "\n" << why.str();
  12002. if (!found) {
  12003. // No expectation matches this call - reports a failure.
  12004. Expect(false, nullptr, -1, ss.str());
  12005. } else if (is_excessive) {
  12006. // We had an upper-bound violation and the failure message is in ss.
  12007. Expect(false, untyped_expectation->file(), untyped_expectation->line(),
  12008. ss.str());
  12009. } else {
  12010. // We had an expected call and the matching expectation is
  12011. // described in ss.
  12012. Log(kInfo, loc.str() + ss.str(), 2);
  12013. }
  12014. };
  12015. #if GTEST_HAS_EXCEPTIONS
  12016. try {
  12017. result = perform_action();
  12018. } catch (...) {
  12019. handle_failures();
  12020. throw;
  12021. }
  12022. #else
  12023. result = perform_action();
  12024. #endif
  12025. if (result != nullptr) result->PrintAsActionResult(&ss);
  12026. handle_failures();
  12027. return result;
  12028. }
  12029. // Returns an Expectation object that references and co-owns exp,
  12030. // which must be an expectation on this mock function.
  12031. Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
  12032. // See the definition of untyped_expectations_ for why access to it
  12033. // is unprotected here.
  12034. for (UntypedExpectations::const_iterator it =
  12035. untyped_expectations_.begin();
  12036. it != untyped_expectations_.end(); ++it) {
  12037. if (it->get() == exp) {
  12038. return Expectation(*it);
  12039. }
  12040. }
  12041. Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
  12042. return Expectation();
  12043. // The above statement is just to make the code compile, and will
  12044. // never be executed.
  12045. }
  12046. // Verifies that all expectations on this mock function have been
  12047. // satisfied. Reports one or more Google Test non-fatal failures
  12048. // and returns false if not.
  12049. bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
  12050. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  12051. g_gmock_mutex.AssertHeld();
  12052. bool expectations_met = true;
  12053. for (UntypedExpectations::const_iterator it =
  12054. untyped_expectations_.begin();
  12055. it != untyped_expectations_.end(); ++it) {
  12056. ExpectationBase* const untyped_expectation = it->get();
  12057. if (untyped_expectation->IsOverSaturated()) {
  12058. // There was an upper-bound violation. Since the error was
  12059. // already reported when it occurred, there is no need to do
  12060. // anything here.
  12061. expectations_met = false;
  12062. } else if (!untyped_expectation->IsSatisfied()) {
  12063. expectations_met = false;
  12064. ::std::stringstream ss;
  12065. ss << "Actual function call count doesn't match "
  12066. << untyped_expectation->source_text() << "...\n";
  12067. // No need to show the source file location of the expectation
  12068. // in the description, as the Expect() call that follows already
  12069. // takes care of it.
  12070. untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
  12071. untyped_expectation->DescribeCallCountTo(&ss);
  12072. Expect(false, untyped_expectation->file(),
  12073. untyped_expectation->line(), ss.str());
  12074. }
  12075. }
  12076. // Deleting our expectations may trigger other mock objects to be deleted, for
  12077. // example if an action contains a reference counted smart pointer to that
  12078. // mock object, and that is the last reference. So if we delete our
  12079. // expectations within the context of the global mutex we may deadlock when
  12080. // this method is called again. Instead, make a copy of the set of
  12081. // expectations to delete, clear our set within the mutex, and then clear the
  12082. // copied set outside of it.
  12083. UntypedExpectations expectations_to_delete;
  12084. untyped_expectations_.swap(expectations_to_delete);
  12085. g_gmock_mutex.Unlock();
  12086. expectations_to_delete.clear();
  12087. g_gmock_mutex.Lock();
  12088. return expectations_met;
  12089. }
  12090. CallReaction intToCallReaction(int mock_behavior) {
  12091. if (mock_behavior >= kAllow && mock_behavior <= kFail) {
  12092. return static_cast<internal::CallReaction>(mock_behavior);
  12093. }
  12094. return kWarn;
  12095. }
  12096. } // namespace internal
  12097. // Class Mock.
  12098. namespace {
  12099. typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
  12100. // The current state of a mock object. Such information is needed for
  12101. // detecting leaked mock objects and explicitly verifying a mock's
  12102. // expectations.
  12103. struct MockObjectState {
  12104. MockObjectState()
  12105. : first_used_file(nullptr), first_used_line(-1), leakable(false) {}
  12106. // Where in the source file an ON_CALL or EXPECT_CALL is first
  12107. // invoked on this mock object.
  12108. const char* first_used_file;
  12109. int first_used_line;
  12110. ::std::string first_used_test_suite;
  12111. ::std::string first_used_test;
  12112. bool leakable; // true if and only if it's OK to leak the object.
  12113. FunctionMockers function_mockers; // All registered methods of the object.
  12114. };
  12115. // A global registry holding the state of all mock objects that are
  12116. // alive. A mock object is added to this registry the first time
  12117. // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
  12118. // is removed from the registry in the mock object's destructor.
  12119. class MockObjectRegistry {
  12120. public:
  12121. // Maps a mock object (identified by its address) to its state.
  12122. typedef std::map<const void*, MockObjectState> StateMap;
  12123. // This destructor will be called when a program exits, after all
  12124. // tests in it have been run. By then, there should be no mock
  12125. // object alive. Therefore we report any living object as test
  12126. // failure, unless the user explicitly asked us to ignore it.
  12127. ~MockObjectRegistry() {
  12128. if (!GMOCK_FLAG(catch_leaked_mocks))
  12129. return;
  12130. int leaked_count = 0;
  12131. for (StateMap::const_iterator it = states_.begin(); it != states_.end();
  12132. ++it) {
  12133. if (it->second.leakable) // The user said it's fine to leak this object.
  12134. continue;
  12135. // FIXME: Print the type of the leaked object.
  12136. // This can help the user identify the leaked object.
  12137. std::cout << "\n";
  12138. const MockObjectState& state = it->second;
  12139. std::cout << internal::FormatFileLocation(state.first_used_file,
  12140. state.first_used_line);
  12141. std::cout << " ERROR: this mock object";
  12142. if (state.first_used_test != "") {
  12143. std::cout << " (used in test " << state.first_used_test_suite << "."
  12144. << state.first_used_test << ")";
  12145. }
  12146. std::cout << " should be deleted but never is. Its address is @"
  12147. << it->first << ".";
  12148. leaked_count++;
  12149. }
  12150. if (leaked_count > 0) {
  12151. std::cout << "\nERROR: " << leaked_count << " leaked mock "
  12152. << (leaked_count == 1 ? "object" : "objects")
  12153. << " found at program exit. Expectations on a mock object are "
  12154. "verified when the object is destructed. Leaking a mock "
  12155. "means that its expectations aren't verified, which is "
  12156. "usually a test bug. If you really intend to leak a mock, "
  12157. "you can suppress this error using "
  12158. "testing::Mock::AllowLeak(mock_object), or you may use a "
  12159. "fake or stub instead of a mock.\n";
  12160. std::cout.flush();
  12161. ::std::cerr.flush();
  12162. // RUN_ALL_TESTS() has already returned when this destructor is
  12163. // called. Therefore we cannot use the normal Google Test
  12164. // failure reporting mechanism.
  12165. _exit(1); // We cannot call exit() as it is not reentrant and
  12166. // may already have been called.
  12167. }
  12168. }
  12169. StateMap& states() { return states_; }
  12170. private:
  12171. StateMap states_;
  12172. };
  12173. // Protected by g_gmock_mutex.
  12174. MockObjectRegistry g_mock_object_registry;
  12175. // Maps a mock object to the reaction Google Mock should have when an
  12176. // uninteresting method is called. Protected by g_gmock_mutex.
  12177. std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
  12178. // Sets the reaction Google Mock should have when an uninteresting
  12179. // method of the given mock object is called.
  12180. void SetReactionOnUninterestingCalls(const void* mock_obj,
  12181. internal::CallReaction reaction)
  12182. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12183. internal::MutexLock l(&internal::g_gmock_mutex);
  12184. g_uninteresting_call_reaction[mock_obj] = reaction;
  12185. }
  12186. } // namespace
  12187. // Tells Google Mock to allow uninteresting calls on the given mock
  12188. // object.
  12189. void Mock::AllowUninterestingCalls(const void* mock_obj)
  12190. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12191. SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
  12192. }
  12193. // Tells Google Mock to warn the user about uninteresting calls on the
  12194. // given mock object.
  12195. void Mock::WarnUninterestingCalls(const void* mock_obj)
  12196. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12197. SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
  12198. }
  12199. // Tells Google Mock to fail uninteresting calls on the given mock
  12200. // object.
  12201. void Mock::FailUninterestingCalls(const void* mock_obj)
  12202. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12203. SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
  12204. }
  12205. // Tells Google Mock the given mock object is being destroyed and its
  12206. // entry in the call-reaction table should be removed.
  12207. void Mock::UnregisterCallReaction(const void* mock_obj)
  12208. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12209. internal::MutexLock l(&internal::g_gmock_mutex);
  12210. g_uninteresting_call_reaction.erase(mock_obj);
  12211. }
  12212. // Returns the reaction Google Mock will have on uninteresting calls
  12213. // made on the given mock object.
  12214. internal::CallReaction Mock::GetReactionOnUninterestingCalls(
  12215. const void* mock_obj)
  12216. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12217. internal::MutexLock l(&internal::g_gmock_mutex);
  12218. return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
  12219. internal::intToCallReaction(GMOCK_FLAG(default_mock_behavior)) :
  12220. g_uninteresting_call_reaction[mock_obj];
  12221. }
  12222. // Tells Google Mock to ignore mock_obj when checking for leaked mock
  12223. // objects.
  12224. void Mock::AllowLeak(const void* mock_obj)
  12225. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12226. internal::MutexLock l(&internal::g_gmock_mutex);
  12227. g_mock_object_registry.states()[mock_obj].leakable = true;
  12228. }
  12229. // Verifies and clears all expectations on the given mock object. If
  12230. // the expectations aren't satisfied, generates one or more Google
  12231. // Test non-fatal failures and returns false.
  12232. bool Mock::VerifyAndClearExpectations(void* mock_obj)
  12233. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12234. internal::MutexLock l(&internal::g_gmock_mutex);
  12235. return VerifyAndClearExpectationsLocked(mock_obj);
  12236. }
  12237. // Verifies all expectations on the given mock object and clears its
  12238. // default actions and expectations. Returns true if and only if the
  12239. // verification was successful.
  12240. bool Mock::VerifyAndClear(void* mock_obj)
  12241. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12242. internal::MutexLock l(&internal::g_gmock_mutex);
  12243. ClearDefaultActionsLocked(mock_obj);
  12244. return VerifyAndClearExpectationsLocked(mock_obj);
  12245. }
  12246. // Verifies and clears all expectations on the given mock object. If
  12247. // the expectations aren't satisfied, generates one or more Google
  12248. // Test non-fatal failures and returns false.
  12249. bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
  12250. GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
  12251. internal::g_gmock_mutex.AssertHeld();
  12252. if (g_mock_object_registry.states().count(mock_obj) == 0) {
  12253. // No EXPECT_CALL() was set on the given mock object.
  12254. return true;
  12255. }
  12256. // Verifies and clears the expectations on each mock method in the
  12257. // given mock object.
  12258. bool expectations_met = true;
  12259. FunctionMockers& mockers =
  12260. g_mock_object_registry.states()[mock_obj].function_mockers;
  12261. for (FunctionMockers::const_iterator it = mockers.begin();
  12262. it != mockers.end(); ++it) {
  12263. if (!(*it)->VerifyAndClearExpectationsLocked()) {
  12264. expectations_met = false;
  12265. }
  12266. }
  12267. // We don't clear the content of mockers, as they may still be
  12268. // needed by ClearDefaultActionsLocked().
  12269. return expectations_met;
  12270. }
  12271. bool Mock::IsNaggy(void* mock_obj)
  12272. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12273. return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;
  12274. }
  12275. bool Mock::IsNice(void* mock_obj)
  12276. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12277. return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;
  12278. }
  12279. bool Mock::IsStrict(void* mock_obj)
  12280. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12281. return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;
  12282. }
  12283. // Registers a mock object and a mock method it owns.
  12284. void Mock::Register(const void* mock_obj,
  12285. internal::UntypedFunctionMockerBase* mocker)
  12286. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12287. internal::MutexLock l(&internal::g_gmock_mutex);
  12288. g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
  12289. }
  12290. // Tells Google Mock where in the source code mock_obj is used in an
  12291. // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
  12292. // information helps the user identify which object it is.
  12293. void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
  12294. const char* file, int line)
  12295. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12296. internal::MutexLock l(&internal::g_gmock_mutex);
  12297. MockObjectState& state = g_mock_object_registry.states()[mock_obj];
  12298. if (state.first_used_file == nullptr) {
  12299. state.first_used_file = file;
  12300. state.first_used_line = line;
  12301. const TestInfo* const test_info =
  12302. UnitTest::GetInstance()->current_test_info();
  12303. if (test_info != nullptr) {
  12304. state.first_used_test_suite = test_info->test_suite_name();
  12305. state.first_used_test = test_info->name();
  12306. }
  12307. }
  12308. }
  12309. // Unregisters a mock method; removes the owning mock object from the
  12310. // registry when the last mock method associated with it has been
  12311. // unregistered. This is called only in the destructor of
  12312. // FunctionMockerBase.
  12313. void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
  12314. GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
  12315. internal::g_gmock_mutex.AssertHeld();
  12316. for (MockObjectRegistry::StateMap::iterator it =
  12317. g_mock_object_registry.states().begin();
  12318. it != g_mock_object_registry.states().end(); ++it) {
  12319. FunctionMockers& mockers = it->second.function_mockers;
  12320. if (mockers.erase(mocker) > 0) {
  12321. // mocker was in mockers and has been just removed.
  12322. if (mockers.empty()) {
  12323. g_mock_object_registry.states().erase(it);
  12324. }
  12325. return;
  12326. }
  12327. }
  12328. }
  12329. // Clears all ON_CALL()s set on the given mock object.
  12330. void Mock::ClearDefaultActionsLocked(void* mock_obj)
  12331. GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
  12332. internal::g_gmock_mutex.AssertHeld();
  12333. if (g_mock_object_registry.states().count(mock_obj) == 0) {
  12334. // No ON_CALL() was set on the given mock object.
  12335. return;
  12336. }
  12337. // Clears the default actions for each mock method in the given mock
  12338. // object.
  12339. FunctionMockers& mockers =
  12340. g_mock_object_registry.states()[mock_obj].function_mockers;
  12341. for (FunctionMockers::const_iterator it = mockers.begin();
  12342. it != mockers.end(); ++it) {
  12343. (*it)->ClearDefaultActionsLocked();
  12344. }
  12345. // We don't clear the content of mockers, as they may still be
  12346. // needed by VerifyAndClearExpectationsLocked().
  12347. }
  12348. Expectation::Expectation() {}
  12349. Expectation::Expectation(
  12350. const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
  12351. : expectation_base_(an_expectation_base) {}
  12352. Expectation::~Expectation() {}
  12353. // Adds an expectation to a sequence.
  12354. void Sequence::AddExpectation(const Expectation& expectation) const {
  12355. if (*last_expectation_ != expectation) {
  12356. if (last_expectation_->expectation_base() != nullptr) {
  12357. expectation.expectation_base()->immediate_prerequisites_
  12358. += *last_expectation_;
  12359. }
  12360. *last_expectation_ = expectation;
  12361. }
  12362. }
  12363. // Creates the implicit sequence if there isn't one.
  12364. InSequence::InSequence() {
  12365. if (internal::g_gmock_implicit_sequence.get() == nullptr) {
  12366. internal::g_gmock_implicit_sequence.set(new Sequence);
  12367. sequence_created_ = true;
  12368. } else {
  12369. sequence_created_ = false;
  12370. }
  12371. }
  12372. // Deletes the implicit sequence if it was created by the constructor
  12373. // of this object.
  12374. InSequence::~InSequence() {
  12375. if (sequence_created_) {
  12376. delete internal::g_gmock_implicit_sequence.get();
  12377. internal::g_gmock_implicit_sequence.set(nullptr);
  12378. }
  12379. }
  12380. } // namespace testing
  12381. #ifdef _MSC_VER
  12382. #if _MSC_VER == 1900
  12383. # pragma warning(pop)
  12384. #endif
  12385. #endif
  12386. // Copyright 2008, Google Inc.
  12387. // All rights reserved.
  12388. //
  12389. // Redistribution and use in source and binary forms, with or without
  12390. // modification, are permitted provided that the following conditions are
  12391. // met:
  12392. //
  12393. // * Redistributions of source code must retain the above copyright
  12394. // notice, this list of conditions and the following disclaimer.
  12395. // * Redistributions in binary form must reproduce the above
  12396. // copyright notice, this list of conditions and the following disclaimer
  12397. // in the documentation and/or other materials provided with the
  12398. // distribution.
  12399. // * Neither the name of Google Inc. nor the names of its
  12400. // contributors may be used to endorse or promote products derived from
  12401. // this software without specific prior written permission.
  12402. //
  12403. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  12404. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  12405. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  12406. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  12407. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  12408. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  12409. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  12410. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  12411. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12412. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  12413. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  12414. namespace testing {
  12415. GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
  12416. "true if and only if Google Mock should report leaked "
  12417. "mock objects as failures.");
  12418. GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
  12419. "Controls how verbose Google Mock's output is."
  12420. " Valid values:\n"
  12421. " info - prints all messages.\n"
  12422. " warning - prints warnings and errors.\n"
  12423. " error - prints errors only.");
  12424. GMOCK_DEFINE_int32_(default_mock_behavior, 1,
  12425. "Controls the default behavior of mocks."
  12426. " Valid values:\n"
  12427. " 0 - by default, mocks act as NiceMocks.\n"
  12428. " 1 - by default, mocks act as NaggyMocks.\n"
  12429. " 2 - by default, mocks act as StrictMocks.");
  12430. namespace internal {
  12431. // Parses a string as a command line flag. The string should have the
  12432. // format "--gmock_flag=value". When def_optional is true, the
  12433. // "=value" part can be omitted.
  12434. //
  12435. // Returns the value of the flag, or NULL if the parsing failed.
  12436. static const char* ParseGoogleMockFlagValue(const char* str,
  12437. const char* flag,
  12438. bool def_optional) {
  12439. // str and flag must not be NULL.
  12440. if (str == nullptr || flag == nullptr) return nullptr;
  12441. // The flag must start with "--gmock_".
  12442. const std::string flag_str = std::string("--gmock_") + flag;
  12443. const size_t flag_len = flag_str.length();
  12444. if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
  12445. // Skips the flag name.
  12446. const char* flag_end = str + flag_len;
  12447. // When def_optional is true, it's OK to not have a "=value" part.
  12448. if (def_optional && (flag_end[0] == '\0')) {
  12449. return flag_end;
  12450. }
  12451. // If def_optional is true and there are more characters after the
  12452. // flag name, or if def_optional is false, there must be a '=' after
  12453. // the flag name.
  12454. if (flag_end[0] != '=') return nullptr;
  12455. // Returns the string after "=".
  12456. return flag_end + 1;
  12457. }
  12458. // Parses a string for a Google Mock bool flag, in the form of
  12459. // "--gmock_flag=value".
  12460. //
  12461. // On success, stores the value of the flag in *value, and returns
  12462. // true. On failure, returns false without changing *value.
  12463. static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
  12464. bool* value) {
  12465. // Gets the value of the flag as a string.
  12466. const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
  12467. // Aborts if the parsing failed.
  12468. if (value_str == nullptr) return false;
  12469. // Converts the string value to a bool.
  12470. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  12471. return true;
  12472. }
  12473. // Parses a string for a Google Mock string flag, in the form of
  12474. // "--gmock_flag=value".
  12475. //
  12476. // On success, stores the value of the flag in *value, and returns
  12477. // true. On failure, returns false without changing *value.
  12478. template <typename String>
  12479. static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
  12480. String* value) {
  12481. // Gets the value of the flag as a string.
  12482. const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
  12483. // Aborts if the parsing failed.
  12484. if (value_str == nullptr) return false;
  12485. // Sets *value to the value of the flag.
  12486. *value = value_str;
  12487. return true;
  12488. }
  12489. static bool ParseGoogleMockIntFlag(const char* str, const char* flag,
  12490. int32_t* value) {
  12491. // Gets the value of the flag as a string.
  12492. const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
  12493. // Aborts if the parsing failed.
  12494. if (value_str == nullptr) return false;
  12495. // Sets *value to the value of the flag.
  12496. return ParseInt32(Message() << "The value of flag --" << flag,
  12497. value_str, value);
  12498. }
  12499. // The internal implementation of InitGoogleMock().
  12500. //
  12501. // The type parameter CharType can be instantiated to either char or
  12502. // wchar_t.
  12503. template <typename CharType>
  12504. void InitGoogleMockImpl(int* argc, CharType** argv) {
  12505. // Makes sure Google Test is initialized. InitGoogleTest() is
  12506. // idempotent, so it's fine if the user has already called it.
  12507. InitGoogleTest(argc, argv);
  12508. if (*argc <= 0) return;
  12509. for (int i = 1; i != *argc; i++) {
  12510. const std::string arg_string = StreamableToString(argv[i]);
  12511. const char* const arg = arg_string.c_str();
  12512. // Do we see a Google Mock flag?
  12513. if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
  12514. &GMOCK_FLAG(catch_leaked_mocks)) ||
  12515. ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose)) ||
  12516. ParseGoogleMockIntFlag(arg, "default_mock_behavior",
  12517. &GMOCK_FLAG(default_mock_behavior))) {
  12518. // Yes. Shift the remainder of the argv list left by one. Note
  12519. // that argv has (*argc + 1) elements, the last one always being
  12520. // NULL. The following loop moves the trailing NULL element as
  12521. // well.
  12522. for (int j = i; j != *argc; j++) {
  12523. argv[j] = argv[j + 1];
  12524. }
  12525. // Decrements the argument count.
  12526. (*argc)--;
  12527. // We also need to decrement the iterator as we just removed
  12528. // an element.
  12529. i--;
  12530. }
  12531. }
  12532. }
  12533. } // namespace internal
  12534. // Initializes Google Mock. This must be called before running the
  12535. // tests. In particular, it parses a command line for the flags that
  12536. // Google Mock recognizes. Whenever a Google Mock flag is seen, it is
  12537. // removed from argv, and *argc is decremented.
  12538. //
  12539. // No value is returned. Instead, the Google Mock flag variables are
  12540. // updated.
  12541. //
  12542. // Since Google Test is needed for Google Mock to work, this function
  12543. // also initializes Google Test and parses its flags, if that hasn't
  12544. // been done.
  12545. GTEST_API_ void InitGoogleMock(int* argc, char** argv) {
  12546. internal::InitGoogleMockImpl(argc, argv);
  12547. }
  12548. // This overloaded version can be used in Windows programs compiled in
  12549. // UNICODE mode.
  12550. GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
  12551. internal::InitGoogleMockImpl(argc, argv);
  12552. }
  12553. // This overloaded version can be used on Arduino/embedded platforms where
  12554. // there is no argc/argv.
  12555. GTEST_API_ void InitGoogleMock() {
  12556. // Since Arduino doesn't have a command line, fake out the argc/argv arguments
  12557. int argc = 1;
  12558. const auto arg0 = "dummy";
  12559. char* argv0 = const_cast<char*>(arg0);
  12560. char** argv = &argv0;
  12561. internal::InitGoogleMockImpl(&argc, argv);
  12562. }
  12563. } // namespace testing