gtest-all.cc 405 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394
  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 GTEST_INCLUDE_GTEST_GTEST_SPI_H_
  101. #define GTEST_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. virtual ~ScopedFakeTestPartResultReporter();
  132. // Appends the TestPartResult object to the TestPartResultArray
  133. // received in the constructor.
  134. //
  135. // This method is from the TestPartResultReporterInterface
  136. // interface.
  137. virtual void ReportTestPartResult(const TestPartResult& result);
  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 // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
  280. #include <ctype.h>
  281. #include <math.h>
  282. #include <stdarg.h>
  283. #include <stdio.h>
  284. #include <stdlib.h>
  285. #include <time.h>
  286. #include <wchar.h>
  287. #include <wctype.h>
  288. #include <algorithm>
  289. #include <iomanip>
  290. #include <limits>
  291. #include <list>
  292. #include <map>
  293. #include <ostream> // NOLINT
  294. #include <sstream>
  295. #include <vector>
  296. #if GTEST_OS_LINUX
  297. // FIXME: Use autoconf to detect availability of
  298. // gettimeofday().
  299. # define GTEST_HAS_GETTIMEOFDAY_ 1
  300. # include <fcntl.h> // NOLINT
  301. # include <limits.h> // NOLINT
  302. # include <sched.h> // NOLINT
  303. // Declares vsnprintf(). This header is not available on Windows.
  304. # include <strings.h> // NOLINT
  305. # include <sys/mman.h> // NOLINT
  306. # include <sys/time.h> // NOLINT
  307. # include <unistd.h> // NOLINT
  308. # include <string>
  309. #elif GTEST_OS_SYMBIAN
  310. # define GTEST_HAS_GETTIMEOFDAY_ 1
  311. # include <sys/time.h> // NOLINT
  312. #elif GTEST_OS_ZOS
  313. # define GTEST_HAS_GETTIMEOFDAY_ 1
  314. # include <sys/time.h> // NOLINT
  315. // On z/OS we additionally need strings.h for strcasecmp.
  316. # include <strings.h> // NOLINT
  317. #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
  318. # include <windows.h> // NOLINT
  319. # undef min
  320. #elif GTEST_OS_WINDOWS // We are on Windows proper.
  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. // MinGW has gettimeofday() but not _ftime64().
  327. // FIXME: Use autoconf to detect availability of
  328. // gettimeofday().
  329. // FIXME: There are other ways to get the time on
  330. // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
  331. // supports these. consider using them instead.
  332. # define GTEST_HAS_GETTIMEOFDAY_ 1
  333. # include <sys/time.h> // NOLINT
  334. # endif // GTEST_OS_WINDOWS_MINGW
  335. // cpplint thinks that the header is already included, so we want to
  336. // silence it.
  337. # include <windows.h> // NOLINT
  338. # undef min
  339. #else
  340. // Assume other platforms have gettimeofday().
  341. // FIXME: Use autoconf to detect availability of
  342. // gettimeofday().
  343. # define GTEST_HAS_GETTIMEOFDAY_ 1
  344. // cpplint thinks that the header is already included, so we want to
  345. // silence it.
  346. # include <sys/time.h> // NOLINT
  347. # include <unistd.h> // NOLINT
  348. #endif // GTEST_OS_LINUX
  349. #if GTEST_HAS_EXCEPTIONS
  350. # include <stdexcept>
  351. #endif
  352. #if GTEST_CAN_STREAM_RESULTS_
  353. # include <arpa/inet.h> // NOLINT
  354. # include <netdb.h> // NOLINT
  355. # include <sys/socket.h> // NOLINT
  356. # include <sys/types.h> // NOLINT
  357. #endif
  358. // Copyright 2005, Google Inc.
  359. // All rights reserved.
  360. //
  361. // Redistribution and use in source and binary forms, with or without
  362. // modification, are permitted provided that the following conditions are
  363. // met:
  364. //
  365. // * Redistributions of source code must retain the above copyright
  366. // notice, this list of conditions and the following disclaimer.
  367. // * Redistributions in binary form must reproduce the above
  368. // copyright notice, this list of conditions and the following disclaimer
  369. // in the documentation and/or other materials provided with the
  370. // distribution.
  371. // * Neither the name of Google Inc. nor the names of its
  372. // contributors may be used to endorse or promote products derived from
  373. // this software without specific prior written permission.
  374. //
  375. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  376. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  377. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  378. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  379. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  380. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  381. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  382. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  383. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  384. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  385. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  386. // Utility functions and classes used by the Google C++ testing framework.//
  387. // This file contains purely Google Test's internal implementation. Please
  388. // DO NOT #INCLUDE IT IN A USER PROGRAM.
  389. #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
  390. #define GTEST_SRC_GTEST_INTERNAL_INL_H_
  391. #ifndef _WIN32_WCE
  392. # include <errno.h>
  393. #endif // !_WIN32_WCE
  394. #include <stddef.h>
  395. #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
  396. #include <string.h> // For memmove.
  397. #include <algorithm>
  398. #include <string>
  399. #include <vector>
  400. #if GTEST_CAN_STREAM_RESULTS_
  401. # include <arpa/inet.h> // NOLINT
  402. # include <netdb.h> // NOLINT
  403. #endif
  404. #if GTEST_OS_WINDOWS
  405. # include <windows.h> // NOLINT
  406. #endif // GTEST_OS_WINDOWS
  407. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  408. /* class A needs to have dll-interface to be used by clients of class B */)
  409. namespace testing {
  410. // Declares the flags.
  411. //
  412. // We don't want the users to modify this flag in the code, but want
  413. // Google Test's own unit tests to be able to access it. Therefore we
  414. // declare it here as opposed to in gtest.h.
  415. GTEST_DECLARE_bool_(death_test_use_fork);
  416. namespace internal {
  417. // The value of GetTestTypeId() as seen from within the Google Test
  418. // library. This is solely for testing GetTestTypeId().
  419. GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
  420. // Names of the flags (needed for parsing Google Test flags).
  421. const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
  422. const char kBreakOnFailureFlag[] = "break_on_failure";
  423. const char kCatchExceptionsFlag[] = "catch_exceptions";
  424. const char kColorFlag[] = "color";
  425. const char kFilterFlag[] = "filter";
  426. const char kListTestsFlag[] = "list_tests";
  427. const char kOutputFlag[] = "output";
  428. const char kPrintTimeFlag[] = "print_time";
  429. const char kPrintUTF8Flag[] = "print_utf8";
  430. const char kRandomSeedFlag[] = "random_seed";
  431. const char kRepeatFlag[] = "repeat";
  432. const char kShuffleFlag[] = "shuffle";
  433. const char kStackTraceDepthFlag[] = "stack_trace_depth";
  434. const char kStreamResultToFlag[] = "stream_result_to";
  435. const char kThrowOnFailureFlag[] = "throw_on_failure";
  436. const char kFlagfileFlag[] = "flagfile";
  437. // A valid random seed must be in [1, kMaxRandomSeed].
  438. const int kMaxRandomSeed = 99999;
  439. // g_help_flag is true iff the --help flag or an equivalent form is
  440. // specified on the command line.
  441. GTEST_API_ extern bool g_help_flag;
  442. // Returns the current time in milliseconds.
  443. GTEST_API_ TimeInMillis GetTimeInMillis();
  444. // Returns true iff Google Test should use colors in the output.
  445. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
  446. // Formats the given time in milliseconds as seconds.
  447. GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
  448. // Converts the given time in milliseconds to a date string in the ISO 8601
  449. // format, without the timezone information. N.B.: due to the use the
  450. // non-reentrant localtime() function, this function is not thread safe. Do
  451. // not use it in any code that can be called from multiple threads.
  452. GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
  453. // Parses a string for an Int32 flag, in the form of "--flag=value".
  454. //
  455. // On success, stores the value of the flag in *value, and returns
  456. // true. On failure, returns false without changing *value.
  457. GTEST_API_ bool ParseInt32Flag(
  458. const char* str, const char* flag, Int32* value);
  459. // Returns a random seed in range [1, kMaxRandomSeed] based on the
  460. // given --gtest_random_seed flag value.
  461. inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
  462. const unsigned int raw_seed = (random_seed_flag == 0) ?
  463. static_cast<unsigned int>(GetTimeInMillis()) :
  464. static_cast<unsigned int>(random_seed_flag);
  465. // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
  466. // it's easy to type.
  467. const int normalized_seed =
  468. static_cast<int>((raw_seed - 1U) %
  469. static_cast<unsigned int>(kMaxRandomSeed)) + 1;
  470. return normalized_seed;
  471. }
  472. // Returns the first valid random seed after 'seed'. The behavior is
  473. // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
  474. // considered to be 1.
  475. inline int GetNextRandomSeed(int seed) {
  476. GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
  477. << "Invalid random seed " << seed << " - must be in [1, "
  478. << kMaxRandomSeed << "].";
  479. const int next_seed = seed + 1;
  480. return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
  481. }
  482. // This class saves the values of all Google Test flags in its c'tor, and
  483. // restores them in its d'tor.
  484. class GTestFlagSaver {
  485. public:
  486. // The c'tor.
  487. GTestFlagSaver() {
  488. also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
  489. break_on_failure_ = GTEST_FLAG(break_on_failure);
  490. catch_exceptions_ = GTEST_FLAG(catch_exceptions);
  491. color_ = GTEST_FLAG(color);
  492. death_test_style_ = GTEST_FLAG(death_test_style);
  493. death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
  494. filter_ = GTEST_FLAG(filter);
  495. internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
  496. list_tests_ = GTEST_FLAG(list_tests);
  497. output_ = GTEST_FLAG(output);
  498. print_time_ = GTEST_FLAG(print_time);
  499. print_utf8_ = GTEST_FLAG(print_utf8);
  500. random_seed_ = GTEST_FLAG(random_seed);
  501. repeat_ = GTEST_FLAG(repeat);
  502. shuffle_ = GTEST_FLAG(shuffle);
  503. stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
  504. stream_result_to_ = GTEST_FLAG(stream_result_to);
  505. throw_on_failure_ = GTEST_FLAG(throw_on_failure);
  506. }
  507. // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
  508. ~GTestFlagSaver() {
  509. GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
  510. GTEST_FLAG(break_on_failure) = break_on_failure_;
  511. GTEST_FLAG(catch_exceptions) = catch_exceptions_;
  512. GTEST_FLAG(color) = color_;
  513. GTEST_FLAG(death_test_style) = death_test_style_;
  514. GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
  515. GTEST_FLAG(filter) = filter_;
  516. GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
  517. GTEST_FLAG(list_tests) = list_tests_;
  518. GTEST_FLAG(output) = output_;
  519. GTEST_FLAG(print_time) = print_time_;
  520. GTEST_FLAG(print_utf8) = print_utf8_;
  521. GTEST_FLAG(random_seed) = random_seed_;
  522. GTEST_FLAG(repeat) = repeat_;
  523. GTEST_FLAG(shuffle) = shuffle_;
  524. GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
  525. GTEST_FLAG(stream_result_to) = stream_result_to_;
  526. GTEST_FLAG(throw_on_failure) = throw_on_failure_;
  527. }
  528. private:
  529. // Fields for saving the original values of flags.
  530. bool also_run_disabled_tests_;
  531. bool break_on_failure_;
  532. bool catch_exceptions_;
  533. std::string color_;
  534. std::string death_test_style_;
  535. bool death_test_use_fork_;
  536. std::string filter_;
  537. std::string internal_run_death_test_;
  538. bool list_tests_;
  539. std::string output_;
  540. bool print_time_;
  541. bool print_utf8_;
  542. internal::Int32 random_seed_;
  543. internal::Int32 repeat_;
  544. bool shuffle_;
  545. internal::Int32 stack_trace_depth_;
  546. std::string stream_result_to_;
  547. bool throw_on_failure_;
  548. } GTEST_ATTRIBUTE_UNUSED_;
  549. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  550. // code_point parameter is of type UInt32 because wchar_t may not be
  551. // wide enough to contain a code point.
  552. // If the code_point is not a valid Unicode code point
  553. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  554. // to "(Invalid Unicode 0xXXXXXXXX)".
  555. GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
  556. // Converts a wide string to a narrow string in UTF-8 encoding.
  557. // The wide string is assumed to have the following encoding:
  558. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
  559. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  560. // Parameter str points to a null-terminated wide string.
  561. // Parameter num_chars may additionally limit the number
  562. // of wchar_t characters processed. -1 is used when the entire string
  563. // should be processed.
  564. // If the string contains code points that are not valid Unicode code points
  565. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  566. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  567. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  568. // will be encoded as individual Unicode characters from Basic Normal Plane.
  569. GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
  570. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  571. // if the variable is present. If a file already exists at this location, this
  572. // function will write over it. If the variable is present, but the file cannot
  573. // be created, prints an error and exits.
  574. void WriteToShardStatusFileIfNeeded();
  575. // Checks whether sharding is enabled by examining the relevant
  576. // environment variable values. If the variables are present,
  577. // but inconsistent (e.g., shard_index >= total_shards), prints
  578. // an error and exits. If in_subprocess_for_death_test, sharding is
  579. // disabled because it must only be applied to the original test
  580. // process. Otherwise, we could filter out death tests we intended to execute.
  581. GTEST_API_ bool ShouldShard(const char* total_shards_str,
  582. const char* shard_index_str,
  583. bool in_subprocess_for_death_test);
  584. // Parses the environment variable var as an Int32. If it is unset,
  585. // returns default_val. If it is not an Int32, prints an error and
  586. // and aborts.
  587. GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
  588. // Given the total number of shards, the shard index, and the test id,
  589. // returns true iff the test should be run on this shard. The test id is
  590. // some arbitrary but unique non-negative integer assigned to each test
  591. // method. Assumes that 0 <= shard_index < total_shards.
  592. GTEST_API_ bool ShouldRunTestOnShard(
  593. int total_shards, int shard_index, int test_id);
  594. // STL container utilities.
  595. // Returns the number of elements in the given container that satisfy
  596. // the given predicate.
  597. template <class Container, typename Predicate>
  598. inline int CountIf(const Container& c, Predicate predicate) {
  599. // Implemented as an explicit loop since std::count_if() in libCstd on
  600. // Solaris has a non-standard signature.
  601. int count = 0;
  602. for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
  603. if (predicate(*it))
  604. ++count;
  605. }
  606. return count;
  607. }
  608. // Applies a function/functor to each element in the container.
  609. template <class Container, typename Functor>
  610. void ForEach(const Container& c, Functor functor) {
  611. std::for_each(c.begin(), c.end(), functor);
  612. }
  613. // Returns the i-th element of the vector, or default_value if i is not
  614. // in range [0, v.size()).
  615. template <typename E>
  616. inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
  617. return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
  618. }
  619. // Performs an in-place shuffle of a range of the vector's elements.
  620. // 'begin' and 'end' are element indices as an STL-style range;
  621. // i.e. [begin, end) are shuffled, where 'end' == size() means to
  622. // shuffle to the end of the vector.
  623. template <typename E>
  624. void ShuffleRange(internal::Random* random, int begin, int end,
  625. std::vector<E>* v) {
  626. const int size = static_cast<int>(v->size());
  627. GTEST_CHECK_(0 <= begin && begin <= size)
  628. << "Invalid shuffle range start " << begin << ": must be in range [0, "
  629. << size << "].";
  630. GTEST_CHECK_(begin <= end && end <= size)
  631. << "Invalid shuffle range finish " << end << ": must be in range ["
  632. << begin << ", " << size << "].";
  633. // Fisher-Yates shuffle, from
  634. // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  635. for (int range_width = end - begin; range_width >= 2; range_width--) {
  636. const int last_in_range = begin + range_width - 1;
  637. const int selected = begin + random->Generate(range_width);
  638. std::swap((*v)[selected], (*v)[last_in_range]);
  639. }
  640. }
  641. // Performs an in-place shuffle of the vector's elements.
  642. template <typename E>
  643. inline void Shuffle(internal::Random* random, std::vector<E>* v) {
  644. ShuffleRange(random, 0, static_cast<int>(v->size()), v);
  645. }
  646. // A function for deleting an object. Handy for being used as a
  647. // functor.
  648. template <typename T>
  649. static void Delete(T* x) {
  650. delete x;
  651. }
  652. // A predicate that checks the key of a TestProperty against a known key.
  653. //
  654. // TestPropertyKeyIs is copyable.
  655. class TestPropertyKeyIs {
  656. public:
  657. // Constructor.
  658. //
  659. // TestPropertyKeyIs has NO default constructor.
  660. explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
  661. // Returns true iff the test name of test property matches on key_.
  662. bool operator()(const TestProperty& test_property) const {
  663. return test_property.key() == key_;
  664. }
  665. private:
  666. std::string key_;
  667. };
  668. // Class UnitTestOptions.
  669. //
  670. // This class contains functions for processing options the user
  671. // specifies when running the tests. It has only static members.
  672. //
  673. // In most cases, the user can specify an option using either an
  674. // environment variable or a command line flag. E.g. you can set the
  675. // test filter using either GTEST_FILTER or --gtest_filter. If both
  676. // the variable and the flag are present, the latter overrides the
  677. // former.
  678. class GTEST_API_ UnitTestOptions {
  679. public:
  680. // Functions for processing the gtest_output flag.
  681. // Returns the output format, or "" for normal printed output.
  682. static std::string GetOutputFormat();
  683. // Returns the absolute path of the requested output file, or the
  684. // default (test_detail.xml in the original working directory) if
  685. // none was explicitly specified.
  686. static std::string GetAbsolutePathToOutputFile();
  687. // Functions for processing the gtest_filter flag.
  688. // Returns true iff the wildcard pattern matches the string. The
  689. // first ':' or '\0' character in pattern marks the end of it.
  690. //
  691. // This recursive algorithm isn't very efficient, but is clear and
  692. // works well enough for matching test names, which are short.
  693. static bool PatternMatchesString(const char *pattern, const char *str);
  694. // Returns true iff the user-specified filter matches the test case
  695. // name and the test name.
  696. static bool FilterMatchesTest(const std::string &test_case_name,
  697. const std::string &test_name);
  698. #if GTEST_OS_WINDOWS
  699. // Function for supporting the gtest_catch_exception flag.
  700. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  701. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  702. // This function is useful as an __except condition.
  703. static int GTestShouldProcessSEH(DWORD exception_code);
  704. #endif // GTEST_OS_WINDOWS
  705. // Returns true if "name" matches the ':' separated list of glob-style
  706. // filters in "filter".
  707. static bool MatchesFilter(const std::string& name, const char* filter);
  708. };
  709. // Returns the current application's name, removing directory path if that
  710. // is present. Used by UnitTestOptions::GetOutputFile.
  711. GTEST_API_ FilePath GetCurrentExecutableName();
  712. // The role interface for getting the OS stack trace as a string.
  713. class OsStackTraceGetterInterface {
  714. public:
  715. OsStackTraceGetterInterface() {}
  716. virtual ~OsStackTraceGetterInterface() {}
  717. // Returns the current OS stack trace as an std::string. Parameters:
  718. //
  719. // max_depth - the maximum number of stack frames to be included
  720. // in the trace.
  721. // skip_count - the number of top frames to be skipped; doesn't count
  722. // against max_depth.
  723. virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
  724. // UponLeavingGTest() should be called immediately before Google Test calls
  725. // user code. It saves some information about the current stack that
  726. // CurrentStackTrace() will use to find and hide Google Test stack frames.
  727. virtual void UponLeavingGTest() = 0;
  728. // This string is inserted in place of stack frames that are part of
  729. // Google Test's implementation.
  730. static const char* const kElidedFramesMarker;
  731. private:
  732. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
  733. };
  734. // A working implementation of the OsStackTraceGetterInterface interface.
  735. class OsStackTraceGetter : public OsStackTraceGetterInterface {
  736. public:
  737. OsStackTraceGetter() {}
  738. virtual std::string CurrentStackTrace(int max_depth, int skip_count);
  739. virtual void UponLeavingGTest();
  740. private:
  741. #if GTEST_HAS_ABSL
  742. Mutex mutex_; // Protects all internal state.
  743. // We save the stack frame below the frame that calls user code.
  744. // We do this because the address of the frame immediately below
  745. // the user code changes between the call to UponLeavingGTest()
  746. // and any calls to the stack trace code from within the user code.
  747. void* caller_frame_ = nullptr;
  748. #endif // GTEST_HAS_ABSL
  749. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
  750. };
  751. // Information about a Google Test trace point.
  752. struct TraceInfo {
  753. const char* file;
  754. int line;
  755. std::string message;
  756. };
  757. // This is the default global test part result reporter used in UnitTestImpl.
  758. // This class should only be used by UnitTestImpl.
  759. class DefaultGlobalTestPartResultReporter
  760. : public TestPartResultReporterInterface {
  761. public:
  762. explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
  763. // Implements the TestPartResultReporterInterface. Reports the test part
  764. // result in the current test.
  765. virtual void ReportTestPartResult(const TestPartResult& result);
  766. private:
  767. UnitTestImpl* const unit_test_;
  768. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
  769. };
  770. // This is the default per thread test part result reporter used in
  771. // UnitTestImpl. This class should only be used by UnitTestImpl.
  772. class DefaultPerThreadTestPartResultReporter
  773. : public TestPartResultReporterInterface {
  774. public:
  775. explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
  776. // Implements the TestPartResultReporterInterface. The implementation just
  777. // delegates to the current global test part result reporter of *unit_test_.
  778. virtual void ReportTestPartResult(const TestPartResult& result);
  779. private:
  780. UnitTestImpl* const unit_test_;
  781. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
  782. };
  783. // The private implementation of the UnitTest class. We don't protect
  784. // the methods under a mutex, as this class is not accessible by a
  785. // user and the UnitTest class that delegates work to this class does
  786. // proper locking.
  787. class GTEST_API_ UnitTestImpl {
  788. public:
  789. explicit UnitTestImpl(UnitTest* parent);
  790. virtual ~UnitTestImpl();
  791. // There are two different ways to register your own TestPartResultReporter.
  792. // You can register your own repoter to listen either only for test results
  793. // from the current thread or for results from all threads.
  794. // By default, each per-thread test result repoter just passes a new
  795. // TestPartResult to the global test result reporter, which registers the
  796. // test part result for the currently running test.
  797. // Returns the global test part result reporter.
  798. TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
  799. // Sets the global test part result reporter.
  800. void SetGlobalTestPartResultReporter(
  801. TestPartResultReporterInterface* reporter);
  802. // Returns the test part result reporter for the current thread.
  803. TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
  804. // Sets the test part result reporter for the current thread.
  805. void SetTestPartResultReporterForCurrentThread(
  806. TestPartResultReporterInterface* reporter);
  807. // Gets the number of successful test cases.
  808. int successful_test_case_count() const;
  809. // Gets the number of failed test cases.
  810. int failed_test_case_count() const;
  811. // Gets the number of all test cases.
  812. int total_test_case_count() const;
  813. // Gets the number of all test cases that contain at least one test
  814. // that should run.
  815. int test_case_to_run_count() const;
  816. // Gets the number of successful tests.
  817. int successful_test_count() const;
  818. // Gets the number of failed tests.
  819. int failed_test_count() const;
  820. // Gets the number of disabled tests that will be reported in the XML report.
  821. int reportable_disabled_test_count() const;
  822. // Gets the number of disabled tests.
  823. int disabled_test_count() const;
  824. // Gets the number of tests to be printed in the XML report.
  825. int reportable_test_count() const;
  826. // Gets the number of all tests.
  827. int total_test_count() const;
  828. // Gets the number of tests that should run.
  829. int test_to_run_count() const;
  830. // Gets the time of the test program start, in ms from the start of the
  831. // UNIX epoch.
  832. TimeInMillis start_timestamp() const { return start_timestamp_; }
  833. // Gets the elapsed time, in milliseconds.
  834. TimeInMillis elapsed_time() const { return elapsed_time_; }
  835. // Returns true iff the unit test passed (i.e. all test cases passed).
  836. bool Passed() const { return !Failed(); }
  837. // Returns true iff the unit test failed (i.e. some test case failed
  838. // or something outside of all tests failed).
  839. bool Failed() const {
  840. return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
  841. }
  842. // Gets the i-th test case among all the test cases. i can range from 0 to
  843. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  844. const TestCase* GetTestCase(int i) const {
  845. const int index = GetElementOr(test_case_indices_, i, -1);
  846. return index < 0 ? NULL : test_cases_[i];
  847. }
  848. // Gets the i-th test case among all the test cases. i can range from 0 to
  849. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  850. TestCase* GetMutableTestCase(int i) {
  851. const int index = GetElementOr(test_case_indices_, i, -1);
  852. return index < 0 ? NULL : test_cases_[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 TestCase with the given name. If one doesn't
  883. // exist, creates one and returns it.
  884. //
  885. // Arguments:
  886. //
  887. // test_case_name: name of the test case
  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 case
  891. // tear_down_tc: pointer to the function that tears down the test case
  892. TestCase* GetTestCase(const char* test_case_name,
  893. const char* type_param,
  894. Test::SetUpTestCaseFunc set_up_tc,
  895. Test::TearDownTestCaseFunc tear_down_tc);
  896. // Adds a TestInfo to the unit test.
  897. //
  898. // Arguments:
  899. //
  900. // set_up_tc: pointer to the function that sets up the test case
  901. // tear_down_tc: pointer to the function that tears down the test case
  902. // test_info: the TestInfo object
  903. void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
  904. Test::TearDownTestCaseFunc tear_down_tc,
  905. TestInfo* test_info) {
  906. // In order to support thread-safe death tests, we need to
  907. // remember the original working directory when the test program
  908. // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
  909. // the user may have changed the current directory before calling
  910. // RUN_ALL_TESTS(). Therefore we capture the current directory in
  911. // AddTestInfo(), which is called to register a TEST or TEST_F
  912. // before main() is reached.
  913. if (original_working_dir_.IsEmpty()) {
  914. original_working_dir_.Set(FilePath::GetCurrentDir());
  915. GTEST_CHECK_(!original_working_dir_.IsEmpty())
  916. << "Failed to get the current working directory.";
  917. }
  918. GetTestCase(test_info->test_case_name(),
  919. test_info->type_param(),
  920. set_up_tc,
  921. tear_down_tc)->AddTestInfo(test_info);
  922. }
  923. // Returns ParameterizedTestCaseRegistry object used to keep track of
  924. // value-parameterized tests and instantiate and register them.
  925. internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
  926. return parameterized_test_registry_;
  927. }
  928. // Sets the TestCase object for the test that's currently running.
  929. void set_current_test_case(TestCase* a_current_test_case) {
  930. current_test_case_ = a_current_test_case;
  931. }
  932. // Sets the TestInfo object for the test that's currently running. If
  933. // current_test_info is NULL, the assertion results will be stored in
  934. // ad_hoc_test_result_.
  935. void set_current_test_info(TestInfo* a_current_test_info) {
  936. current_test_info_ = a_current_test_info;
  937. }
  938. // Registers all parameterized tests defined using TEST_P and
  939. // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
  940. // combination. This method can be called more then once; it has guards
  941. // protecting from registering the tests more then once. If
  942. // value-parameterized tests are disabled, RegisterParameterizedTests is
  943. // present but does nothing.
  944. void RegisterParameterizedTests();
  945. // Runs all tests in this UnitTest object, prints the result, and
  946. // returns true if all tests are successful. If any exception is
  947. // thrown during a test, this test is considered to be failed, but
  948. // the rest of the tests will still be run.
  949. bool RunAllTests();
  950. // Clears the results of all tests, except the ad hoc tests.
  951. void ClearNonAdHocTestResult() {
  952. ForEach(test_cases_, TestCase::ClearTestCaseResult);
  953. }
  954. // Clears the results of ad-hoc test assertions.
  955. void ClearAdHocTestResult() {
  956. ad_hoc_test_result_.Clear();
  957. }
  958. // Adds a TestProperty to the current TestResult object when invoked in a
  959. // context of a test or a test case, or to the global property set. If the
  960. // result already contains a property with the same key, the value will be
  961. // updated.
  962. void RecordProperty(const TestProperty& test_property);
  963. enum ReactionToSharding {
  964. HONOR_SHARDING_PROTOCOL,
  965. IGNORE_SHARDING_PROTOCOL
  966. };
  967. // Matches the full name of each test against the user-specified
  968. // filter to decide whether the test should run, then records the
  969. // result in each TestCase and TestInfo object.
  970. // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
  971. // based on sharding variables in the environment.
  972. // Returns the number of tests that should run.
  973. int FilterTests(ReactionToSharding shard_tests);
  974. // Prints the names of the tests matching the user-specified filter flag.
  975. void ListTestsMatchingFilter();
  976. const TestCase* current_test_case() const { return current_test_case_; }
  977. TestInfo* current_test_info() { return current_test_info_; }
  978. const TestInfo* current_test_info() const { return current_test_info_; }
  979. // Returns the vector of environments that need to be set-up/torn-down
  980. // before/after the tests are run.
  981. std::vector<Environment*>& environments() { return environments_; }
  982. // Getters for the per-thread Google Test trace stack.
  983. std::vector<TraceInfo>& gtest_trace_stack() {
  984. return *(gtest_trace_stack_.pointer());
  985. }
  986. const std::vector<TraceInfo>& gtest_trace_stack() const {
  987. return gtest_trace_stack_.get();
  988. }
  989. #if GTEST_HAS_DEATH_TEST
  990. void InitDeathTestSubprocessControlInfo() {
  991. internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
  992. }
  993. // Returns a pointer to the parsed --gtest_internal_run_death_test
  994. // flag, or NULL if that flag was not specified.
  995. // This information is useful only in a death test child process.
  996. // Must not be called before a call to InitGoogleTest.
  997. const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
  998. return internal_run_death_test_flag_.get();
  999. }
  1000. // Returns a pointer to the current death test factory.
  1001. internal::DeathTestFactory* death_test_factory() {
  1002. return death_test_factory_.get();
  1003. }
  1004. void SuppressTestEventsIfInSubprocess();
  1005. friend class ReplaceDeathTestFactory;
  1006. #endif // GTEST_HAS_DEATH_TEST
  1007. // Initializes the event listener performing XML output as specified by
  1008. // UnitTestOptions. Must not be called before InitGoogleTest.
  1009. void ConfigureXmlOutput();
  1010. #if GTEST_CAN_STREAM_RESULTS_
  1011. // Initializes the event listener for streaming test results to a socket.
  1012. // Must not be called before InitGoogleTest.
  1013. void ConfigureStreamingOutput();
  1014. #endif
  1015. // Performs initialization dependent upon flag values obtained in
  1016. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  1017. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  1018. // this function is also called from RunAllTests. Since this function can be
  1019. // called more than once, it has to be idempotent.
  1020. void PostFlagParsingInit();
  1021. // Gets the random seed used at the start of the current test iteration.
  1022. int random_seed() const { return random_seed_; }
  1023. // Gets the random number generator.
  1024. internal::Random* random() { return &random_; }
  1025. // Shuffles all test cases, and the tests within each test case,
  1026. // making sure that death tests are still run first.
  1027. void ShuffleTests();
  1028. // Restores the test cases and tests to their order before the first shuffle.
  1029. void UnshuffleTests();
  1030. // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
  1031. // UnitTest::Run() starts.
  1032. bool catch_exceptions() const { return catch_exceptions_; }
  1033. private:
  1034. friend class ::testing::UnitTest;
  1035. // Used by UnitTest::Run() to capture the state of
  1036. // GTEST_FLAG(catch_exceptions) at the moment it starts.
  1037. void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
  1038. // The UnitTest object that owns this implementation object.
  1039. UnitTest* const parent_;
  1040. // The working directory when the first TEST() or TEST_F() was
  1041. // executed.
  1042. internal::FilePath original_working_dir_;
  1043. // The default test part result reporters.
  1044. DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
  1045. DefaultPerThreadTestPartResultReporter
  1046. default_per_thread_test_part_result_reporter_;
  1047. // Points to (but doesn't own) the global test part result reporter.
  1048. TestPartResultReporterInterface* global_test_part_result_repoter_;
  1049. // Protects read and write access to global_test_part_result_reporter_.
  1050. internal::Mutex global_test_part_result_reporter_mutex_;
  1051. // Points to (but doesn't own) the per-thread test part result reporter.
  1052. internal::ThreadLocal<TestPartResultReporterInterface*>
  1053. per_thread_test_part_result_reporter_;
  1054. // The vector of environments that need to be set-up/torn-down
  1055. // before/after the tests are run.
  1056. std::vector<Environment*> environments_;
  1057. // The vector of TestCases in their original order. It owns the
  1058. // elements in the vector.
  1059. std::vector<TestCase*> test_cases_;
  1060. // Provides a level of indirection for the test case list to allow
  1061. // easy shuffling and restoring the test case order. The i-th
  1062. // element of this vector is the index of the i-th test case in the
  1063. // shuffled order.
  1064. std::vector<int> test_case_indices_;
  1065. // ParameterizedTestRegistry object used to register value-parameterized
  1066. // tests.
  1067. internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
  1068. // Indicates whether RegisterParameterizedTests() has been called already.
  1069. bool parameterized_tests_registered_;
  1070. // Index of the last death test case registered. Initially -1.
  1071. int last_death_test_case_;
  1072. // This points to the TestCase for the currently running test. It
  1073. // changes as Google Test goes through one test case after another.
  1074. // When no test is running, this is set to NULL and Google Test
  1075. // stores assertion results in ad_hoc_test_result_. Initially NULL.
  1076. TestCase* current_test_case_;
  1077. // This points to the TestInfo for the currently running test. It
  1078. // changes as Google Test goes through one test after another. When
  1079. // no test is running, this is set to NULL and Google Test stores
  1080. // assertion results in ad_hoc_test_result_. Initially NULL.
  1081. TestInfo* current_test_info_;
  1082. // Normally, a user only writes assertions inside a TEST or TEST_F,
  1083. // or inside a function called by a TEST or TEST_F. Since Google
  1084. // Test keeps track of which test is current running, it can
  1085. // associate such an assertion with the test it belongs to.
  1086. //
  1087. // If an assertion is encountered when no TEST or TEST_F is running,
  1088. // Google Test attributes the assertion result to an imaginary "ad hoc"
  1089. // test, and records the result in ad_hoc_test_result_.
  1090. TestResult ad_hoc_test_result_;
  1091. // The list of event listeners that can be used to track events inside
  1092. // Google Test.
  1093. TestEventListeners listeners_;
  1094. // The OS stack trace getter. Will be deleted when the UnitTest
  1095. // object is destructed. By default, an OsStackTraceGetter is used,
  1096. // but the user can set this field to use a custom getter if that is
  1097. // desired.
  1098. OsStackTraceGetterInterface* os_stack_trace_getter_;
  1099. // True iff PostFlagParsingInit() has been called.
  1100. bool post_flag_parse_init_performed_;
  1101. // The random number seed used at the beginning of the test run.
  1102. int random_seed_;
  1103. // Our random number generator.
  1104. internal::Random random_;
  1105. // The time of the test program start, in ms from the start of the
  1106. // UNIX epoch.
  1107. TimeInMillis start_timestamp_;
  1108. // How long the test took to run, in milliseconds.
  1109. TimeInMillis elapsed_time_;
  1110. #if GTEST_HAS_DEATH_TEST
  1111. // The decomposed components of the gtest_internal_run_death_test flag,
  1112. // parsed when RUN_ALL_TESTS is called.
  1113. internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
  1114. internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
  1115. #endif // GTEST_HAS_DEATH_TEST
  1116. // A per-thread stack of traces created by the SCOPED_TRACE() macro.
  1117. internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
  1118. // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
  1119. // starts.
  1120. bool catch_exceptions_;
  1121. GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
  1122. }; // class UnitTestImpl
  1123. // Convenience function for accessing the global UnitTest
  1124. // implementation object.
  1125. inline UnitTestImpl* GetUnitTestImpl() {
  1126. return UnitTest::GetInstance()->impl();
  1127. }
  1128. #if GTEST_USES_SIMPLE_RE
  1129. // Internal helper functions for implementing the simple regular
  1130. // expression matcher.
  1131. GTEST_API_ bool IsInSet(char ch, const char* str);
  1132. GTEST_API_ bool IsAsciiDigit(char ch);
  1133. GTEST_API_ bool IsAsciiPunct(char ch);
  1134. GTEST_API_ bool IsRepeat(char ch);
  1135. GTEST_API_ bool IsAsciiWhiteSpace(char ch);
  1136. GTEST_API_ bool IsAsciiWordChar(char ch);
  1137. GTEST_API_ bool IsValidEscape(char ch);
  1138. GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
  1139. GTEST_API_ bool ValidateRegex(const char* regex);
  1140. GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
  1141. GTEST_API_ bool MatchRepetitionAndRegexAtHead(
  1142. bool escaped, char ch, char repeat, const char* regex, const char* str);
  1143. GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
  1144. #endif // GTEST_USES_SIMPLE_RE
  1145. // Parses the command line for Google Test flags, without initializing
  1146. // other parts of Google Test.
  1147. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
  1148. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
  1149. #if GTEST_HAS_DEATH_TEST
  1150. // Returns the message describing the last system error, regardless of the
  1151. // platform.
  1152. GTEST_API_ std::string GetLastErrnoDescription();
  1153. // Attempts to parse a string into a positive integer pointed to by the
  1154. // number parameter. Returns true if that is possible.
  1155. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
  1156. // it here.
  1157. template <typename Integer>
  1158. bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
  1159. // Fail fast if the given string does not begin with a digit;
  1160. // this bypasses strtoXXX's "optional leading whitespace and plus
  1161. // or minus sign" semantics, which are undesirable here.
  1162. if (str.empty() || !IsDigit(str[0])) {
  1163. return false;
  1164. }
  1165. errno = 0;
  1166. char* end;
  1167. // BiggestConvertible is the largest integer type that system-provided
  1168. // string-to-number conversion routines can return.
  1169. # if GTEST_OS_WINDOWS && !defined(__GNUC__)
  1170. // MSVC and C++ Builder define __int64 instead of the standard long long.
  1171. typedef unsigned __int64 BiggestConvertible;
  1172. const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
  1173. # else
  1174. typedef unsigned long long BiggestConvertible; // NOLINT
  1175. const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
  1176. # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
  1177. const bool parse_success = *end == '\0' && errno == 0;
  1178. // FIXME: Convert this to compile time assertion when it is
  1179. // available.
  1180. GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
  1181. const Integer result = static_cast<Integer>(parsed);
  1182. if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
  1183. *number = result;
  1184. return true;
  1185. }
  1186. return false;
  1187. }
  1188. #endif // GTEST_HAS_DEATH_TEST
  1189. // TestResult contains some private methods that should be hidden from
  1190. // Google Test user but are required for testing. This class allow our tests
  1191. // to access them.
  1192. //
  1193. // This class is supplied only for the purpose of testing Google Test's own
  1194. // constructs. Do not use it in user tests, either directly or indirectly.
  1195. class TestResultAccessor {
  1196. public:
  1197. static void RecordProperty(TestResult* test_result,
  1198. const std::string& xml_element,
  1199. const TestProperty& property) {
  1200. test_result->RecordProperty(xml_element, property);
  1201. }
  1202. static void ClearTestPartResults(TestResult* test_result) {
  1203. test_result->ClearTestPartResults();
  1204. }
  1205. static const std::vector<testing::TestPartResult>& test_part_results(
  1206. const TestResult& test_result) {
  1207. return test_result.test_part_results();
  1208. }
  1209. };
  1210. #if GTEST_CAN_STREAM_RESULTS_
  1211. // Streams test results to the given port on the given host machine.
  1212. class StreamingListener : public EmptyTestEventListener {
  1213. public:
  1214. // Abstract base class for writing strings to a socket.
  1215. class AbstractSocketWriter {
  1216. public:
  1217. virtual ~AbstractSocketWriter() {}
  1218. // Sends a string to the socket.
  1219. virtual void Send(const std::string& message) = 0;
  1220. // Closes the socket.
  1221. virtual void CloseConnection() {}
  1222. // Sends a string and a newline to the socket.
  1223. void SendLn(const std::string& message) { Send(message + "\n"); }
  1224. };
  1225. // Concrete class for actually writing strings to a socket.
  1226. class SocketWriter : public AbstractSocketWriter {
  1227. public:
  1228. SocketWriter(const std::string& host, const std::string& port)
  1229. : sockfd_(-1), host_name_(host), port_num_(port) {
  1230. MakeConnection();
  1231. }
  1232. virtual ~SocketWriter() {
  1233. if (sockfd_ != -1)
  1234. CloseConnection();
  1235. }
  1236. // Sends a string to the socket.
  1237. virtual void Send(const std::string& message) {
  1238. GTEST_CHECK_(sockfd_ != -1)
  1239. << "Send() can be called only when there is a connection.";
  1240. const int len = static_cast<int>(message.length());
  1241. if (write(sockfd_, message.c_str(), len) != len) {
  1242. GTEST_LOG_(WARNING)
  1243. << "stream_result_to: failed to stream to "
  1244. << host_name_ << ":" << port_num_;
  1245. }
  1246. }
  1247. private:
  1248. // Creates a client socket and connects to the server.
  1249. void MakeConnection();
  1250. // Closes the socket.
  1251. void CloseConnection() {
  1252. GTEST_CHECK_(sockfd_ != -1)
  1253. << "CloseConnection() can be called only when there is a connection.";
  1254. close(sockfd_);
  1255. sockfd_ = -1;
  1256. }
  1257. int sockfd_; // socket file descriptor
  1258. const std::string host_name_;
  1259. const std::string port_num_;
  1260. GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
  1261. }; // class SocketWriter
  1262. // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
  1263. static std::string UrlEncode(const char* str);
  1264. StreamingListener(const std::string& host, const std::string& port)
  1265. : socket_writer_(new SocketWriter(host, port)) {
  1266. Start();
  1267. }
  1268. explicit StreamingListener(AbstractSocketWriter* socket_writer)
  1269. : socket_writer_(socket_writer) { Start(); }
  1270. void OnTestProgramStart(const UnitTest& /* unit_test */) {
  1271. SendLn("event=TestProgramStart");
  1272. }
  1273. void OnTestProgramEnd(const UnitTest& unit_test) {
  1274. // Note that Google Test current only report elapsed time for each
  1275. // test iteration, not for the entire test program.
  1276. SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
  1277. // Notify the streaming server to stop.
  1278. socket_writer_->CloseConnection();
  1279. }
  1280. void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
  1281. SendLn("event=TestIterationStart&iteration=" +
  1282. StreamableToString(iteration));
  1283. }
  1284. void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
  1285. SendLn("event=TestIterationEnd&passed=" +
  1286. FormatBool(unit_test.Passed()) + "&elapsed_time=" +
  1287. StreamableToString(unit_test.elapsed_time()) + "ms");
  1288. }
  1289. void OnTestCaseStart(const TestCase& test_case) {
  1290. SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
  1291. }
  1292. void OnTestCaseEnd(const TestCase& test_case) {
  1293. SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
  1294. + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
  1295. + "ms");
  1296. }
  1297. void OnTestStart(const TestInfo& test_info) {
  1298. SendLn(std::string("event=TestStart&name=") + test_info.name());
  1299. }
  1300. void OnTestEnd(const TestInfo& test_info) {
  1301. SendLn("event=TestEnd&passed=" +
  1302. FormatBool((test_info.result())->Passed()) +
  1303. "&elapsed_time=" +
  1304. StreamableToString((test_info.result())->elapsed_time()) + "ms");
  1305. }
  1306. void OnTestPartResult(const TestPartResult& test_part_result) {
  1307. const char* file_name = test_part_result.file_name();
  1308. if (file_name == NULL)
  1309. file_name = "";
  1310. SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
  1311. "&line=" + StreamableToString(test_part_result.line_number()) +
  1312. "&message=" + UrlEncode(test_part_result.message()));
  1313. }
  1314. private:
  1315. // Sends the given message and a newline to the socket.
  1316. void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
  1317. // Called at the start of streaming to notify the receiver what
  1318. // protocol we are using.
  1319. void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
  1320. std::string FormatBool(bool value) { return value ? "1" : "0"; }
  1321. const scoped_ptr<AbstractSocketWriter> socket_writer_;
  1322. GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
  1323. }; // class StreamingListener
  1324. #endif // GTEST_CAN_STREAM_RESULTS_
  1325. } // namespace internal
  1326. } // namespace testing
  1327. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  1328. #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
  1329. #if GTEST_OS_WINDOWS
  1330. # define vsnprintf _vsnprintf
  1331. #endif // GTEST_OS_WINDOWS
  1332. #if GTEST_OS_MAC
  1333. #ifndef GTEST_OS_IOS
  1334. #include <crt_externs.h>
  1335. #endif
  1336. #endif
  1337. #if GTEST_HAS_ABSL
  1338. #include "absl/debugging/failure_signal_handler.h"
  1339. #include "absl/debugging/stacktrace.h"
  1340. #include "absl/debugging/symbolize.h"
  1341. #include "absl/strings/str_cat.h"
  1342. #endif // GTEST_HAS_ABSL
  1343. namespace testing {
  1344. using internal::CountIf;
  1345. using internal::ForEach;
  1346. using internal::GetElementOr;
  1347. using internal::Shuffle;
  1348. // Constants.
  1349. // A test whose test case name or test name matches this filter is
  1350. // disabled and not run.
  1351. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
  1352. // A test case whose name matches this filter is considered a death
  1353. // test case and will be run before test cases whose name doesn't
  1354. // match this filter.
  1355. static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
  1356. // A test filter that matches everything.
  1357. static const char kUniversalFilter[] = "*";
  1358. // The default output format.
  1359. static const char kDefaultOutputFormat[] = "xml";
  1360. // The default output file.
  1361. static const char kDefaultOutputFile[] = "test_detail";
  1362. // The environment variable name for the test shard index.
  1363. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
  1364. // The environment variable name for the total number of test shards.
  1365. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
  1366. // The environment variable name for the test shard status file.
  1367. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
  1368. namespace internal {
  1369. // The text used in failure messages to indicate the start of the
  1370. // stack trace.
  1371. const char kStackTraceMarker[] = "\nStack trace:\n";
  1372. // g_help_flag is true iff the --help flag or an equivalent form is
  1373. // specified on the command line.
  1374. bool g_help_flag = false;
  1375. // Utilty function to Open File for Writing
  1376. static FILE* OpenFileForWriting(const std::string& output_file) {
  1377. FILE* fileout = NULL;
  1378. FilePath output_file_path(output_file);
  1379. FilePath output_dir(output_file_path.RemoveFileName());
  1380. if (output_dir.CreateDirectoriesRecursively()) {
  1381. fileout = posix::FOpen(output_file.c_str(), "w");
  1382. }
  1383. if (fileout == NULL) {
  1384. GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
  1385. }
  1386. return fileout;
  1387. }
  1388. } // namespace internal
  1389. // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
  1390. // environment variable.
  1391. static const char* GetDefaultFilter() {
  1392. const char* const testbridge_test_only =
  1393. internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
  1394. if (testbridge_test_only != NULL) {
  1395. return testbridge_test_only;
  1396. }
  1397. return kUniversalFilter;
  1398. }
  1399. GTEST_DEFINE_bool_(
  1400. also_run_disabled_tests,
  1401. internal::BoolFromGTestEnv("also_run_disabled_tests", false),
  1402. "Run disabled tests too, in addition to the tests normally being run.");
  1403. GTEST_DEFINE_bool_(
  1404. break_on_failure,
  1405. internal::BoolFromGTestEnv("break_on_failure", false),
  1406. "True iff a failed assertion should be a debugger break-point.");
  1407. GTEST_DEFINE_bool_(
  1408. catch_exceptions,
  1409. internal::BoolFromGTestEnv("catch_exceptions", true),
  1410. "True iff " GTEST_NAME_
  1411. " should catch exceptions and treat them as test failures.");
  1412. GTEST_DEFINE_string_(
  1413. color,
  1414. internal::StringFromGTestEnv("color", "auto"),
  1415. "Whether to use colors in the output. Valid values: yes, no, "
  1416. "and auto. 'auto' means to use colors if the output is "
  1417. "being sent to a terminal and the TERM environment variable "
  1418. "is set to a terminal type that supports colors.");
  1419. GTEST_DEFINE_string_(
  1420. filter,
  1421. internal::StringFromGTestEnv("filter", GetDefaultFilter()),
  1422. "A colon-separated list of glob (not regex) patterns "
  1423. "for filtering the tests to run, optionally followed by a "
  1424. "'-' and a : separated list of negative patterns (tests to "
  1425. "exclude). A test is run if it matches one of the positive "
  1426. "patterns and does not match any of the negative patterns.");
  1427. GTEST_DEFINE_bool_(
  1428. install_failure_signal_handler,
  1429. internal::BoolFromGTestEnv("install_failure_signal_handler", false),
  1430. "If true and supported on the current platform, " GTEST_NAME_ " should "
  1431. "install a signal handler that dumps debugging information when fatal "
  1432. "signals are raised.");
  1433. GTEST_DEFINE_bool_(list_tests, false,
  1434. "List all tests without running them.");
  1435. // The net priority order after flag processing is thus:
  1436. // --gtest_output command line flag
  1437. // GTEST_OUTPUT environment variable
  1438. // XML_OUTPUT_FILE environment variable
  1439. // ''
  1440. GTEST_DEFINE_string_(
  1441. output,
  1442. internal::StringFromGTestEnv("output",
  1443. internal::OutputFlagAlsoCheckEnvVar().c_str()),
  1444. "A format (defaults to \"xml\" but can be specified to be \"json\"), "
  1445. "optionally followed by a colon and an output file name or directory. "
  1446. "A directory is indicated by a trailing pathname separator. "
  1447. "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
  1448. "If a directory is specified, output files will be created "
  1449. "within that directory, with file-names based on the test "
  1450. "executable's name and, if necessary, made unique by adding "
  1451. "digits.");
  1452. GTEST_DEFINE_bool_(
  1453. print_time,
  1454. internal::BoolFromGTestEnv("print_time", true),
  1455. "True iff " GTEST_NAME_
  1456. " should display elapsed time in text output.");
  1457. GTEST_DEFINE_bool_(
  1458. print_utf8,
  1459. internal::BoolFromGTestEnv("print_utf8", true),
  1460. "True iff " GTEST_NAME_
  1461. " prints UTF8 characters as text.");
  1462. GTEST_DEFINE_int32_(
  1463. random_seed,
  1464. internal::Int32FromGTestEnv("random_seed", 0),
  1465. "Random number seed to use when shuffling test orders. Must be in range "
  1466. "[1, 99999], or 0 to use a seed based on the current time.");
  1467. GTEST_DEFINE_int32_(
  1468. repeat,
  1469. internal::Int32FromGTestEnv("repeat", 1),
  1470. "How many times to repeat each test. Specify a negative number "
  1471. "for repeating forever. Useful for shaking out flaky tests.");
  1472. GTEST_DEFINE_bool_(
  1473. show_internal_stack_frames, false,
  1474. "True iff " GTEST_NAME_ " should include internal stack frames when "
  1475. "printing test failure stack traces.");
  1476. GTEST_DEFINE_bool_(
  1477. shuffle,
  1478. internal::BoolFromGTestEnv("shuffle", false),
  1479. "True iff " GTEST_NAME_
  1480. " should randomize tests' order on every run.");
  1481. GTEST_DEFINE_int32_(
  1482. stack_trace_depth,
  1483. internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
  1484. "The maximum number of stack frames to print when an "
  1485. "assertion fails. The valid range is 0 through 100, inclusive.");
  1486. GTEST_DEFINE_string_(
  1487. stream_result_to,
  1488. internal::StringFromGTestEnv("stream_result_to", ""),
  1489. "This flag specifies the host name and the port number on which to stream "
  1490. "test results. Example: \"localhost:555\". The flag is effective only on "
  1491. "Linux.");
  1492. GTEST_DEFINE_bool_(
  1493. throw_on_failure,
  1494. internal::BoolFromGTestEnv("throw_on_failure", false),
  1495. "When this flag is specified, a failed assertion will throw an exception "
  1496. "if exceptions are enabled or exit the program with a non-zero code "
  1497. "otherwise. For use with an external test framework.");
  1498. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  1499. GTEST_DEFINE_string_(
  1500. flagfile,
  1501. internal::StringFromGTestEnv("flagfile", ""),
  1502. "This flag specifies the flagfile to read command-line flags from.");
  1503. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  1504. namespace internal {
  1505. // Generates a random number from [0, range), using a Linear
  1506. // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
  1507. // than kMaxRange.
  1508. UInt32 Random::Generate(UInt32 range) {
  1509. // These constants are the same as are used in glibc's rand(3).
  1510. // Use wider types than necessary to prevent unsigned overflow diagnostics.
  1511. state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange;
  1512. GTEST_CHECK_(range > 0)
  1513. << "Cannot generate a number in the range [0, 0).";
  1514. GTEST_CHECK_(range <= kMaxRange)
  1515. << "Generation of a number in [0, " << range << ") was requested, "
  1516. << "but this can only generate numbers in [0, " << kMaxRange << ").";
  1517. // Converting via modulus introduces a bit of downward bias, but
  1518. // it's simple, and a linear congruential generator isn't too good
  1519. // to begin with.
  1520. return state_ % range;
  1521. }
  1522. // GTestIsInitialized() returns true iff the user has initialized
  1523. // Google Test. Useful for catching the user mistake of not initializing
  1524. // Google Test before calling RUN_ALL_TESTS().
  1525. static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
  1526. // Iterates over a vector of TestCases, keeping a running sum of the
  1527. // results of calling a given int-returning method on each.
  1528. // Returns the sum.
  1529. static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
  1530. int (TestCase::*method)() const) {
  1531. int sum = 0;
  1532. for (size_t i = 0; i < case_list.size(); i++) {
  1533. sum += (case_list[i]->*method)();
  1534. }
  1535. return sum;
  1536. }
  1537. // Returns true iff the test case passed.
  1538. static bool TestCasePassed(const TestCase* test_case) {
  1539. return test_case->should_run() && test_case->Passed();
  1540. }
  1541. // Returns true iff the test case failed.
  1542. static bool TestCaseFailed(const TestCase* test_case) {
  1543. return test_case->should_run() && test_case->Failed();
  1544. }
  1545. // Returns true iff test_case contains at least one test that should
  1546. // run.
  1547. static bool ShouldRunTestCase(const TestCase* test_case) {
  1548. return test_case->should_run();
  1549. }
  1550. // AssertHelper constructor.
  1551. AssertHelper::AssertHelper(TestPartResult::Type type,
  1552. const char* file,
  1553. int line,
  1554. const char* message)
  1555. : data_(new AssertHelperData(type, file, line, message)) {
  1556. }
  1557. AssertHelper::~AssertHelper() {
  1558. delete data_;
  1559. }
  1560. // Message assignment, for assertion streaming support.
  1561. void AssertHelper::operator=(const Message& message) const {
  1562. UnitTest::GetInstance()->
  1563. AddTestPartResult(data_->type, data_->file, data_->line,
  1564. AppendUserMessage(data_->message, message),
  1565. UnitTest::GetInstance()->impl()
  1566. ->CurrentOsStackTraceExceptTop(1)
  1567. // Skips the stack frame for this function itself.
  1568. ); // NOLINT
  1569. }
  1570. // Mutex for linked pointers.
  1571. GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
  1572. // A copy of all command line arguments. Set by InitGoogleTest().
  1573. static ::std::vector<std::string> g_argvs;
  1574. ::std::vector<std::string> GetArgvs() {
  1575. #if defined(GTEST_CUSTOM_GET_ARGVS_)
  1576. // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
  1577. // ::string. This code converts it to the appropriate type.
  1578. const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
  1579. return ::std::vector<std::string>(custom.begin(), custom.end());
  1580. #else // defined(GTEST_CUSTOM_GET_ARGVS_)
  1581. return g_argvs;
  1582. #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
  1583. }
  1584. // Returns the current application's name, removing directory path if that
  1585. // is present.
  1586. FilePath GetCurrentExecutableName() {
  1587. FilePath result;
  1588. #if GTEST_OS_WINDOWS
  1589. result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
  1590. #else
  1591. result.Set(FilePath(GetArgvs()[0]));
  1592. #endif // GTEST_OS_WINDOWS
  1593. return result.RemoveDirectoryName();
  1594. }
  1595. // Functions for processing the gtest_output flag.
  1596. // Returns the output format, or "" for normal printed output.
  1597. std::string UnitTestOptions::GetOutputFormat() {
  1598. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1599. const char* const colon = strchr(gtest_output_flag, ':');
  1600. return (colon == NULL) ?
  1601. std::string(gtest_output_flag) :
  1602. std::string(gtest_output_flag, colon - gtest_output_flag);
  1603. }
  1604. // Returns the name of the requested output file, or the default if none
  1605. // was explicitly specified.
  1606. std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
  1607. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1608. std::string format = GetOutputFormat();
  1609. if (format.empty())
  1610. format = std::string(kDefaultOutputFormat);
  1611. const char* const colon = strchr(gtest_output_flag, ':');
  1612. if (colon == NULL)
  1613. return internal::FilePath::MakeFileName(
  1614. internal::FilePath(
  1615. UnitTest::GetInstance()->original_working_dir()),
  1616. internal::FilePath(kDefaultOutputFile), 0,
  1617. format.c_str()).string();
  1618. internal::FilePath output_name(colon + 1);
  1619. if (!output_name.IsAbsolutePath())
  1620. // FIXME: on Windows \some\path is not an absolute
  1621. // path (as its meaning depends on the current drive), yet the
  1622. // following logic for turning it into an absolute path is wrong.
  1623. // Fix it.
  1624. output_name = internal::FilePath::ConcatPaths(
  1625. internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
  1626. internal::FilePath(colon + 1));
  1627. if (!output_name.IsDirectory())
  1628. return output_name.string();
  1629. internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
  1630. output_name, internal::GetCurrentExecutableName(),
  1631. GetOutputFormat().c_str()));
  1632. return result.string();
  1633. }
  1634. // Returns true iff the wildcard pattern matches the string. The
  1635. // first ':' or '\0' character in pattern marks the end of it.
  1636. //
  1637. // This recursive algorithm isn't very efficient, but is clear and
  1638. // works well enough for matching test names, which are short.
  1639. bool UnitTestOptions::PatternMatchesString(const char *pattern,
  1640. const char *str) {
  1641. switch (*pattern) {
  1642. case '\0':
  1643. case ':': // Either ':' or '\0' marks the end of the pattern.
  1644. return *str == '\0';
  1645. case '?': // Matches any single character.
  1646. return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
  1647. case '*': // Matches any string (possibly empty) of characters.
  1648. return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
  1649. PatternMatchesString(pattern + 1, str);
  1650. default: // Non-special character. Matches itself.
  1651. return *pattern == *str &&
  1652. PatternMatchesString(pattern + 1, str + 1);
  1653. }
  1654. }
  1655. bool UnitTestOptions::MatchesFilter(
  1656. const std::string& name, const char* filter) {
  1657. const char *cur_pattern = filter;
  1658. for (;;) {
  1659. if (PatternMatchesString(cur_pattern, name.c_str())) {
  1660. return true;
  1661. }
  1662. // Finds the next pattern in the filter.
  1663. cur_pattern = strchr(cur_pattern, ':');
  1664. // Returns if no more pattern can be found.
  1665. if (cur_pattern == NULL) {
  1666. return false;
  1667. }
  1668. // Skips the pattern separater (the ':' character).
  1669. cur_pattern++;
  1670. }
  1671. }
  1672. // Returns true iff the user-specified filter matches the test case
  1673. // name and the test name.
  1674. bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
  1675. const std::string &test_name) {
  1676. const std::string& full_name = test_case_name + "." + test_name.c_str();
  1677. // Split --gtest_filter at '-', if there is one, to separate into
  1678. // positive filter and negative filter portions
  1679. const char* const p = GTEST_FLAG(filter).c_str();
  1680. const char* const dash = strchr(p, '-');
  1681. std::string positive;
  1682. std::string negative;
  1683. if (dash == NULL) {
  1684. positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
  1685. negative = "";
  1686. } else {
  1687. positive = std::string(p, dash); // Everything up to the dash
  1688. negative = std::string(dash + 1); // Everything after the dash
  1689. if (positive.empty()) {
  1690. // Treat '-test1' as the same as '*-test1'
  1691. positive = kUniversalFilter;
  1692. }
  1693. }
  1694. // A filter is a colon-separated list of patterns. It matches a
  1695. // test if any pattern in it matches the test.
  1696. return (MatchesFilter(full_name, positive.c_str()) &&
  1697. !MatchesFilter(full_name, negative.c_str()));
  1698. }
  1699. #if GTEST_HAS_SEH
  1700. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  1701. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  1702. // This function is useful as an __except condition.
  1703. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
  1704. // Google Test should handle a SEH exception if:
  1705. // 1. the user wants it to, AND
  1706. // 2. this is not a breakpoint exception, AND
  1707. // 3. this is not a C++ exception (VC++ implements them via SEH,
  1708. // apparently).
  1709. //
  1710. // SEH exception code for C++ exceptions.
  1711. // (see http://support.microsoft.com/kb/185294 for more information).
  1712. const DWORD kCxxExceptionCode = 0xe06d7363;
  1713. bool should_handle = true;
  1714. if (!GTEST_FLAG(catch_exceptions))
  1715. should_handle = false;
  1716. else if (exception_code == EXCEPTION_BREAKPOINT)
  1717. should_handle = false;
  1718. else if (exception_code == kCxxExceptionCode)
  1719. should_handle = false;
  1720. return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
  1721. }
  1722. #endif // GTEST_HAS_SEH
  1723. } // namespace internal
  1724. // The c'tor sets this object as the test part result reporter used by
  1725. // Google Test. The 'result' parameter specifies where to report the
  1726. // results. Intercepts only failures from the current thread.
  1727. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1728. TestPartResultArray* result)
  1729. : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
  1730. result_(result) {
  1731. Init();
  1732. }
  1733. // The c'tor sets this object as the test part result reporter used by
  1734. // Google Test. The 'result' parameter specifies where to report the
  1735. // results.
  1736. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1737. InterceptMode intercept_mode, TestPartResultArray* result)
  1738. : intercept_mode_(intercept_mode),
  1739. result_(result) {
  1740. Init();
  1741. }
  1742. void ScopedFakeTestPartResultReporter::Init() {
  1743. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1744. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1745. old_reporter_ = impl->GetGlobalTestPartResultReporter();
  1746. impl->SetGlobalTestPartResultReporter(this);
  1747. } else {
  1748. old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
  1749. impl->SetTestPartResultReporterForCurrentThread(this);
  1750. }
  1751. }
  1752. // The d'tor restores the test part result reporter used by Google Test
  1753. // before.
  1754. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
  1755. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1756. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1757. impl->SetGlobalTestPartResultReporter(old_reporter_);
  1758. } else {
  1759. impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
  1760. }
  1761. }
  1762. // Increments the test part result count and remembers the result.
  1763. // This method is from the TestPartResultReporterInterface interface.
  1764. void ScopedFakeTestPartResultReporter::ReportTestPartResult(
  1765. const TestPartResult& result) {
  1766. result_->Append(result);
  1767. }
  1768. namespace internal {
  1769. // Returns the type ID of ::testing::Test. We should always call this
  1770. // instead of GetTypeId< ::testing::Test>() to get the type ID of
  1771. // testing::Test. This is to work around a suspected linker bug when
  1772. // using Google Test as a framework on Mac OS X. The bug causes
  1773. // GetTypeId< ::testing::Test>() to return different values depending
  1774. // on whether the call is from the Google Test framework itself or
  1775. // from user test code. GetTestTypeId() is guaranteed to always
  1776. // return the same value, as it always calls GetTypeId<>() from the
  1777. // gtest.cc, which is within the Google Test framework.
  1778. TypeId GetTestTypeId() {
  1779. return GetTypeId<Test>();
  1780. }
  1781. // The value of GetTestTypeId() as seen from within the Google Test
  1782. // library. This is solely for testing GetTestTypeId().
  1783. extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
  1784. // This predicate-formatter checks that 'results' contains a test part
  1785. // failure of the given type and that the failure message contains the
  1786. // given substring.
  1787. static AssertionResult HasOneFailure(const char* /* results_expr */,
  1788. const char* /* type_expr */,
  1789. const char* /* substr_expr */,
  1790. const TestPartResultArray& results,
  1791. TestPartResult::Type type,
  1792. const std::string& substr) {
  1793. const std::string expected(type == TestPartResult::kFatalFailure ?
  1794. "1 fatal failure" :
  1795. "1 non-fatal failure");
  1796. Message msg;
  1797. if (results.size() != 1) {
  1798. msg << "Expected: " << expected << "\n"
  1799. << " Actual: " << results.size() << " failures";
  1800. for (int i = 0; i < results.size(); i++) {
  1801. msg << "\n" << results.GetTestPartResult(i);
  1802. }
  1803. return AssertionFailure() << msg;
  1804. }
  1805. const TestPartResult& r = results.GetTestPartResult(0);
  1806. if (r.type() != type) {
  1807. return AssertionFailure() << "Expected: " << expected << "\n"
  1808. << " Actual:\n"
  1809. << r;
  1810. }
  1811. if (strstr(r.message(), substr.c_str()) == NULL) {
  1812. return AssertionFailure() << "Expected: " << expected << " containing \""
  1813. << substr << "\"\n"
  1814. << " Actual:\n"
  1815. << r;
  1816. }
  1817. return AssertionSuccess();
  1818. }
  1819. // The constructor of SingleFailureChecker remembers where to look up
  1820. // test part results, what type of failure we expect, and what
  1821. // substring the failure message should contain.
  1822. SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
  1823. TestPartResult::Type type,
  1824. const std::string& substr)
  1825. : results_(results), type_(type), substr_(substr) {}
  1826. // The destructor of SingleFailureChecker verifies that the given
  1827. // TestPartResultArray contains exactly one failure that has the given
  1828. // type and contains the given substring. If that's not the case, a
  1829. // non-fatal failure will be generated.
  1830. SingleFailureChecker::~SingleFailureChecker() {
  1831. EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
  1832. }
  1833. DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
  1834. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  1835. void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
  1836. const TestPartResult& result) {
  1837. unit_test_->current_test_result()->AddTestPartResult(result);
  1838. unit_test_->listeners()->repeater()->OnTestPartResult(result);
  1839. }
  1840. DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
  1841. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  1842. void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
  1843. const TestPartResult& result) {
  1844. unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
  1845. }
  1846. // Returns the global test part result reporter.
  1847. TestPartResultReporterInterface*
  1848. UnitTestImpl::GetGlobalTestPartResultReporter() {
  1849. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  1850. return global_test_part_result_repoter_;
  1851. }
  1852. // Sets the global test part result reporter.
  1853. void UnitTestImpl::SetGlobalTestPartResultReporter(
  1854. TestPartResultReporterInterface* reporter) {
  1855. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  1856. global_test_part_result_repoter_ = reporter;
  1857. }
  1858. // Returns the test part result reporter for the current thread.
  1859. TestPartResultReporterInterface*
  1860. UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
  1861. return per_thread_test_part_result_reporter_.get();
  1862. }
  1863. // Sets the test part result reporter for the current thread.
  1864. void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
  1865. TestPartResultReporterInterface* reporter) {
  1866. per_thread_test_part_result_reporter_.set(reporter);
  1867. }
  1868. // Gets the number of successful test cases.
  1869. int UnitTestImpl::successful_test_case_count() const {
  1870. return CountIf(test_cases_, TestCasePassed);
  1871. }
  1872. // Gets the number of failed test cases.
  1873. int UnitTestImpl::failed_test_case_count() const {
  1874. return CountIf(test_cases_, TestCaseFailed);
  1875. }
  1876. // Gets the number of all test cases.
  1877. int UnitTestImpl::total_test_case_count() const {
  1878. return static_cast<int>(test_cases_.size());
  1879. }
  1880. // Gets the number of all test cases that contain at least one test
  1881. // that should run.
  1882. int UnitTestImpl::test_case_to_run_count() const {
  1883. return CountIf(test_cases_, ShouldRunTestCase);
  1884. }
  1885. // Gets the number of successful tests.
  1886. int UnitTestImpl::successful_test_count() const {
  1887. return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
  1888. }
  1889. // Gets the number of failed tests.
  1890. int UnitTestImpl::failed_test_count() const {
  1891. return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
  1892. }
  1893. // Gets the number of disabled tests that will be reported in the XML report.
  1894. int UnitTestImpl::reportable_disabled_test_count() const {
  1895. return SumOverTestCaseList(test_cases_,
  1896. &TestCase::reportable_disabled_test_count);
  1897. }
  1898. // Gets the number of disabled tests.
  1899. int UnitTestImpl::disabled_test_count() const {
  1900. return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
  1901. }
  1902. // Gets the number of tests to be printed in the XML report.
  1903. int UnitTestImpl::reportable_test_count() const {
  1904. return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
  1905. }
  1906. // Gets the number of all tests.
  1907. int UnitTestImpl::total_test_count() const {
  1908. return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
  1909. }
  1910. // Gets the number of tests that should run.
  1911. int UnitTestImpl::test_to_run_count() const {
  1912. return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
  1913. }
  1914. // Returns the current OS stack trace as an std::string.
  1915. //
  1916. // The maximum number of stack frames to be included is specified by
  1917. // the gtest_stack_trace_depth flag. The skip_count parameter
  1918. // specifies the number of top frames to be skipped, which doesn't
  1919. // count against the number of frames to be included.
  1920. //
  1921. // For example, if Foo() calls Bar(), which in turn calls
  1922. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  1923. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  1924. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
  1925. return os_stack_trace_getter()->CurrentStackTrace(
  1926. static_cast<int>(GTEST_FLAG(stack_trace_depth)),
  1927. skip_count + 1
  1928. // Skips the user-specified number of frames plus this function
  1929. // itself.
  1930. ); // NOLINT
  1931. }
  1932. // Returns the current time in milliseconds.
  1933. TimeInMillis GetTimeInMillis() {
  1934. #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
  1935. // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
  1936. // http://analogous.blogspot.com/2005/04/epoch.html
  1937. const TimeInMillis kJavaEpochToWinFileTimeDelta =
  1938. static_cast<TimeInMillis>(116444736UL) * 100000UL;
  1939. const DWORD kTenthMicrosInMilliSecond = 10000;
  1940. SYSTEMTIME now_systime;
  1941. FILETIME now_filetime;
  1942. ULARGE_INTEGER now_int64;
  1943. // FIXME: Shouldn't this just use
  1944. // GetSystemTimeAsFileTime()?
  1945. GetSystemTime(&now_systime);
  1946. if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
  1947. now_int64.LowPart = now_filetime.dwLowDateTime;
  1948. now_int64.HighPart = now_filetime.dwHighDateTime;
  1949. now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
  1950. kJavaEpochToWinFileTimeDelta;
  1951. return now_int64.QuadPart;
  1952. }
  1953. return 0;
  1954. #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
  1955. __timeb64 now;
  1956. // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
  1957. // (deprecated function) there.
  1958. // FIXME: Use GetTickCount()? Or use
  1959. // SystemTimeToFileTime()
  1960. GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
  1961. _ftime64(&now);
  1962. GTEST_DISABLE_MSC_DEPRECATED_POP_()
  1963. return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
  1964. #elif GTEST_HAS_GETTIMEOFDAY_
  1965. struct timeval now;
  1966. gettimeofday(&now, NULL);
  1967. return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
  1968. #else
  1969. # error "Don't know how to get the current time on your system."
  1970. #endif
  1971. }
  1972. // Utilities
  1973. // class String.
  1974. #if GTEST_OS_WINDOWS_MOBILE
  1975. // Creates a UTF-16 wide string from the given ANSI string, allocating
  1976. // memory using new. The caller is responsible for deleting the return
  1977. // value using delete[]. Returns the wide string, or NULL if the
  1978. // input is NULL.
  1979. LPCWSTR String::AnsiToUtf16(const char* ansi) {
  1980. if (!ansi) return NULL;
  1981. const int length = strlen(ansi);
  1982. const int unicode_length =
  1983. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  1984. NULL, 0);
  1985. WCHAR* unicode = new WCHAR[unicode_length + 1];
  1986. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  1987. unicode, unicode_length);
  1988. unicode[unicode_length] = 0;
  1989. return unicode;
  1990. }
  1991. // Creates an ANSI string from the given wide string, allocating
  1992. // memory using new. The caller is responsible for deleting the return
  1993. // value using delete[]. Returns the ANSI string, or NULL if the
  1994. // input is NULL.
  1995. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
  1996. if (!utf16_str) return NULL;
  1997. const int ansi_length =
  1998. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  1999. NULL, 0, NULL, NULL);
  2000. char* ansi = new char[ansi_length + 1];
  2001. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  2002. ansi, ansi_length, NULL, NULL);
  2003. ansi[ansi_length] = 0;
  2004. return ansi;
  2005. }
  2006. #endif // GTEST_OS_WINDOWS_MOBILE
  2007. // Compares two C strings. Returns true iff they have the same content.
  2008. //
  2009. // Unlike strcmp(), this function can handle NULL argument(s). A NULL
  2010. // C string is considered different to any non-NULL C string,
  2011. // including the empty string.
  2012. bool String::CStringEquals(const char * lhs, const char * rhs) {
  2013. if ( lhs == NULL ) return rhs == NULL;
  2014. if ( rhs == NULL ) return false;
  2015. return strcmp(lhs, rhs) == 0;
  2016. }
  2017. #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  2018. // Converts an array of wide chars to a narrow string using the UTF-8
  2019. // encoding, and streams the result to the given Message object.
  2020. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
  2021. Message* msg) {
  2022. for (size_t i = 0; i != length; ) { // NOLINT
  2023. if (wstr[i] != L'\0') {
  2024. *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
  2025. while (i != length && wstr[i] != L'\0')
  2026. i++;
  2027. } else {
  2028. *msg << '\0';
  2029. i++;
  2030. }
  2031. }
  2032. }
  2033. #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  2034. void SplitString(const ::std::string& str, char delimiter,
  2035. ::std::vector< ::std::string>* dest) {
  2036. ::std::vector< ::std::string> parsed;
  2037. ::std::string::size_type pos = 0;
  2038. while (::testing::internal::AlwaysTrue()) {
  2039. const ::std::string::size_type colon = str.find(delimiter, pos);
  2040. if (colon == ::std::string::npos) {
  2041. parsed.push_back(str.substr(pos));
  2042. break;
  2043. } else {
  2044. parsed.push_back(str.substr(pos, colon - pos));
  2045. pos = colon + 1;
  2046. }
  2047. }
  2048. dest->swap(parsed);
  2049. }
  2050. } // namespace internal
  2051. // Constructs an empty Message.
  2052. // We allocate the stringstream separately because otherwise each use of
  2053. // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
  2054. // stack frame leading to huge stack frames in some cases; gcc does not reuse
  2055. // the stack space.
  2056. Message::Message() : ss_(new ::std::stringstream) {
  2057. // By default, we want there to be enough precision when printing
  2058. // a double to a Message.
  2059. *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
  2060. }
  2061. // These two overloads allow streaming a wide C string to a Message
  2062. // using the UTF-8 encoding.
  2063. Message& Message::operator <<(const wchar_t* wide_c_str) {
  2064. return *this << internal::String::ShowWideCString(wide_c_str);
  2065. }
  2066. Message& Message::operator <<(wchar_t* wide_c_str) {
  2067. return *this << internal::String::ShowWideCString(wide_c_str);
  2068. }
  2069. #if GTEST_HAS_STD_WSTRING
  2070. // Converts the given wide string to a narrow string using the UTF-8
  2071. // encoding, and streams the result to this Message object.
  2072. Message& Message::operator <<(const ::std::wstring& wstr) {
  2073. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  2074. return *this;
  2075. }
  2076. #endif // GTEST_HAS_STD_WSTRING
  2077. #if GTEST_HAS_GLOBAL_WSTRING
  2078. // Converts the given wide string to a narrow string using the UTF-8
  2079. // encoding, and streams the result to this Message object.
  2080. Message& Message::operator <<(const ::wstring& wstr) {
  2081. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  2082. return *this;
  2083. }
  2084. #endif // GTEST_HAS_GLOBAL_WSTRING
  2085. // Gets the text streamed to this object so far as an std::string.
  2086. // Each '\0' character in the buffer is replaced with "\\0".
  2087. std::string Message::GetString() const {
  2088. return internal::StringStreamToString(ss_.get());
  2089. }
  2090. // AssertionResult constructors.
  2091. // Used in EXPECT_TRUE/FALSE(assertion_result).
  2092. AssertionResult::AssertionResult(const AssertionResult& other)
  2093. : success_(other.success_),
  2094. message_(other.message_.get() != NULL ?
  2095. new ::std::string(*other.message_) :
  2096. static_cast< ::std::string*>(NULL)) {
  2097. }
  2098. // Swaps two AssertionResults.
  2099. void AssertionResult::swap(AssertionResult& other) {
  2100. using std::swap;
  2101. swap(success_, other.success_);
  2102. swap(message_, other.message_);
  2103. }
  2104. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  2105. AssertionResult AssertionResult::operator!() const {
  2106. AssertionResult negation(!success_);
  2107. if (message_.get() != NULL)
  2108. negation << *message_;
  2109. return negation;
  2110. }
  2111. // Makes a successful assertion result.
  2112. AssertionResult AssertionSuccess() {
  2113. return AssertionResult(true);
  2114. }
  2115. // Makes a failed assertion result.
  2116. AssertionResult AssertionFailure() {
  2117. return AssertionResult(false);
  2118. }
  2119. // Makes a failed assertion result with the given failure message.
  2120. // Deprecated; use AssertionFailure() << message.
  2121. AssertionResult AssertionFailure(const Message& message) {
  2122. return AssertionFailure() << message;
  2123. }
  2124. namespace internal {
  2125. namespace edit_distance {
  2126. std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
  2127. const std::vector<size_t>& right) {
  2128. std::vector<std::vector<double> > costs(
  2129. left.size() + 1, std::vector<double>(right.size() + 1));
  2130. std::vector<std::vector<EditType> > best_move(
  2131. left.size() + 1, std::vector<EditType>(right.size() + 1));
  2132. // Populate for empty right.
  2133. for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
  2134. costs[l_i][0] = static_cast<double>(l_i);
  2135. best_move[l_i][0] = kRemove;
  2136. }
  2137. // Populate for empty left.
  2138. for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
  2139. costs[0][r_i] = static_cast<double>(r_i);
  2140. best_move[0][r_i] = kAdd;
  2141. }
  2142. for (size_t l_i = 0; l_i < left.size(); ++l_i) {
  2143. for (size_t r_i = 0; r_i < right.size(); ++r_i) {
  2144. if (left[l_i] == right[r_i]) {
  2145. // Found a match. Consume it.
  2146. costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
  2147. best_move[l_i + 1][r_i + 1] = kMatch;
  2148. continue;
  2149. }
  2150. const double add = costs[l_i + 1][r_i];
  2151. const double remove = costs[l_i][r_i + 1];
  2152. const double replace = costs[l_i][r_i];
  2153. if (add < remove && add < replace) {
  2154. costs[l_i + 1][r_i + 1] = add + 1;
  2155. best_move[l_i + 1][r_i + 1] = kAdd;
  2156. } else if (remove < add && remove < replace) {
  2157. costs[l_i + 1][r_i + 1] = remove + 1;
  2158. best_move[l_i + 1][r_i + 1] = kRemove;
  2159. } else {
  2160. // We make replace a little more expensive than add/remove to lower
  2161. // their priority.
  2162. costs[l_i + 1][r_i + 1] = replace + 1.00001;
  2163. best_move[l_i + 1][r_i + 1] = kReplace;
  2164. }
  2165. }
  2166. }
  2167. // Reconstruct the best path. We do it in reverse order.
  2168. std::vector<EditType> best_path;
  2169. for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
  2170. EditType move = best_move[l_i][r_i];
  2171. best_path.push_back(move);
  2172. l_i -= move != kAdd;
  2173. r_i -= move != kRemove;
  2174. }
  2175. std::reverse(best_path.begin(), best_path.end());
  2176. return best_path;
  2177. }
  2178. namespace {
  2179. // Helper class to convert string into ids with deduplication.
  2180. class InternalStrings {
  2181. public:
  2182. size_t GetId(const std::string& str) {
  2183. IdMap::iterator it = ids_.find(str);
  2184. if (it != ids_.end()) return it->second;
  2185. size_t id = ids_.size();
  2186. return ids_[str] = id;
  2187. }
  2188. private:
  2189. typedef std::map<std::string, size_t> IdMap;
  2190. IdMap ids_;
  2191. };
  2192. } // namespace
  2193. std::vector<EditType> CalculateOptimalEdits(
  2194. const std::vector<std::string>& left,
  2195. const std::vector<std::string>& right) {
  2196. std::vector<size_t> left_ids, right_ids;
  2197. {
  2198. InternalStrings intern_table;
  2199. for (size_t i = 0; i < left.size(); ++i) {
  2200. left_ids.push_back(intern_table.GetId(left[i]));
  2201. }
  2202. for (size_t i = 0; i < right.size(); ++i) {
  2203. right_ids.push_back(intern_table.GetId(right[i]));
  2204. }
  2205. }
  2206. return CalculateOptimalEdits(left_ids, right_ids);
  2207. }
  2208. namespace {
  2209. // Helper class that holds the state for one hunk and prints it out to the
  2210. // stream.
  2211. // It reorders adds/removes when possible to group all removes before all
  2212. // adds. It also adds the hunk header before printint into the stream.
  2213. class Hunk {
  2214. public:
  2215. Hunk(size_t left_start, size_t right_start)
  2216. : left_start_(left_start),
  2217. right_start_(right_start),
  2218. adds_(),
  2219. removes_(),
  2220. common_() {}
  2221. void PushLine(char edit, const char* line) {
  2222. switch (edit) {
  2223. case ' ':
  2224. ++common_;
  2225. FlushEdits();
  2226. hunk_.push_back(std::make_pair(' ', line));
  2227. break;
  2228. case '-':
  2229. ++removes_;
  2230. hunk_removes_.push_back(std::make_pair('-', line));
  2231. break;
  2232. case '+':
  2233. ++adds_;
  2234. hunk_adds_.push_back(std::make_pair('+', line));
  2235. break;
  2236. }
  2237. }
  2238. void PrintTo(std::ostream* os) {
  2239. PrintHeader(os);
  2240. FlushEdits();
  2241. for (std::list<std::pair<char, const char*> >::const_iterator it =
  2242. hunk_.begin();
  2243. it != hunk_.end(); ++it) {
  2244. *os << it->first << it->second << "\n";
  2245. }
  2246. }
  2247. bool has_edits() const { return adds_ || removes_; }
  2248. private:
  2249. void FlushEdits() {
  2250. hunk_.splice(hunk_.end(), hunk_removes_);
  2251. hunk_.splice(hunk_.end(), hunk_adds_);
  2252. }
  2253. // Print a unified diff header for one hunk.
  2254. // The format is
  2255. // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
  2256. // where the left/right parts are omitted if unnecessary.
  2257. void PrintHeader(std::ostream* ss) const {
  2258. *ss << "@@ ";
  2259. if (removes_) {
  2260. *ss << "-" << left_start_ << "," << (removes_ + common_);
  2261. }
  2262. if (removes_ && adds_) {
  2263. *ss << " ";
  2264. }
  2265. if (adds_) {
  2266. *ss << "+" << right_start_ << "," << (adds_ + common_);
  2267. }
  2268. *ss << " @@\n";
  2269. }
  2270. size_t left_start_, right_start_;
  2271. size_t adds_, removes_, common_;
  2272. std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
  2273. };
  2274. } // namespace
  2275. // Create a list of diff hunks in Unified diff format.
  2276. // Each hunk has a header generated by PrintHeader above plus a body with
  2277. // lines prefixed with ' ' for no change, '-' for deletion and '+' for
  2278. // addition.
  2279. // 'context' represents the desired unchanged prefix/suffix around the diff.
  2280. // If two hunks are close enough that their contexts overlap, then they are
  2281. // joined into one hunk.
  2282. std::string CreateUnifiedDiff(const std::vector<std::string>& left,
  2283. const std::vector<std::string>& right,
  2284. size_t context) {
  2285. const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
  2286. size_t l_i = 0, r_i = 0, edit_i = 0;
  2287. std::stringstream ss;
  2288. while (edit_i < edits.size()) {
  2289. // Find first edit.
  2290. while (edit_i < edits.size() && edits[edit_i] == kMatch) {
  2291. ++l_i;
  2292. ++r_i;
  2293. ++edit_i;
  2294. }
  2295. // Find the first line to include in the hunk.
  2296. const size_t prefix_context = std::min(l_i, context);
  2297. Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
  2298. for (size_t i = prefix_context; i > 0; --i) {
  2299. hunk.PushLine(' ', left[l_i - i].c_str());
  2300. }
  2301. // Iterate the edits until we found enough suffix for the hunk or the input
  2302. // is over.
  2303. size_t n_suffix = 0;
  2304. for (; edit_i < edits.size(); ++edit_i) {
  2305. if (n_suffix >= context) {
  2306. // Continue only if the next hunk is very close.
  2307. std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
  2308. while (it != edits.end() && *it == kMatch) ++it;
  2309. if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
  2310. // There is no next edit or it is too far away.
  2311. break;
  2312. }
  2313. }
  2314. EditType edit = edits[edit_i];
  2315. // Reset count when a non match is found.
  2316. n_suffix = edit == kMatch ? n_suffix + 1 : 0;
  2317. if (edit == kMatch || edit == kRemove || edit == kReplace) {
  2318. hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
  2319. }
  2320. if (edit == kAdd || edit == kReplace) {
  2321. hunk.PushLine('+', right[r_i].c_str());
  2322. }
  2323. // Advance indices, depending on edit type.
  2324. l_i += edit != kAdd;
  2325. r_i += edit != kRemove;
  2326. }
  2327. if (!hunk.has_edits()) {
  2328. // We are done. We don't want this hunk.
  2329. break;
  2330. }
  2331. hunk.PrintTo(&ss);
  2332. }
  2333. return ss.str();
  2334. }
  2335. } // namespace edit_distance
  2336. namespace {
  2337. // The string representation of the values received in EqFailure() are already
  2338. // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
  2339. // characters the same.
  2340. std::vector<std::string> SplitEscapedString(const std::string& str) {
  2341. std::vector<std::string> lines;
  2342. size_t start = 0, end = str.size();
  2343. if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
  2344. ++start;
  2345. --end;
  2346. }
  2347. bool escaped = false;
  2348. for (size_t i = start; i + 1 < end; ++i) {
  2349. if (escaped) {
  2350. escaped = false;
  2351. if (str[i] == 'n') {
  2352. lines.push_back(str.substr(start, i - start - 1));
  2353. start = i + 1;
  2354. }
  2355. } else {
  2356. escaped = str[i] == '\\';
  2357. }
  2358. }
  2359. lines.push_back(str.substr(start, end - start));
  2360. return lines;
  2361. }
  2362. } // namespace
  2363. // Constructs and returns the message for an equality assertion
  2364. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  2365. //
  2366. // The first four parameters are the expressions used in the assertion
  2367. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  2368. // where foo is 5 and bar is 6, we have:
  2369. //
  2370. // lhs_expression: "foo"
  2371. // rhs_expression: "bar"
  2372. // lhs_value: "5"
  2373. // rhs_value: "6"
  2374. //
  2375. // The ignoring_case parameter is true iff the assertion is a
  2376. // *_STRCASEEQ*. When it's true, the string "Ignoring case" will
  2377. // be inserted into the message.
  2378. AssertionResult EqFailure(const char* lhs_expression,
  2379. const char* rhs_expression,
  2380. const std::string& lhs_value,
  2381. const std::string& rhs_value,
  2382. bool ignoring_case) {
  2383. Message msg;
  2384. msg << "Expected equality of these values:";
  2385. msg << "\n " << lhs_expression;
  2386. if (lhs_value != lhs_expression) {
  2387. msg << "\n Which is: " << lhs_value;
  2388. }
  2389. msg << "\n " << rhs_expression;
  2390. if (rhs_value != rhs_expression) {
  2391. msg << "\n Which is: " << rhs_value;
  2392. }
  2393. if (ignoring_case) {
  2394. msg << "\nIgnoring case";
  2395. }
  2396. if (!lhs_value.empty() && !rhs_value.empty()) {
  2397. const std::vector<std::string> lhs_lines =
  2398. SplitEscapedString(lhs_value);
  2399. const std::vector<std::string> rhs_lines =
  2400. SplitEscapedString(rhs_value);
  2401. if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
  2402. msg << "\nWith diff:\n"
  2403. << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
  2404. }
  2405. }
  2406. return AssertionFailure() << msg;
  2407. }
  2408. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  2409. std::string GetBoolAssertionFailureMessage(
  2410. const AssertionResult& assertion_result,
  2411. const char* expression_text,
  2412. const char* actual_predicate_value,
  2413. const char* expected_predicate_value) {
  2414. const char* actual_message = assertion_result.message();
  2415. Message msg;
  2416. msg << "Value of: " << expression_text
  2417. << "\n Actual: " << actual_predicate_value;
  2418. if (actual_message[0] != '\0')
  2419. msg << " (" << actual_message << ")";
  2420. msg << "\nExpected: " << expected_predicate_value;
  2421. return msg.GetString();
  2422. }
  2423. // Helper function for implementing ASSERT_NEAR.
  2424. AssertionResult DoubleNearPredFormat(const char* expr1,
  2425. const char* expr2,
  2426. const char* abs_error_expr,
  2427. double val1,
  2428. double val2,
  2429. double abs_error) {
  2430. const double diff = fabs(val1 - val2);
  2431. if (diff <= abs_error) return AssertionSuccess();
  2432. // FIXME: do not print the value of an expression if it's
  2433. // already a literal.
  2434. return AssertionFailure()
  2435. << "The difference between " << expr1 << " and " << expr2
  2436. << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
  2437. << expr1 << " evaluates to " << val1 << ",\n"
  2438. << expr2 << " evaluates to " << val2 << ", and\n"
  2439. << abs_error_expr << " evaluates to " << abs_error << ".";
  2440. }
  2441. // Helper template for implementing FloatLE() and DoubleLE().
  2442. template <typename RawType>
  2443. AssertionResult FloatingPointLE(const char* expr1,
  2444. const char* expr2,
  2445. RawType val1,
  2446. RawType val2) {
  2447. // Returns success if val1 is less than val2,
  2448. if (val1 < val2) {
  2449. return AssertionSuccess();
  2450. }
  2451. // or if val1 is almost equal to val2.
  2452. const FloatingPoint<RawType> lhs(val1), rhs(val2);
  2453. if (lhs.AlmostEquals(rhs)) {
  2454. return AssertionSuccess();
  2455. }
  2456. // Note that the above two checks will both fail if either val1 or
  2457. // val2 is NaN, as the IEEE floating-point standard requires that
  2458. // any predicate involving a NaN must return false.
  2459. ::std::stringstream val1_ss;
  2460. val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2461. << val1;
  2462. ::std::stringstream val2_ss;
  2463. val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2464. << val2;
  2465. return AssertionFailure()
  2466. << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
  2467. << " Actual: " << StringStreamToString(&val1_ss) << " vs "
  2468. << StringStreamToString(&val2_ss);
  2469. }
  2470. } // namespace internal
  2471. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2472. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2473. AssertionResult FloatLE(const char* expr1, const char* expr2,
  2474. float val1, float val2) {
  2475. return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
  2476. }
  2477. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2478. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2479. AssertionResult DoubleLE(const char* expr1, const char* expr2,
  2480. double val1, double val2) {
  2481. return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
  2482. }
  2483. namespace internal {
  2484. // The helper function for {ASSERT|EXPECT}_EQ with int or enum
  2485. // arguments.
  2486. AssertionResult CmpHelperEQ(const char* lhs_expression,
  2487. const char* rhs_expression,
  2488. BiggestInt lhs,
  2489. BiggestInt rhs) {
  2490. if (lhs == rhs) {
  2491. return AssertionSuccess();
  2492. }
  2493. return EqFailure(lhs_expression,
  2494. rhs_expression,
  2495. FormatForComparisonFailureMessage(lhs, rhs),
  2496. FormatForComparisonFailureMessage(rhs, lhs),
  2497. false);
  2498. }
  2499. // A macro for implementing the helper functions needed to implement
  2500. // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
  2501. // just to avoid copy-and-paste of similar code.
  2502. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
  2503. AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
  2504. BiggestInt val1, BiggestInt val2) {\
  2505. if (val1 op val2) {\
  2506. return AssertionSuccess();\
  2507. } else {\
  2508. return AssertionFailure() \
  2509. << "Expected: (" << expr1 << ") " #op " (" << expr2\
  2510. << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
  2511. << " vs " << FormatForComparisonFailureMessage(val2, val1);\
  2512. }\
  2513. }
  2514. // Implements the helper function for {ASSERT|EXPECT}_NE with int or
  2515. // enum arguments.
  2516. GTEST_IMPL_CMP_HELPER_(NE, !=)
  2517. // Implements the helper function for {ASSERT|EXPECT}_LE with int or
  2518. // enum arguments.
  2519. GTEST_IMPL_CMP_HELPER_(LE, <=)
  2520. // Implements the helper function for {ASSERT|EXPECT}_LT with int or
  2521. // enum arguments.
  2522. GTEST_IMPL_CMP_HELPER_(LT, < )
  2523. // Implements the helper function for {ASSERT|EXPECT}_GE with int or
  2524. // enum arguments.
  2525. GTEST_IMPL_CMP_HELPER_(GE, >=)
  2526. // Implements the helper function for {ASSERT|EXPECT}_GT with int or
  2527. // enum arguments.
  2528. GTEST_IMPL_CMP_HELPER_(GT, > )
  2529. #undef GTEST_IMPL_CMP_HELPER_
  2530. // The helper function for {ASSERT|EXPECT}_STREQ.
  2531. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  2532. const char* rhs_expression,
  2533. const char* lhs,
  2534. const char* rhs) {
  2535. if (String::CStringEquals(lhs, rhs)) {
  2536. return AssertionSuccess();
  2537. }
  2538. return EqFailure(lhs_expression,
  2539. rhs_expression,
  2540. PrintToString(lhs),
  2541. PrintToString(rhs),
  2542. false);
  2543. }
  2544. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  2545. AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
  2546. const char* rhs_expression,
  2547. const char* lhs,
  2548. const char* rhs) {
  2549. if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
  2550. return AssertionSuccess();
  2551. }
  2552. return EqFailure(lhs_expression,
  2553. rhs_expression,
  2554. PrintToString(lhs),
  2555. PrintToString(rhs),
  2556. true);
  2557. }
  2558. // The helper function for {ASSERT|EXPECT}_STRNE.
  2559. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  2560. const char* s2_expression,
  2561. const char* s1,
  2562. const char* s2) {
  2563. if (!String::CStringEquals(s1, s2)) {
  2564. return AssertionSuccess();
  2565. } else {
  2566. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  2567. << s2_expression << "), actual: \""
  2568. << s1 << "\" vs \"" << s2 << "\"";
  2569. }
  2570. }
  2571. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  2572. AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  2573. const char* s2_expression,
  2574. const char* s1,
  2575. const char* s2) {
  2576. if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
  2577. return AssertionSuccess();
  2578. } else {
  2579. return AssertionFailure()
  2580. << "Expected: (" << s1_expression << ") != ("
  2581. << s2_expression << ") (ignoring case), actual: \""
  2582. << s1 << "\" vs \"" << s2 << "\"";
  2583. }
  2584. }
  2585. } // namespace internal
  2586. namespace {
  2587. // Helper functions for implementing IsSubString() and IsNotSubstring().
  2588. // This group of overloaded functions return true iff needle is a
  2589. // substring of haystack. NULL is considered a substring of itself
  2590. // only.
  2591. bool IsSubstringPred(const char* needle, const char* haystack) {
  2592. if (needle == NULL || haystack == NULL)
  2593. return needle == haystack;
  2594. return strstr(haystack, needle) != NULL;
  2595. }
  2596. bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
  2597. if (needle == NULL || haystack == NULL)
  2598. return needle == haystack;
  2599. return wcsstr(haystack, needle) != NULL;
  2600. }
  2601. // StringType here can be either ::std::string or ::std::wstring.
  2602. template <typename StringType>
  2603. bool IsSubstringPred(const StringType& needle,
  2604. const StringType& haystack) {
  2605. return haystack.find(needle) != StringType::npos;
  2606. }
  2607. // This function implements either IsSubstring() or IsNotSubstring(),
  2608. // depending on the value of the expected_to_be_substring parameter.
  2609. // StringType here can be const char*, const wchar_t*, ::std::string,
  2610. // or ::std::wstring.
  2611. template <typename StringType>
  2612. AssertionResult IsSubstringImpl(
  2613. bool expected_to_be_substring,
  2614. const char* needle_expr, const char* haystack_expr,
  2615. const StringType& needle, const StringType& haystack) {
  2616. if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
  2617. return AssertionSuccess();
  2618. const bool is_wide_string = sizeof(needle[0]) > 1;
  2619. const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
  2620. return AssertionFailure()
  2621. << "Value of: " << needle_expr << "\n"
  2622. << " Actual: " << begin_string_quote << needle << "\"\n"
  2623. << "Expected: " << (expected_to_be_substring ? "" : "not ")
  2624. << "a substring of " << haystack_expr << "\n"
  2625. << "Which is: " << begin_string_quote << haystack << "\"";
  2626. }
  2627. } // namespace
  2628. // IsSubstring() and IsNotSubstring() check whether needle is a
  2629. // substring of haystack (NULL is considered a substring of itself
  2630. // only), and return an appropriate error message when they fail.
  2631. AssertionResult IsSubstring(
  2632. const char* needle_expr, const char* haystack_expr,
  2633. const char* needle, const char* haystack) {
  2634. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2635. }
  2636. AssertionResult IsSubstring(
  2637. const char* needle_expr, const char* haystack_expr,
  2638. const wchar_t* needle, const wchar_t* haystack) {
  2639. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2640. }
  2641. AssertionResult IsNotSubstring(
  2642. const char* needle_expr, const char* haystack_expr,
  2643. const char* needle, const char* haystack) {
  2644. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2645. }
  2646. AssertionResult IsNotSubstring(
  2647. const char* needle_expr, const char* haystack_expr,
  2648. const wchar_t* needle, const wchar_t* haystack) {
  2649. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2650. }
  2651. AssertionResult IsSubstring(
  2652. const char* needle_expr, const char* haystack_expr,
  2653. const ::std::string& needle, const ::std::string& haystack) {
  2654. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2655. }
  2656. AssertionResult IsNotSubstring(
  2657. const char* needle_expr, const char* haystack_expr,
  2658. const ::std::string& needle, const ::std::string& haystack) {
  2659. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2660. }
  2661. #if GTEST_HAS_STD_WSTRING
  2662. AssertionResult IsSubstring(
  2663. const char* needle_expr, const char* haystack_expr,
  2664. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2665. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2666. }
  2667. AssertionResult IsNotSubstring(
  2668. const char* needle_expr, const char* haystack_expr,
  2669. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2670. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2671. }
  2672. #endif // GTEST_HAS_STD_WSTRING
  2673. namespace internal {
  2674. #if GTEST_OS_WINDOWS
  2675. namespace {
  2676. // Helper function for IsHRESULT{SuccessFailure} predicates
  2677. AssertionResult HRESULTFailureHelper(const char* expr,
  2678. const char* expected,
  2679. long hr) { // NOLINT
  2680. # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
  2681. // Windows CE doesn't support FormatMessage.
  2682. const char error_text[] = "";
  2683. # else
  2684. // Looks up the human-readable system message for the HRESULT code
  2685. // and since we're not passing any params to FormatMessage, we don't
  2686. // want inserts expanded.
  2687. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
  2688. FORMAT_MESSAGE_IGNORE_INSERTS;
  2689. const DWORD kBufSize = 4096;
  2690. // Gets the system's human readable message string for this HRESULT.
  2691. char error_text[kBufSize] = { '\0' };
  2692. DWORD message_length = ::FormatMessageA(kFlags,
  2693. 0, // no source, we're asking system
  2694. hr, // the error
  2695. 0, // no line width restrictions
  2696. error_text, // output buffer
  2697. kBufSize, // buf size
  2698. NULL); // no arguments for inserts
  2699. // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
  2700. for (; message_length && IsSpace(error_text[message_length - 1]);
  2701. --message_length) {
  2702. error_text[message_length - 1] = '\0';
  2703. }
  2704. # endif // GTEST_OS_WINDOWS_MOBILE
  2705. const std::string error_hex("0x" + String::FormatHexInt(hr));
  2706. return ::testing::AssertionFailure()
  2707. << "Expected: " << expr << " " << expected << ".\n"
  2708. << " Actual: " << error_hex << " " << error_text << "\n";
  2709. }
  2710. } // namespace
  2711. AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
  2712. if (SUCCEEDED(hr)) {
  2713. return AssertionSuccess();
  2714. }
  2715. return HRESULTFailureHelper(expr, "succeeds", hr);
  2716. }
  2717. AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
  2718. if (FAILED(hr)) {
  2719. return AssertionSuccess();
  2720. }
  2721. return HRESULTFailureHelper(expr, "fails", hr);
  2722. }
  2723. #endif // GTEST_OS_WINDOWS
  2724. // Utility functions for encoding Unicode text (wide strings) in
  2725. // UTF-8.
  2726. // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
  2727. // like this:
  2728. //
  2729. // Code-point length Encoding
  2730. // 0 - 7 bits 0xxxxxxx
  2731. // 8 - 11 bits 110xxxxx 10xxxxxx
  2732. // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
  2733. // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  2734. // The maximum code-point a one-byte UTF-8 sequence can represent.
  2735. const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
  2736. // The maximum code-point a two-byte UTF-8 sequence can represent.
  2737. const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
  2738. // The maximum code-point a three-byte UTF-8 sequence can represent.
  2739. const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
  2740. // The maximum code-point a four-byte UTF-8 sequence can represent.
  2741. const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
  2742. // Chops off the n lowest bits from a bit pattern. Returns the n
  2743. // lowest bits. As a side effect, the original bit pattern will be
  2744. // shifted to the right by n bits.
  2745. inline UInt32 ChopLowBits(UInt32* bits, int n) {
  2746. const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
  2747. *bits >>= n;
  2748. return low_bits;
  2749. }
  2750. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  2751. // code_point parameter is of type UInt32 because wchar_t may not be
  2752. // wide enough to contain a code point.
  2753. // If the code_point is not a valid Unicode code point
  2754. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  2755. // to "(Invalid Unicode 0xXXXXXXXX)".
  2756. std::string CodePointToUtf8(UInt32 code_point) {
  2757. if (code_point > kMaxCodePoint4) {
  2758. return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
  2759. }
  2760. char str[5]; // Big enough for the largest valid code point.
  2761. if (code_point <= kMaxCodePoint1) {
  2762. str[1] = '\0';
  2763. str[0] = static_cast<char>(code_point); // 0xxxxxxx
  2764. } else if (code_point <= kMaxCodePoint2) {
  2765. str[2] = '\0';
  2766. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2767. str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
  2768. } else if (code_point <= kMaxCodePoint3) {
  2769. str[3] = '\0';
  2770. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2771. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2772. str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
  2773. } else { // code_point <= kMaxCodePoint4
  2774. str[4] = '\0';
  2775. str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2776. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2777. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2778. str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
  2779. }
  2780. return str;
  2781. }
  2782. // The following two functions only make sense if the system
  2783. // uses UTF-16 for wide string encoding. All supported systems
  2784. // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
  2785. // Determines if the arguments constitute UTF-16 surrogate pair
  2786. // and thus should be combined into a single Unicode code point
  2787. // using CreateCodePointFromUtf16SurrogatePair.
  2788. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
  2789. return sizeof(wchar_t) == 2 &&
  2790. (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
  2791. }
  2792. // Creates a Unicode code point from UTF16 surrogate pair.
  2793. inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
  2794. wchar_t second) {
  2795. const UInt32 mask = (1 << 10) - 1;
  2796. return (sizeof(wchar_t) == 2) ?
  2797. (((first & mask) << 10) | (second & mask)) + 0x10000 :
  2798. // This function should not be called when the condition is
  2799. // false, but we provide a sensible default in case it is.
  2800. static_cast<UInt32>(first);
  2801. }
  2802. // Converts a wide string to a narrow string in UTF-8 encoding.
  2803. // The wide string is assumed to have the following encoding:
  2804. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
  2805. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  2806. // Parameter str points to a null-terminated wide string.
  2807. // Parameter num_chars may additionally limit the number
  2808. // of wchar_t characters processed. -1 is used when the entire string
  2809. // should be processed.
  2810. // If the string contains code points that are not valid Unicode code points
  2811. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  2812. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  2813. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  2814. // will be encoded as individual Unicode characters from Basic Normal Plane.
  2815. std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
  2816. if (num_chars == -1)
  2817. num_chars = static_cast<int>(wcslen(str));
  2818. ::std::stringstream stream;
  2819. for (int i = 0; i < num_chars; ++i) {
  2820. UInt32 unicode_code_point;
  2821. if (str[i] == L'\0') {
  2822. break;
  2823. } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
  2824. unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
  2825. str[i + 1]);
  2826. i++;
  2827. } else {
  2828. unicode_code_point = static_cast<UInt32>(str[i]);
  2829. }
  2830. stream << CodePointToUtf8(unicode_code_point);
  2831. }
  2832. return StringStreamToString(&stream);
  2833. }
  2834. // Converts a wide C string to an std::string using the UTF-8 encoding.
  2835. // NULL will be converted to "(null)".
  2836. std::string String::ShowWideCString(const wchar_t * wide_c_str) {
  2837. if (wide_c_str == NULL) return "(null)";
  2838. return internal::WideStringToUtf8(wide_c_str, -1);
  2839. }
  2840. // Compares two wide C strings. Returns true iff they have the same
  2841. // content.
  2842. //
  2843. // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
  2844. // C string is considered different to any non-NULL C string,
  2845. // including the empty string.
  2846. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
  2847. if (lhs == NULL) return rhs == NULL;
  2848. if (rhs == NULL) return false;
  2849. return wcscmp(lhs, rhs) == 0;
  2850. }
  2851. // Helper function for *_STREQ on wide strings.
  2852. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  2853. const char* rhs_expression,
  2854. const wchar_t* lhs,
  2855. const wchar_t* rhs) {
  2856. if (String::WideCStringEquals(lhs, rhs)) {
  2857. return AssertionSuccess();
  2858. }
  2859. return EqFailure(lhs_expression,
  2860. rhs_expression,
  2861. PrintToString(lhs),
  2862. PrintToString(rhs),
  2863. false);
  2864. }
  2865. // Helper function for *_STRNE on wide strings.
  2866. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  2867. const char* s2_expression,
  2868. const wchar_t* s1,
  2869. const wchar_t* s2) {
  2870. if (!String::WideCStringEquals(s1, s2)) {
  2871. return AssertionSuccess();
  2872. }
  2873. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  2874. << s2_expression << "), actual: "
  2875. << PrintToString(s1)
  2876. << " vs " << PrintToString(s2);
  2877. }
  2878. // Compares two C strings, ignoring case. Returns true iff they have
  2879. // the same content.
  2880. //
  2881. // Unlike strcasecmp(), this function can handle NULL argument(s). A
  2882. // NULL C string is considered different to any non-NULL C string,
  2883. // including the empty string.
  2884. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
  2885. if (lhs == NULL)
  2886. return rhs == NULL;
  2887. if (rhs == NULL)
  2888. return false;
  2889. return posix::StrCaseCmp(lhs, rhs) == 0;
  2890. }
  2891. // Compares two wide C strings, ignoring case. Returns true iff they
  2892. // have the same content.
  2893. //
  2894. // Unlike wcscasecmp(), this function can handle NULL argument(s).
  2895. // A NULL C string is considered different to any non-NULL wide C string,
  2896. // including the empty string.
  2897. // NB: The implementations on different platforms slightly differ.
  2898. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  2899. // environment variable. On GNU platform this method uses wcscasecmp
  2900. // which compares according to LC_CTYPE category of the current locale.
  2901. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  2902. // current locale.
  2903. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  2904. const wchar_t* rhs) {
  2905. if (lhs == NULL) return rhs == NULL;
  2906. if (rhs == NULL) return false;
  2907. #if GTEST_OS_WINDOWS
  2908. return _wcsicmp(lhs, rhs) == 0;
  2909. #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
  2910. return wcscasecmp(lhs, rhs) == 0;
  2911. #else
  2912. // Android, Mac OS X and Cygwin don't define wcscasecmp.
  2913. // Other unknown OSes may not define it either.
  2914. wint_t left, right;
  2915. do {
  2916. left = towlower(*lhs++);
  2917. right = towlower(*rhs++);
  2918. } while (left && left == right);
  2919. return left == right;
  2920. #endif // OS selector
  2921. }
  2922. // Returns true iff str ends with the given suffix, ignoring case.
  2923. // Any string is considered to end with an empty suffix.
  2924. bool String::EndsWithCaseInsensitive(
  2925. const std::string& str, const std::string& suffix) {
  2926. const size_t str_len = str.length();
  2927. const size_t suffix_len = suffix.length();
  2928. return (str_len >= suffix_len) &&
  2929. CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
  2930. suffix.c_str());
  2931. }
  2932. // Formats an int value as "%02d".
  2933. std::string String::FormatIntWidth2(int value) {
  2934. std::stringstream ss;
  2935. ss << std::setfill('0') << std::setw(2) << value;
  2936. return ss.str();
  2937. }
  2938. // Formats an int value as "%X".
  2939. std::string String::FormatHexInt(int value) {
  2940. std::stringstream ss;
  2941. ss << std::hex << std::uppercase << value;
  2942. return ss.str();
  2943. }
  2944. // Formats a byte as "%02X".
  2945. std::string String::FormatByte(unsigned char value) {
  2946. std::stringstream ss;
  2947. ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
  2948. << static_cast<unsigned int>(value);
  2949. return ss.str();
  2950. }
  2951. // Converts the buffer in a stringstream to an std::string, converting NUL
  2952. // bytes to "\\0" along the way.
  2953. std::string StringStreamToString(::std::stringstream* ss) {
  2954. const ::std::string& str = ss->str();
  2955. const char* const start = str.c_str();
  2956. const char* const end = start + str.length();
  2957. std::string result;
  2958. result.reserve(2 * (end - start));
  2959. for (const char* ch = start; ch != end; ++ch) {
  2960. if (*ch == '\0') {
  2961. result += "\\0"; // Replaces NUL with "\\0";
  2962. } else {
  2963. result += *ch;
  2964. }
  2965. }
  2966. return result;
  2967. }
  2968. // Appends the user-supplied message to the Google-Test-generated message.
  2969. std::string AppendUserMessage(const std::string& gtest_msg,
  2970. const Message& user_msg) {
  2971. // Appends the user message if it's non-empty.
  2972. const std::string user_msg_string = user_msg.GetString();
  2973. if (user_msg_string.empty()) {
  2974. return gtest_msg;
  2975. }
  2976. return gtest_msg + "\n" + user_msg_string;
  2977. }
  2978. } // namespace internal
  2979. // class TestResult
  2980. // Creates an empty TestResult.
  2981. TestResult::TestResult()
  2982. : death_test_count_(0),
  2983. elapsed_time_(0) {
  2984. }
  2985. // D'tor.
  2986. TestResult::~TestResult() {
  2987. }
  2988. // Returns the i-th test part result among all the results. i can
  2989. // range from 0 to total_part_count() - 1. If i is not in that range,
  2990. // aborts the program.
  2991. const TestPartResult& TestResult::GetTestPartResult(int i) const {
  2992. if (i < 0 || i >= total_part_count())
  2993. internal::posix::Abort();
  2994. return test_part_results_.at(i);
  2995. }
  2996. // Returns the i-th test property. i can range from 0 to
  2997. // test_property_count() - 1. If i is not in that range, aborts the
  2998. // program.
  2999. const TestProperty& TestResult::GetTestProperty(int i) const {
  3000. if (i < 0 || i >= test_property_count())
  3001. internal::posix::Abort();
  3002. return test_properties_.at(i);
  3003. }
  3004. // Clears the test part results.
  3005. void TestResult::ClearTestPartResults() {
  3006. test_part_results_.clear();
  3007. }
  3008. // Adds a test part result to the list.
  3009. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
  3010. test_part_results_.push_back(test_part_result);
  3011. }
  3012. // Adds a test property to the list. If a property with the same key as the
  3013. // supplied property is already represented, the value of this test_property
  3014. // replaces the old value for that key.
  3015. void TestResult::RecordProperty(const std::string& xml_element,
  3016. const TestProperty& test_property) {
  3017. if (!ValidateTestProperty(xml_element, test_property)) {
  3018. return;
  3019. }
  3020. internal::MutexLock lock(&test_properites_mutex_);
  3021. const std::vector<TestProperty>::iterator property_with_matching_key =
  3022. std::find_if(test_properties_.begin(), test_properties_.end(),
  3023. internal::TestPropertyKeyIs(test_property.key()));
  3024. if (property_with_matching_key == test_properties_.end()) {
  3025. test_properties_.push_back(test_property);
  3026. return;
  3027. }
  3028. property_with_matching_key->SetValue(test_property.value());
  3029. }
  3030. // The list of reserved attributes used in the <testsuites> element of XML
  3031. // output.
  3032. static const char* const kReservedTestSuitesAttributes[] = {
  3033. "disabled",
  3034. "errors",
  3035. "failures",
  3036. "name",
  3037. "random_seed",
  3038. "tests",
  3039. "time",
  3040. "timestamp"
  3041. };
  3042. // The list of reserved attributes used in the <testsuite> element of XML
  3043. // output.
  3044. static const char* const kReservedTestSuiteAttributes[] = {
  3045. "disabled",
  3046. "errors",
  3047. "failures",
  3048. "name",
  3049. "tests",
  3050. "time"
  3051. };
  3052. // The list of reserved attributes used in the <testcase> element of XML output.
  3053. static const char* const kReservedTestCaseAttributes[] = {
  3054. "classname", "name", "status", "time",
  3055. "type_param", "value_param", "file", "line"};
  3056. template <int kSize>
  3057. std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
  3058. return std::vector<std::string>(array, array + kSize);
  3059. }
  3060. static std::vector<std::string> GetReservedAttributesForElement(
  3061. const std::string& xml_element) {
  3062. if (xml_element == "testsuites") {
  3063. return ArrayAsVector(kReservedTestSuitesAttributes);
  3064. } else if (xml_element == "testsuite") {
  3065. return ArrayAsVector(kReservedTestSuiteAttributes);
  3066. } else if (xml_element == "testcase") {
  3067. return ArrayAsVector(kReservedTestCaseAttributes);
  3068. } else {
  3069. GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
  3070. }
  3071. // This code is unreachable but some compilers may not realizes that.
  3072. return std::vector<std::string>();
  3073. }
  3074. static std::string FormatWordList(const std::vector<std::string>& words) {
  3075. Message word_list;
  3076. for (size_t i = 0; i < words.size(); ++i) {
  3077. if (i > 0 && words.size() > 2) {
  3078. word_list << ", ";
  3079. }
  3080. if (i == words.size() - 1) {
  3081. word_list << "and ";
  3082. }
  3083. word_list << "'" << words[i] << "'";
  3084. }
  3085. return word_list.GetString();
  3086. }
  3087. static bool ValidateTestPropertyName(
  3088. const std::string& property_name,
  3089. const std::vector<std::string>& reserved_names) {
  3090. if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
  3091. reserved_names.end()) {
  3092. ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
  3093. << " (" << FormatWordList(reserved_names)
  3094. << " are reserved by " << GTEST_NAME_ << ")";
  3095. return false;
  3096. }
  3097. return true;
  3098. }
  3099. // Adds a failure if the key is a reserved attribute of the element named
  3100. // xml_element. Returns true if the property is valid.
  3101. bool TestResult::ValidateTestProperty(const std::string& xml_element,
  3102. const TestProperty& test_property) {
  3103. return ValidateTestPropertyName(test_property.key(),
  3104. GetReservedAttributesForElement(xml_element));
  3105. }
  3106. // Clears the object.
  3107. void TestResult::Clear() {
  3108. test_part_results_.clear();
  3109. test_properties_.clear();
  3110. death_test_count_ = 0;
  3111. elapsed_time_ = 0;
  3112. }
  3113. // Returns true iff the test failed.
  3114. bool TestResult::Failed() const {
  3115. for (int i = 0; i < total_part_count(); ++i) {
  3116. if (GetTestPartResult(i).failed())
  3117. return true;
  3118. }
  3119. return false;
  3120. }
  3121. // Returns true iff the test part fatally failed.
  3122. static bool TestPartFatallyFailed(const TestPartResult& result) {
  3123. return result.fatally_failed();
  3124. }
  3125. // Returns true iff the test fatally failed.
  3126. bool TestResult::HasFatalFailure() const {
  3127. return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
  3128. }
  3129. // Returns true iff the test part non-fatally failed.
  3130. static bool TestPartNonfatallyFailed(const TestPartResult& result) {
  3131. return result.nonfatally_failed();
  3132. }
  3133. // Returns true iff the test has a non-fatal failure.
  3134. bool TestResult::HasNonfatalFailure() const {
  3135. return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
  3136. }
  3137. // Gets the number of all test parts. This is the sum of the number
  3138. // of successful test parts and the number of failed test parts.
  3139. int TestResult::total_part_count() const {
  3140. return static_cast<int>(test_part_results_.size());
  3141. }
  3142. // Returns the number of the test properties.
  3143. int TestResult::test_property_count() const {
  3144. return static_cast<int>(test_properties_.size());
  3145. }
  3146. // class Test
  3147. // Creates a Test object.
  3148. // The c'tor saves the states of all flags.
  3149. Test::Test()
  3150. : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
  3151. }
  3152. // The d'tor restores the states of all flags. The actual work is
  3153. // done by the d'tor of the gtest_flag_saver_ field, and thus not
  3154. // visible here.
  3155. Test::~Test() {
  3156. }
  3157. // Sets up the test fixture.
  3158. //
  3159. // A sub-class may override this.
  3160. void Test::SetUp() {
  3161. }
  3162. // Tears down the test fixture.
  3163. //
  3164. // A sub-class may override this.
  3165. void Test::TearDown() {
  3166. }
  3167. // Allows user supplied key value pairs to be recorded for later output.
  3168. void Test::RecordProperty(const std::string& key, const std::string& value) {
  3169. UnitTest::GetInstance()->RecordProperty(key, value);
  3170. }
  3171. // Allows user supplied key value pairs to be recorded for later output.
  3172. void Test::RecordProperty(const std::string& key, int value) {
  3173. Message value_message;
  3174. value_message << value;
  3175. RecordProperty(key, value_message.GetString().c_str());
  3176. }
  3177. namespace internal {
  3178. void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  3179. const std::string& message) {
  3180. // This function is a friend of UnitTest and as such has access to
  3181. // AddTestPartResult.
  3182. UnitTest::GetInstance()->AddTestPartResult(
  3183. result_type,
  3184. NULL, // No info about the source file where the exception occurred.
  3185. -1, // We have no info on which line caused the exception.
  3186. message,
  3187. ""); // No stack trace, either.
  3188. }
  3189. } // namespace internal
  3190. // Google Test requires all tests in the same test case to use the same test
  3191. // fixture class. This function checks if the current test has the
  3192. // same fixture class as the first test in the current test case. If
  3193. // yes, it returns true; otherwise it generates a Google Test failure and
  3194. // returns false.
  3195. bool Test::HasSameFixtureClass() {
  3196. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3197. const TestCase* const test_case = impl->current_test_case();
  3198. // Info about the first test in the current test case.
  3199. const TestInfo* const first_test_info = test_case->test_info_list()[0];
  3200. const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
  3201. const char* const first_test_name = first_test_info->name();
  3202. // Info about the current test.
  3203. const TestInfo* const this_test_info = impl->current_test_info();
  3204. const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
  3205. const char* const this_test_name = this_test_info->name();
  3206. if (this_fixture_id != first_fixture_id) {
  3207. // Is the first test defined using TEST?
  3208. const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
  3209. // Is this test defined using TEST?
  3210. const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
  3211. if (first_is_TEST || this_is_TEST) {
  3212. // Both TEST and TEST_F appear in same test case, which is incorrect.
  3213. // Tell the user how to fix this.
  3214. // Gets the name of the TEST and the name of the TEST_F. Note
  3215. // that first_is_TEST and this_is_TEST cannot both be true, as
  3216. // the fixture IDs are different for the two tests.
  3217. const char* const TEST_name =
  3218. first_is_TEST ? first_test_name : this_test_name;
  3219. const char* const TEST_F_name =
  3220. first_is_TEST ? this_test_name : first_test_name;
  3221. ADD_FAILURE()
  3222. << "All tests in the same test case must use the same test fixture\n"
  3223. << "class, so mixing TEST_F and TEST in the same test case is\n"
  3224. << "illegal. In test case " << this_test_info->test_case_name()
  3225. << ",\n"
  3226. << "test " << TEST_F_name << " is defined using TEST_F but\n"
  3227. << "test " << TEST_name << " is defined using TEST. You probably\n"
  3228. << "want to change the TEST to TEST_F or move it to another test\n"
  3229. << "case.";
  3230. } else {
  3231. // Two fixture classes with the same name appear in two different
  3232. // namespaces, which is not allowed. Tell the user how to fix this.
  3233. ADD_FAILURE()
  3234. << "All tests in the same test case must use the same test fixture\n"
  3235. << "class. However, in test case "
  3236. << this_test_info->test_case_name() << ",\n"
  3237. << "you defined test " << first_test_name
  3238. << " and test " << this_test_name << "\n"
  3239. << "using two different test fixture classes. This can happen if\n"
  3240. << "the two classes are from different namespaces or translation\n"
  3241. << "units and have the same name. You should probably rename one\n"
  3242. << "of the classes to put the tests into different test cases.";
  3243. }
  3244. return false;
  3245. }
  3246. return true;
  3247. }
  3248. #if GTEST_HAS_SEH
  3249. // Adds an "exception thrown" fatal failure to the current test. This
  3250. // function returns its result via an output parameter pointer because VC++
  3251. // prohibits creation of objects with destructors on stack in functions
  3252. // using __try (see error C2712).
  3253. static std::string* FormatSehExceptionMessage(DWORD exception_code,
  3254. const char* location) {
  3255. Message message;
  3256. message << "SEH exception with code 0x" << std::setbase(16) <<
  3257. exception_code << std::setbase(10) << " thrown in " << location << ".";
  3258. return new std::string(message.GetString());
  3259. }
  3260. #endif // GTEST_HAS_SEH
  3261. namespace internal {
  3262. #if GTEST_HAS_EXCEPTIONS
  3263. // Adds an "exception thrown" fatal failure to the current test.
  3264. static std::string FormatCxxExceptionMessage(const char* description,
  3265. const char* location) {
  3266. Message message;
  3267. if (description != NULL) {
  3268. message << "C++ exception with description \"" << description << "\"";
  3269. } else {
  3270. message << "Unknown C++ exception";
  3271. }
  3272. message << " thrown in " << location << ".";
  3273. return message.GetString();
  3274. }
  3275. static std::string PrintTestPartResultToString(
  3276. const TestPartResult& test_part_result);
  3277. GoogleTestFailureException::GoogleTestFailureException(
  3278. const TestPartResult& failure)
  3279. : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
  3280. #endif // GTEST_HAS_EXCEPTIONS
  3281. // We put these helper functions in the internal namespace as IBM's xlC
  3282. // compiler rejects the code if they were declared static.
  3283. // Runs the given method and handles SEH exceptions it throws, when
  3284. // SEH is supported; returns the 0-value for type Result in case of an
  3285. // SEH exception. (Microsoft compilers cannot handle SEH and C++
  3286. // exceptions in the same function. Therefore, we provide a separate
  3287. // wrapper function for handling SEH exceptions.)
  3288. template <class T, typename Result>
  3289. Result HandleSehExceptionsInMethodIfSupported(
  3290. T* object, Result (T::*method)(), const char* location) {
  3291. #if GTEST_HAS_SEH
  3292. __try {
  3293. return (object->*method)();
  3294. } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
  3295. GetExceptionCode())) {
  3296. // We create the exception message on the heap because VC++ prohibits
  3297. // creation of objects with destructors on stack in functions using __try
  3298. // (see error C2712).
  3299. std::string* exception_message = FormatSehExceptionMessage(
  3300. GetExceptionCode(), location);
  3301. internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
  3302. *exception_message);
  3303. delete exception_message;
  3304. return static_cast<Result>(0);
  3305. }
  3306. #else
  3307. (void)location;
  3308. return (object->*method)();
  3309. #endif // GTEST_HAS_SEH
  3310. }
  3311. // Runs the given method and catches and reports C++ and/or SEH-style
  3312. // exceptions, if they are supported; returns the 0-value for type
  3313. // Result in case of an SEH exception.
  3314. template <class T, typename Result>
  3315. Result HandleExceptionsInMethodIfSupported(
  3316. T* object, Result (T::*method)(), const char* location) {
  3317. // NOTE: The user code can affect the way in which Google Test handles
  3318. // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
  3319. // RUN_ALL_TESTS() starts. It is technically possible to check the flag
  3320. // after the exception is caught and either report or re-throw the
  3321. // exception based on the flag's value:
  3322. //
  3323. // try {
  3324. // // Perform the test method.
  3325. // } catch (...) {
  3326. // if (GTEST_FLAG(catch_exceptions))
  3327. // // Report the exception as failure.
  3328. // else
  3329. // throw; // Re-throws the original exception.
  3330. // }
  3331. //
  3332. // However, the purpose of this flag is to allow the program to drop into
  3333. // the debugger when the exception is thrown. On most platforms, once the
  3334. // control enters the catch block, the exception origin information is
  3335. // lost and the debugger will stop the program at the point of the
  3336. // re-throw in this function -- instead of at the point of the original
  3337. // throw statement in the code under test. For this reason, we perform
  3338. // the check early, sacrificing the ability to affect Google Test's
  3339. // exception handling in the method where the exception is thrown.
  3340. if (internal::GetUnitTestImpl()->catch_exceptions()) {
  3341. #if GTEST_HAS_EXCEPTIONS
  3342. try {
  3343. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  3344. } catch (const AssertionException&) { // NOLINT
  3345. // This failure was reported already.
  3346. } catch (const internal::GoogleTestFailureException&) { // NOLINT
  3347. // This exception type can only be thrown by a failed Google
  3348. // Test assertion with the intention of letting another testing
  3349. // framework catch it. Therefore we just re-throw it.
  3350. throw;
  3351. } catch (const std::exception& e) { // NOLINT
  3352. internal::ReportFailureInUnknownLocation(
  3353. TestPartResult::kFatalFailure,
  3354. FormatCxxExceptionMessage(e.what(), location));
  3355. } catch (...) { // NOLINT
  3356. internal::ReportFailureInUnknownLocation(
  3357. TestPartResult::kFatalFailure,
  3358. FormatCxxExceptionMessage(NULL, location));
  3359. }
  3360. return static_cast<Result>(0);
  3361. #else
  3362. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  3363. #endif // GTEST_HAS_EXCEPTIONS
  3364. } else {
  3365. return (object->*method)();
  3366. }
  3367. }
  3368. } // namespace internal
  3369. // Runs the test and updates the test result.
  3370. void Test::Run() {
  3371. if (!HasSameFixtureClass()) return;
  3372. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3373. impl->os_stack_trace_getter()->UponLeavingGTest();
  3374. internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
  3375. // We will run the test only if SetUp() was successful.
  3376. if (!HasFatalFailure()) {
  3377. impl->os_stack_trace_getter()->UponLeavingGTest();
  3378. internal::HandleExceptionsInMethodIfSupported(
  3379. this, &Test::TestBody, "the test body");
  3380. }
  3381. // However, we want to clean up as much as possible. Hence we will
  3382. // always call TearDown(), even if SetUp() or the test body has
  3383. // failed.
  3384. impl->os_stack_trace_getter()->UponLeavingGTest();
  3385. internal::HandleExceptionsInMethodIfSupported(
  3386. this, &Test::TearDown, "TearDown()");
  3387. }
  3388. // Returns true iff the current test has a fatal failure.
  3389. bool Test::HasFatalFailure() {
  3390. return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
  3391. }
  3392. // Returns true iff the current test has a non-fatal failure.
  3393. bool Test::HasNonfatalFailure() {
  3394. return internal::GetUnitTestImpl()->current_test_result()->
  3395. HasNonfatalFailure();
  3396. }
  3397. // class TestInfo
  3398. // Constructs a TestInfo object. It assumes ownership of the test factory
  3399. // object.
  3400. TestInfo::TestInfo(const std::string& a_test_case_name,
  3401. const std::string& a_name,
  3402. const char* a_type_param,
  3403. const char* a_value_param,
  3404. internal::CodeLocation a_code_location,
  3405. internal::TypeId fixture_class_id,
  3406. internal::TestFactoryBase* factory)
  3407. : test_case_name_(a_test_case_name),
  3408. name_(a_name),
  3409. type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  3410. value_param_(a_value_param ? new std::string(a_value_param) : NULL),
  3411. location_(a_code_location),
  3412. fixture_class_id_(fixture_class_id),
  3413. should_run_(false),
  3414. is_disabled_(false),
  3415. matches_filter_(false),
  3416. factory_(factory),
  3417. result_() {}
  3418. // Destructs a TestInfo object.
  3419. TestInfo::~TestInfo() { delete factory_; }
  3420. namespace internal {
  3421. // Creates a new TestInfo object and registers it with Google Test;
  3422. // returns the created object.
  3423. //
  3424. // Arguments:
  3425. //
  3426. // test_case_name: name of the test case
  3427. // name: name of the test
  3428. // type_param: the name of the test's type parameter, or NULL if
  3429. // this is not a typed or a type-parameterized test.
  3430. // value_param: text representation of the test's value parameter,
  3431. // or NULL if this is not a value-parameterized test.
  3432. // code_location: code location where the test is defined
  3433. // fixture_class_id: ID of the test fixture class
  3434. // set_up_tc: pointer to the function that sets up the test case
  3435. // tear_down_tc: pointer to the function that tears down the test case
  3436. // factory: pointer to the factory that creates a test object.
  3437. // The newly created TestInfo instance will assume
  3438. // ownership of the factory object.
  3439. TestInfo* MakeAndRegisterTestInfo(
  3440. const char* test_case_name,
  3441. const char* name,
  3442. const char* type_param,
  3443. const char* value_param,
  3444. CodeLocation code_location,
  3445. TypeId fixture_class_id,
  3446. SetUpTestCaseFunc set_up_tc,
  3447. TearDownTestCaseFunc tear_down_tc,
  3448. TestFactoryBase* factory) {
  3449. TestInfo* const test_info =
  3450. new TestInfo(test_case_name, name, type_param, value_param,
  3451. code_location, fixture_class_id, factory);
  3452. GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
  3453. return test_info;
  3454. }
  3455. void ReportInvalidTestCaseType(const char* test_case_name,
  3456. CodeLocation code_location) {
  3457. Message errors;
  3458. errors
  3459. << "Attempted redefinition of test case " << test_case_name << ".\n"
  3460. << "All tests in the same test case must use the same test fixture\n"
  3461. << "class. However, in test case " << test_case_name << ", you tried\n"
  3462. << "to define a test using a fixture class different from the one\n"
  3463. << "used earlier. This can happen if the two fixture classes are\n"
  3464. << "from different namespaces and have the same name. You should\n"
  3465. << "probably rename one of the classes to put the tests into different\n"
  3466. << "test cases.";
  3467. GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
  3468. code_location.line)
  3469. << " " << errors.GetString();
  3470. }
  3471. } // namespace internal
  3472. namespace {
  3473. // A predicate that checks the test name of a TestInfo against a known
  3474. // value.
  3475. //
  3476. // This is used for implementation of the TestCase class only. We put
  3477. // it in the anonymous namespace to prevent polluting the outer
  3478. // namespace.
  3479. //
  3480. // TestNameIs is copyable.
  3481. class TestNameIs {
  3482. public:
  3483. // Constructor.
  3484. //
  3485. // TestNameIs has NO default constructor.
  3486. explicit TestNameIs(const char* name)
  3487. : name_(name) {}
  3488. // Returns true iff the test name of test_info matches name_.
  3489. bool operator()(const TestInfo * test_info) const {
  3490. return test_info && test_info->name() == name_;
  3491. }
  3492. private:
  3493. std::string name_;
  3494. };
  3495. } // namespace
  3496. namespace internal {
  3497. // This method expands all parameterized tests registered with macros TEST_P
  3498. // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
  3499. // This will be done just once during the program runtime.
  3500. void UnitTestImpl::RegisterParameterizedTests() {
  3501. if (!parameterized_tests_registered_) {
  3502. parameterized_test_registry_.RegisterTests();
  3503. parameterized_tests_registered_ = true;
  3504. }
  3505. }
  3506. } // namespace internal
  3507. // Creates the test object, runs it, records its result, and then
  3508. // deletes it.
  3509. void TestInfo::Run() {
  3510. if (!should_run_) return;
  3511. // Tells UnitTest where to store test result.
  3512. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3513. impl->set_current_test_info(this);
  3514. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3515. // Notifies the unit test event listeners that a test is about to start.
  3516. repeater->OnTestStart(*this);
  3517. const TimeInMillis start = internal::GetTimeInMillis();
  3518. impl->os_stack_trace_getter()->UponLeavingGTest();
  3519. // Creates the test object.
  3520. Test* const test = internal::HandleExceptionsInMethodIfSupported(
  3521. factory_, &internal::TestFactoryBase::CreateTest,
  3522. "the test fixture's constructor");
  3523. // Runs the test if the constructor didn't generate a fatal failure.
  3524. // Note that the object will not be null
  3525. if (!Test::HasFatalFailure()) {
  3526. // This doesn't throw as all user code that can throw are wrapped into
  3527. // exception handling code.
  3528. test->Run();
  3529. }
  3530. // Deletes the test object.
  3531. impl->os_stack_trace_getter()->UponLeavingGTest();
  3532. internal::HandleExceptionsInMethodIfSupported(
  3533. test, &Test::DeleteSelf_, "the test fixture's destructor");
  3534. result_.set_elapsed_time(internal::GetTimeInMillis() - start);
  3535. // Notifies the unit test event listener that a test has just finished.
  3536. repeater->OnTestEnd(*this);
  3537. // Tells UnitTest to stop associating assertion results to this
  3538. // test.
  3539. impl->set_current_test_info(NULL);
  3540. }
  3541. // class TestCase
  3542. // Gets the number of successful tests in this test case.
  3543. int TestCase::successful_test_count() const {
  3544. return CountIf(test_info_list_, TestPassed);
  3545. }
  3546. // Gets the number of failed tests in this test case.
  3547. int TestCase::failed_test_count() const {
  3548. return CountIf(test_info_list_, TestFailed);
  3549. }
  3550. // Gets the number of disabled tests that will be reported in the XML report.
  3551. int TestCase::reportable_disabled_test_count() const {
  3552. return CountIf(test_info_list_, TestReportableDisabled);
  3553. }
  3554. // Gets the number of disabled tests in this test case.
  3555. int TestCase::disabled_test_count() const {
  3556. return CountIf(test_info_list_, TestDisabled);
  3557. }
  3558. // Gets the number of tests to be printed in the XML report.
  3559. int TestCase::reportable_test_count() const {
  3560. return CountIf(test_info_list_, TestReportable);
  3561. }
  3562. // Get the number of tests in this test case that should run.
  3563. int TestCase::test_to_run_count() const {
  3564. return CountIf(test_info_list_, ShouldRunTest);
  3565. }
  3566. // Gets the number of all tests.
  3567. int TestCase::total_test_count() const {
  3568. return static_cast<int>(test_info_list_.size());
  3569. }
  3570. // Creates a TestCase with the given name.
  3571. //
  3572. // Arguments:
  3573. //
  3574. // name: name of the test case
  3575. // a_type_param: the name of the test case's type parameter, or NULL if
  3576. // this is not a typed or a type-parameterized test case.
  3577. // set_up_tc: pointer to the function that sets up the test case
  3578. // tear_down_tc: pointer to the function that tears down the test case
  3579. TestCase::TestCase(const char* a_name, const char* a_type_param,
  3580. Test::SetUpTestCaseFunc set_up_tc,
  3581. Test::TearDownTestCaseFunc tear_down_tc)
  3582. : name_(a_name),
  3583. type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  3584. set_up_tc_(set_up_tc),
  3585. tear_down_tc_(tear_down_tc),
  3586. should_run_(false),
  3587. elapsed_time_(0) {
  3588. }
  3589. // Destructor of TestCase.
  3590. TestCase::~TestCase() {
  3591. // Deletes every Test in the collection.
  3592. ForEach(test_info_list_, internal::Delete<TestInfo>);
  3593. }
  3594. // Returns the i-th test among all the tests. i can range from 0 to
  3595. // total_test_count() - 1. If i is not in that range, returns NULL.
  3596. const TestInfo* TestCase::GetTestInfo(int i) const {
  3597. const int index = GetElementOr(test_indices_, i, -1);
  3598. return index < 0 ? NULL : test_info_list_[index];
  3599. }
  3600. // Returns the i-th test among all the tests. i can range from 0 to
  3601. // total_test_count() - 1. If i is not in that range, returns NULL.
  3602. TestInfo* TestCase::GetMutableTestInfo(int i) {
  3603. const int index = GetElementOr(test_indices_, i, -1);
  3604. return index < 0 ? NULL : test_info_list_[index];
  3605. }
  3606. // Adds a test to this test case. Will delete the test upon
  3607. // destruction of the TestCase object.
  3608. void TestCase::AddTestInfo(TestInfo * test_info) {
  3609. test_info_list_.push_back(test_info);
  3610. test_indices_.push_back(static_cast<int>(test_indices_.size()));
  3611. }
  3612. // Runs every test in this TestCase.
  3613. void TestCase::Run() {
  3614. if (!should_run_) return;
  3615. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3616. impl->set_current_test_case(this);
  3617. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3618. repeater->OnTestCaseStart(*this);
  3619. impl->os_stack_trace_getter()->UponLeavingGTest();
  3620. internal::HandleExceptionsInMethodIfSupported(
  3621. this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
  3622. const internal::TimeInMillis start = internal::GetTimeInMillis();
  3623. for (int i = 0; i < total_test_count(); i++) {
  3624. GetMutableTestInfo(i)->Run();
  3625. }
  3626. elapsed_time_ = internal::GetTimeInMillis() - start;
  3627. impl->os_stack_trace_getter()->UponLeavingGTest();
  3628. internal::HandleExceptionsInMethodIfSupported(
  3629. this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
  3630. repeater->OnTestCaseEnd(*this);
  3631. impl->set_current_test_case(NULL);
  3632. }
  3633. // Clears the results of all tests in this test case.
  3634. void TestCase::ClearResult() {
  3635. ad_hoc_test_result_.Clear();
  3636. ForEach(test_info_list_, TestInfo::ClearTestResult);
  3637. }
  3638. // Shuffles the tests in this test case.
  3639. void TestCase::ShuffleTests(internal::Random* random) {
  3640. Shuffle(random, &test_indices_);
  3641. }
  3642. // Restores the test order to before the first shuffle.
  3643. void TestCase::UnshuffleTests() {
  3644. for (size_t i = 0; i < test_indices_.size(); i++) {
  3645. test_indices_[i] = static_cast<int>(i);
  3646. }
  3647. }
  3648. // Formats a countable noun. Depending on its quantity, either the
  3649. // singular form or the plural form is used. e.g.
  3650. //
  3651. // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
  3652. // FormatCountableNoun(5, "book", "books") returns "5 books".
  3653. static std::string FormatCountableNoun(int count,
  3654. const char * singular_form,
  3655. const char * plural_form) {
  3656. return internal::StreamableToString(count) + " " +
  3657. (count == 1 ? singular_form : plural_form);
  3658. }
  3659. // Formats the count of tests.
  3660. static std::string FormatTestCount(int test_count) {
  3661. return FormatCountableNoun(test_count, "test", "tests");
  3662. }
  3663. // Formats the count of test cases.
  3664. static std::string FormatTestCaseCount(int test_case_count) {
  3665. return FormatCountableNoun(test_case_count, "test case", "test cases");
  3666. }
  3667. // Converts a TestPartResult::Type enum to human-friendly string
  3668. // representation. Both kNonFatalFailure and kFatalFailure are translated
  3669. // to "Failure", as the user usually doesn't care about the difference
  3670. // between the two when viewing the test result.
  3671. static const char * TestPartResultTypeToString(TestPartResult::Type type) {
  3672. switch (type) {
  3673. case TestPartResult::kSuccess:
  3674. return "Success";
  3675. case TestPartResult::kNonFatalFailure:
  3676. case TestPartResult::kFatalFailure:
  3677. #ifdef _MSC_VER
  3678. return "error: ";
  3679. #else
  3680. return "Failure\n";
  3681. #endif
  3682. default:
  3683. return "Unknown result type";
  3684. }
  3685. }
  3686. namespace internal {
  3687. // Prints a TestPartResult to an std::string.
  3688. static std::string PrintTestPartResultToString(
  3689. const TestPartResult& test_part_result) {
  3690. return (Message()
  3691. << internal::FormatFileLocation(test_part_result.file_name(),
  3692. test_part_result.line_number())
  3693. << " " << TestPartResultTypeToString(test_part_result.type())
  3694. << test_part_result.message()).GetString();
  3695. }
  3696. // Prints a TestPartResult.
  3697. static void PrintTestPartResult(const TestPartResult& test_part_result) {
  3698. const std::string& result =
  3699. PrintTestPartResultToString(test_part_result);
  3700. printf("%s\n", result.c_str());
  3701. fflush(stdout);
  3702. // If the test program runs in Visual Studio or a debugger, the
  3703. // following statements add the test part result message to the Output
  3704. // window such that the user can double-click on it to jump to the
  3705. // corresponding source code location; otherwise they do nothing.
  3706. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3707. // We don't call OutputDebugString*() on Windows Mobile, as printing
  3708. // to stdout is done by OutputDebugString() there already - we don't
  3709. // want the same message printed twice.
  3710. ::OutputDebugStringA(result.c_str());
  3711. ::OutputDebugStringA("\n");
  3712. #endif
  3713. }
  3714. // class PrettyUnitTestResultPrinter
  3715. enum GTestColor {
  3716. COLOR_DEFAULT,
  3717. COLOR_RED,
  3718. COLOR_GREEN,
  3719. COLOR_YELLOW
  3720. };
  3721. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
  3722. !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  3723. // Returns the character attribute for the given color.
  3724. static WORD GetColorAttribute(GTestColor color) {
  3725. switch (color) {
  3726. case COLOR_RED: return FOREGROUND_RED;
  3727. case COLOR_GREEN: return FOREGROUND_GREEN;
  3728. case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
  3729. default: return 0;
  3730. }
  3731. }
  3732. static int GetBitOffset(WORD color_mask) {
  3733. if (color_mask == 0) return 0;
  3734. int bitOffset = 0;
  3735. while ((color_mask & 1) == 0) {
  3736. color_mask >>= 1;
  3737. ++bitOffset;
  3738. }
  3739. return bitOffset;
  3740. }
  3741. static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
  3742. // Let's reuse the BG
  3743. static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
  3744. BACKGROUND_RED | BACKGROUND_INTENSITY;
  3745. static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
  3746. FOREGROUND_RED | FOREGROUND_INTENSITY;
  3747. const WORD existing_bg = old_color_attrs & background_mask;
  3748. WORD new_color =
  3749. GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
  3750. static const int bg_bitOffset = GetBitOffset(background_mask);
  3751. static const int fg_bitOffset = GetBitOffset(foreground_mask);
  3752. if (((new_color & background_mask) >> bg_bitOffset) ==
  3753. ((new_color & foreground_mask) >> fg_bitOffset)) {
  3754. new_color ^= FOREGROUND_INTENSITY; // invert intensity
  3755. }
  3756. return new_color;
  3757. }
  3758. #else
  3759. // Returns the ANSI color code for the given color. COLOR_DEFAULT is
  3760. // an invalid input.
  3761. static const char* GetAnsiColorCode(GTestColor color) {
  3762. switch (color) {
  3763. case COLOR_RED: return "1";
  3764. case COLOR_GREEN: return "2";
  3765. case COLOR_YELLOW: return "3";
  3766. default: return NULL;
  3767. };
  3768. }
  3769. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3770. // Returns true iff Google Test should use colors in the output.
  3771. bool ShouldUseColor(bool stdout_is_tty) {
  3772. const char* const gtest_color = GTEST_FLAG(color).c_str();
  3773. if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
  3774. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
  3775. // On Windows the TERM variable is usually not set, but the
  3776. // console there does support colors.
  3777. return stdout_is_tty;
  3778. #else
  3779. // On non-Windows platforms, we rely on the TERM variable.
  3780. const char* const term = posix::GetEnv("TERM");
  3781. const bool term_supports_color =
  3782. String::CStringEquals(term, "xterm") ||
  3783. String::CStringEquals(term, "xterm-color") ||
  3784. String::CStringEquals(term, "xterm-256color") ||
  3785. String::CStringEquals(term, "screen") ||
  3786. String::CStringEquals(term, "screen-256color") ||
  3787. String::CStringEquals(term, "tmux") ||
  3788. String::CStringEquals(term, "tmux-256color") ||
  3789. String::CStringEquals(term, "rxvt-unicode") ||
  3790. String::CStringEquals(term, "rxvt-unicode-256color") ||
  3791. String::CStringEquals(term, "linux") ||
  3792. String::CStringEquals(term, "cygwin");
  3793. return stdout_is_tty && term_supports_color;
  3794. #endif // GTEST_OS_WINDOWS
  3795. }
  3796. return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
  3797. String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
  3798. String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
  3799. String::CStringEquals(gtest_color, "1");
  3800. // We take "yes", "true", "t", and "1" as meaning "yes". If the
  3801. // value is neither one of these nor "auto", we treat it as "no" to
  3802. // be conservative.
  3803. }
  3804. // Helpers for printing colored strings to stdout. Note that on Windows, we
  3805. // cannot simply emit special characters and have the terminal change colors.
  3806. // This routine must actually emit the characters rather than return a string
  3807. // that would be colored when printed, as can be done on Linux.
  3808. static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
  3809. va_list args;
  3810. va_start(args, fmt);
  3811. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \
  3812. GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
  3813. const bool use_color = AlwaysFalse();
  3814. #else
  3815. static const bool in_color_mode =
  3816. ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
  3817. const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
  3818. #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
  3819. // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
  3820. if (!use_color) {
  3821. vprintf(fmt, args);
  3822. va_end(args);
  3823. return;
  3824. }
  3825. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
  3826. !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  3827. const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  3828. // Gets the current text color.
  3829. CONSOLE_SCREEN_BUFFER_INFO buffer_info;
  3830. GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
  3831. const WORD old_color_attrs = buffer_info.wAttributes;
  3832. const WORD new_color = GetNewColor(color, old_color_attrs);
  3833. // We need to flush the stream buffers into the console before each
  3834. // SetConsoleTextAttribute call lest it affect the text that is already
  3835. // printed but has not yet reached the console.
  3836. fflush(stdout);
  3837. SetConsoleTextAttribute(stdout_handle, new_color);
  3838. vprintf(fmt, args);
  3839. fflush(stdout);
  3840. // Restores the text color.
  3841. SetConsoleTextAttribute(stdout_handle, old_color_attrs);
  3842. #else
  3843. printf("\033[0;3%sm", GetAnsiColorCode(color));
  3844. vprintf(fmt, args);
  3845. printf("\033[m"); // Resets the terminal to default.
  3846. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3847. va_end(args);
  3848. }
  3849. // Text printed in Google Test's text output and --gtest_list_tests
  3850. // output to label the type parameter and value parameter for a test.
  3851. static const char kTypeParamLabel[] = "TypeParam";
  3852. static const char kValueParamLabel[] = "GetParam()";
  3853. static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
  3854. const char* const type_param = test_info.type_param();
  3855. const char* const value_param = test_info.value_param();
  3856. if (type_param != NULL || value_param != NULL) {
  3857. printf(", where ");
  3858. if (type_param != NULL) {
  3859. printf("%s = %s", kTypeParamLabel, type_param);
  3860. if (value_param != NULL)
  3861. printf(" and ");
  3862. }
  3863. if (value_param != NULL) {
  3864. printf("%s = %s", kValueParamLabel, value_param);
  3865. }
  3866. }
  3867. }
  3868. // This class implements the TestEventListener interface.
  3869. //
  3870. // Class PrettyUnitTestResultPrinter is copyable.
  3871. class PrettyUnitTestResultPrinter : public TestEventListener {
  3872. public:
  3873. PrettyUnitTestResultPrinter() {}
  3874. static void PrintTestName(const char * test_case, const char * test) {
  3875. printf("%s.%s", test_case, test);
  3876. }
  3877. // The following methods override what's in the TestEventListener class.
  3878. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
  3879. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  3880. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  3881. virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
  3882. virtual void OnTestCaseStart(const TestCase& test_case);
  3883. virtual void OnTestStart(const TestInfo& test_info);
  3884. virtual void OnTestPartResult(const TestPartResult& result);
  3885. virtual void OnTestEnd(const TestInfo& test_info);
  3886. virtual void OnTestCaseEnd(const TestCase& test_case);
  3887. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  3888. virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
  3889. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3890. virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
  3891. private:
  3892. static void PrintFailedTests(const UnitTest& unit_test);
  3893. };
  3894. // Fired before each iteration of tests starts.
  3895. void PrettyUnitTestResultPrinter::OnTestIterationStart(
  3896. const UnitTest& unit_test, int iteration) {
  3897. if (GTEST_FLAG(repeat) != 1)
  3898. printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
  3899. const char* const filter = GTEST_FLAG(filter).c_str();
  3900. // Prints the filter if it's not *. This reminds the user that some
  3901. // tests may be skipped.
  3902. if (!String::CStringEquals(filter, kUniversalFilter)) {
  3903. ColoredPrintf(COLOR_YELLOW,
  3904. "Note: %s filter = %s\n", GTEST_NAME_, filter);
  3905. }
  3906. if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
  3907. const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
  3908. ColoredPrintf(COLOR_YELLOW,
  3909. "Note: This is test shard %d of %s.\n",
  3910. static_cast<int>(shard_index) + 1,
  3911. internal::posix::GetEnv(kTestTotalShards));
  3912. }
  3913. if (GTEST_FLAG(shuffle)) {
  3914. ColoredPrintf(COLOR_YELLOW,
  3915. "Note: Randomizing tests' orders with a seed of %d .\n",
  3916. unit_test.random_seed());
  3917. }
  3918. ColoredPrintf(COLOR_GREEN, "[==========] ");
  3919. printf("Running %s from %s.\n",
  3920. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  3921. FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  3922. fflush(stdout);
  3923. }
  3924. void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
  3925. const UnitTest& /*unit_test*/) {
  3926. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3927. printf("Global test environment set-up.\n");
  3928. fflush(stdout);
  3929. }
  3930. void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
  3931. const std::string counts =
  3932. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  3933. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3934. printf("%s from %s", counts.c_str(), test_case.name());
  3935. if (test_case.type_param() == NULL) {
  3936. printf("\n");
  3937. } else {
  3938. printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
  3939. }
  3940. fflush(stdout);
  3941. }
  3942. void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
  3943. ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
  3944. PrintTestName(test_info.test_case_name(), test_info.name());
  3945. printf("\n");
  3946. fflush(stdout);
  3947. }
  3948. // Called after an assertion failure.
  3949. void PrettyUnitTestResultPrinter::OnTestPartResult(
  3950. const TestPartResult& result) {
  3951. // If the test part succeeded, we don't need to do anything.
  3952. if (result.type() == TestPartResult::kSuccess)
  3953. return;
  3954. // Print failure message from the assertion (e.g. expected this and got that).
  3955. PrintTestPartResult(result);
  3956. fflush(stdout);
  3957. }
  3958. void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  3959. if (test_info.result()->Passed()) {
  3960. ColoredPrintf(COLOR_GREEN, "[ OK ] ");
  3961. } else {
  3962. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  3963. }
  3964. PrintTestName(test_info.test_case_name(), test_info.name());
  3965. if (test_info.result()->Failed())
  3966. PrintFullTestCommentIfPresent(test_info);
  3967. if (GTEST_FLAG(print_time)) {
  3968. printf(" (%s ms)\n", internal::StreamableToString(
  3969. test_info.result()->elapsed_time()).c_str());
  3970. } else {
  3971. printf("\n");
  3972. }
  3973. fflush(stdout);
  3974. }
  3975. void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
  3976. if (!GTEST_FLAG(print_time)) return;
  3977. const std::string counts =
  3978. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  3979. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3980. printf("%s from %s (%s ms total)\n\n",
  3981. counts.c_str(), test_case.name(),
  3982. internal::StreamableToString(test_case.elapsed_time()).c_str());
  3983. fflush(stdout);
  3984. }
  3985. void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
  3986. const UnitTest& /*unit_test*/) {
  3987. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3988. printf("Global test environment tear-down\n");
  3989. fflush(stdout);
  3990. }
  3991. // Internal helper for printing the list of failed tests.
  3992. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
  3993. const int failed_test_count = unit_test.failed_test_count();
  3994. if (failed_test_count == 0) {
  3995. return;
  3996. }
  3997. for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  3998. const TestCase& test_case = *unit_test.GetTestCase(i);
  3999. if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
  4000. continue;
  4001. }
  4002. for (int j = 0; j < test_case.total_test_count(); ++j) {
  4003. const TestInfo& test_info = *test_case.GetTestInfo(j);
  4004. if (!test_info.should_run() || test_info.result()->Passed()) {
  4005. continue;
  4006. }
  4007. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  4008. printf("%s.%s", test_case.name(), test_info.name());
  4009. PrintFullTestCommentIfPresent(test_info);
  4010. printf("\n");
  4011. }
  4012. }
  4013. }
  4014. void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4015. int /*iteration*/) {
  4016. ColoredPrintf(COLOR_GREEN, "[==========] ");
  4017. printf("%s from %s ran.",
  4018. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  4019. FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  4020. if (GTEST_FLAG(print_time)) {
  4021. printf(" (%s ms total)",
  4022. internal::StreamableToString(unit_test.elapsed_time()).c_str());
  4023. }
  4024. printf("\n");
  4025. ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
  4026. printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  4027. int num_failures = unit_test.failed_test_count();
  4028. if (!unit_test.Passed()) {
  4029. const int failed_test_count = unit_test.failed_test_count();
  4030. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  4031. printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
  4032. PrintFailedTests(unit_test);
  4033. printf("\n%2d FAILED %s\n", num_failures,
  4034. num_failures == 1 ? "TEST" : "TESTS");
  4035. }
  4036. int num_disabled = unit_test.reportable_disabled_test_count();
  4037. if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
  4038. if (!num_failures) {
  4039. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
  4040. }
  4041. ColoredPrintf(COLOR_YELLOW,
  4042. " YOU HAVE %d DISABLED %s\n\n",
  4043. num_disabled,
  4044. num_disabled == 1 ? "TEST" : "TESTS");
  4045. }
  4046. // Ensure that Google Test output is printed before, e.g., heapchecker output.
  4047. fflush(stdout);
  4048. }
  4049. // End PrettyUnitTestResultPrinter
  4050. // class TestEventRepeater
  4051. //
  4052. // This class forwards events to other event listeners.
  4053. class TestEventRepeater : public TestEventListener {
  4054. public:
  4055. TestEventRepeater() : forwarding_enabled_(true) {}
  4056. virtual ~TestEventRepeater();
  4057. void Append(TestEventListener *listener);
  4058. TestEventListener* Release(TestEventListener* listener);
  4059. // Controls whether events will be forwarded to listeners_. Set to false
  4060. // in death test child processes.
  4061. bool forwarding_enabled() const { return forwarding_enabled_; }
  4062. void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
  4063. virtual void OnTestProgramStart(const UnitTest& unit_test);
  4064. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  4065. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  4066. virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
  4067. virtual void OnTestCaseStart(const TestCase& test_case);
  4068. virtual void OnTestStart(const TestInfo& test_info);
  4069. virtual void OnTestPartResult(const TestPartResult& result);
  4070. virtual void OnTestEnd(const TestInfo& test_info);
  4071. virtual void OnTestCaseEnd(const TestCase& test_case);
  4072. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  4073. virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
  4074. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  4075. virtual void OnTestProgramEnd(const UnitTest& unit_test);
  4076. private:
  4077. // Controls whether events will be forwarded to listeners_. Set to false
  4078. // in death test child processes.
  4079. bool forwarding_enabled_;
  4080. // The list of listeners that receive events.
  4081. std::vector<TestEventListener*> listeners_;
  4082. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
  4083. };
  4084. TestEventRepeater::~TestEventRepeater() {
  4085. ForEach(listeners_, Delete<TestEventListener>);
  4086. }
  4087. void TestEventRepeater::Append(TestEventListener *listener) {
  4088. listeners_.push_back(listener);
  4089. }
  4090. // FIXME: Factor the search functionality into Vector::Find.
  4091. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
  4092. for (size_t i = 0; i < listeners_.size(); ++i) {
  4093. if (listeners_[i] == listener) {
  4094. listeners_.erase(listeners_.begin() + i);
  4095. return listener;
  4096. }
  4097. }
  4098. return NULL;
  4099. }
  4100. // Since most methods are very similar, use macros to reduce boilerplate.
  4101. // This defines a member that forwards the call to all listeners.
  4102. #define GTEST_REPEATER_METHOD_(Name, Type) \
  4103. void TestEventRepeater::Name(const Type& parameter) { \
  4104. if (forwarding_enabled_) { \
  4105. for (size_t i = 0; i < listeners_.size(); i++) { \
  4106. listeners_[i]->Name(parameter); \
  4107. } \
  4108. } \
  4109. }
  4110. // This defines a member that forwards the call to all listeners in reverse
  4111. // order.
  4112. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
  4113. void TestEventRepeater::Name(const Type& parameter) { \
  4114. if (forwarding_enabled_) { \
  4115. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
  4116. listeners_[i]->Name(parameter); \
  4117. } \
  4118. } \
  4119. }
  4120. GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
  4121. GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
  4122. GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
  4123. GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
  4124. GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
  4125. GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
  4126. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
  4127. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
  4128. GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
  4129. GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
  4130. GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
  4131. #undef GTEST_REPEATER_METHOD_
  4132. #undef GTEST_REVERSE_REPEATER_METHOD_
  4133. void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
  4134. int iteration) {
  4135. if (forwarding_enabled_) {
  4136. for (size_t i = 0; i < listeners_.size(); i++) {
  4137. listeners_[i]->OnTestIterationStart(unit_test, iteration);
  4138. }
  4139. }
  4140. }
  4141. void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
  4142. int iteration) {
  4143. if (forwarding_enabled_) {
  4144. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
  4145. listeners_[i]->OnTestIterationEnd(unit_test, iteration);
  4146. }
  4147. }
  4148. }
  4149. // End TestEventRepeater
  4150. // This class generates an XML output file.
  4151. class XmlUnitTestResultPrinter : public EmptyTestEventListener {
  4152. public:
  4153. explicit XmlUnitTestResultPrinter(const char* output_file);
  4154. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  4155. void ListTestsMatchingFilter(const std::vector<TestCase*>& test_cases);
  4156. // Prints an XML summary of all unit tests.
  4157. static void PrintXmlTestsList(std::ostream* stream,
  4158. const std::vector<TestCase*>& test_cases);
  4159. private:
  4160. // Is c a whitespace character that is normalized to a space character
  4161. // when it appears in an XML attribute value?
  4162. static bool IsNormalizableWhitespace(char c) {
  4163. return c == 0x9 || c == 0xA || c == 0xD;
  4164. }
  4165. // May c appear in a well-formed XML document?
  4166. static bool IsValidXmlCharacter(char c) {
  4167. return IsNormalizableWhitespace(c) || c >= 0x20;
  4168. }
  4169. // Returns an XML-escaped copy of the input string str. If
  4170. // is_attribute is true, the text is meant to appear as an attribute
  4171. // value, and normalizable whitespace is preserved by replacing it
  4172. // with character references.
  4173. static std::string EscapeXml(const std::string& str, bool is_attribute);
  4174. // Returns the given string with all characters invalid in XML removed.
  4175. static std::string RemoveInvalidXmlCharacters(const std::string& str);
  4176. // Convenience wrapper around EscapeXml when str is an attribute value.
  4177. static std::string EscapeXmlAttribute(const std::string& str) {
  4178. return EscapeXml(str, true);
  4179. }
  4180. // Convenience wrapper around EscapeXml when str is not an attribute value.
  4181. static std::string EscapeXmlText(const char* str) {
  4182. return EscapeXml(str, false);
  4183. }
  4184. // Verifies that the given attribute belongs to the given element and
  4185. // streams the attribute as XML.
  4186. static void OutputXmlAttribute(std::ostream* stream,
  4187. const std::string& element_name,
  4188. const std::string& name,
  4189. const std::string& value);
  4190. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  4191. static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
  4192. // Streams an XML representation of a TestInfo object.
  4193. static void OutputXmlTestInfo(::std::ostream* stream,
  4194. const char* test_case_name,
  4195. const TestInfo& test_info);
  4196. // Prints an XML representation of a TestCase object
  4197. static void PrintXmlTestCase(::std::ostream* stream,
  4198. const TestCase& test_case);
  4199. // Prints an XML summary of unit_test to output stream out.
  4200. static void PrintXmlUnitTest(::std::ostream* stream,
  4201. const UnitTest& unit_test);
  4202. // Produces a string representing the test properties in a result as space
  4203. // delimited XML attributes based on the property key="value" pairs.
  4204. // When the std::string is not empty, it includes a space at the beginning,
  4205. // to delimit this attribute from prior attributes.
  4206. static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
  4207. // Streams an XML representation of the test properties of a TestResult
  4208. // object.
  4209. static void OutputXmlTestProperties(std::ostream* stream,
  4210. const TestResult& result);
  4211. // The output file.
  4212. const std::string output_file_;
  4213. GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
  4214. };
  4215. // Creates a new XmlUnitTestResultPrinter.
  4216. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
  4217. : output_file_(output_file) {
  4218. if (output_file_.empty()) {
  4219. GTEST_LOG_(FATAL) << "XML output file may not be null";
  4220. }
  4221. }
  4222. // Called after the unit test ends.
  4223. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4224. int /*iteration*/) {
  4225. FILE* xmlout = OpenFileForWriting(output_file_);
  4226. std::stringstream stream;
  4227. PrintXmlUnitTest(&stream, unit_test);
  4228. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  4229. fclose(xmlout);
  4230. }
  4231. void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
  4232. const std::vector<TestCase*>& test_cases) {
  4233. FILE* xmlout = OpenFileForWriting(output_file_);
  4234. std::stringstream stream;
  4235. PrintXmlTestsList(&stream, test_cases);
  4236. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  4237. fclose(xmlout);
  4238. }
  4239. // Returns an XML-escaped copy of the input string str. If is_attribute
  4240. // is true, the text is meant to appear as an attribute value, and
  4241. // normalizable whitespace is preserved by replacing it with character
  4242. // references.
  4243. //
  4244. // Invalid XML characters in str, if any, are stripped from the output.
  4245. // It is expected that most, if not all, of the text processed by this
  4246. // module will consist of ordinary English text.
  4247. // If this module is ever modified to produce version 1.1 XML output,
  4248. // most invalid characters can be retained using character references.
  4249. // FIXME: It might be nice to have a minimally invasive, human-readable
  4250. // escaping scheme for invalid characters, rather than dropping them.
  4251. std::string XmlUnitTestResultPrinter::EscapeXml(
  4252. const std::string& str, bool is_attribute) {
  4253. Message m;
  4254. for (size_t i = 0; i < str.size(); ++i) {
  4255. const char ch = str[i];
  4256. switch (ch) {
  4257. case '<':
  4258. m << "&lt;";
  4259. break;
  4260. case '>':
  4261. m << "&gt;";
  4262. break;
  4263. case '&':
  4264. m << "&amp;";
  4265. break;
  4266. case '\'':
  4267. if (is_attribute)
  4268. m << "&apos;";
  4269. else
  4270. m << '\'';
  4271. break;
  4272. case '"':
  4273. if (is_attribute)
  4274. m << "&quot;";
  4275. else
  4276. m << '"';
  4277. break;
  4278. default:
  4279. if (IsValidXmlCharacter(ch)) {
  4280. if (is_attribute && IsNormalizableWhitespace(ch))
  4281. m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
  4282. << ";";
  4283. else
  4284. m << ch;
  4285. }
  4286. break;
  4287. }
  4288. }
  4289. return m.GetString();
  4290. }
  4291. // Returns the given string with all characters invalid in XML removed.
  4292. // Currently invalid characters are dropped from the string. An
  4293. // alternative is to replace them with certain characters such as . or ?.
  4294. std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
  4295. const std::string& str) {
  4296. std::string output;
  4297. output.reserve(str.size());
  4298. for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
  4299. if (IsValidXmlCharacter(*it))
  4300. output.push_back(*it);
  4301. return output;
  4302. }
  4303. // The following routines generate an XML representation of a UnitTest
  4304. // object.
  4305. // GOOGLETEST_CM0009 DO NOT DELETE
  4306. //
  4307. // This is how Google Test concepts map to the DTD:
  4308. //
  4309. // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
  4310. // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
  4311. // <testcase name="test-name"> <-- corresponds to a TestInfo object
  4312. // <failure message="...">...</failure>
  4313. // <failure message="...">...</failure>
  4314. // <failure message="...">...</failure>
  4315. // <-- individual assertion failures
  4316. // </testcase>
  4317. // </testsuite>
  4318. // </testsuites>
  4319. // Formats the given time in milliseconds as seconds.
  4320. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
  4321. ::std::stringstream ss;
  4322. ss << (static_cast<double>(ms) * 1e-3);
  4323. return ss.str();
  4324. }
  4325. static bool PortableLocaltime(time_t seconds, struct tm* out) {
  4326. #if defined(_MSC_VER)
  4327. return localtime_s(out, &seconds) == 0;
  4328. #elif defined(__MINGW32__) || defined(__MINGW64__)
  4329. // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
  4330. // Windows' localtime(), which has a thread-local tm buffer.
  4331. struct tm* tm_ptr = localtime(&seconds); // NOLINT
  4332. if (tm_ptr == NULL)
  4333. return false;
  4334. *out = *tm_ptr;
  4335. return true;
  4336. #else
  4337. return localtime_r(&seconds, out) != NULL;
  4338. #endif
  4339. }
  4340. // Converts the given epoch time in milliseconds to a date string in the ISO
  4341. // 8601 format, without the timezone information.
  4342. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
  4343. struct tm time_struct;
  4344. if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  4345. return "";
  4346. // YYYY-MM-DDThh:mm:ss
  4347. return StreamableToString(time_struct.tm_year + 1900) + "-" +
  4348. String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  4349. String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  4350. String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  4351. String::FormatIntWidth2(time_struct.tm_min) + ":" +
  4352. String::FormatIntWidth2(time_struct.tm_sec);
  4353. }
  4354. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  4355. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
  4356. const char* data) {
  4357. const char* segment = data;
  4358. *stream << "<![CDATA[";
  4359. for (;;) {
  4360. const char* const next_segment = strstr(segment, "]]>");
  4361. if (next_segment != NULL) {
  4362. stream->write(
  4363. segment, static_cast<std::streamsize>(next_segment - segment));
  4364. *stream << "]]>]]&gt;<![CDATA[";
  4365. segment = next_segment + strlen("]]>");
  4366. } else {
  4367. *stream << segment;
  4368. break;
  4369. }
  4370. }
  4371. *stream << "]]>";
  4372. }
  4373. void XmlUnitTestResultPrinter::OutputXmlAttribute(
  4374. std::ostream* stream,
  4375. const std::string& element_name,
  4376. const std::string& name,
  4377. const std::string& value) {
  4378. const std::vector<std::string>& allowed_names =
  4379. GetReservedAttributesForElement(element_name);
  4380. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4381. allowed_names.end())
  4382. << "Attribute " << name << " is not allowed for element <" << element_name
  4383. << ">.";
  4384. *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
  4385. }
  4386. // Prints an XML representation of a TestInfo object.
  4387. // FIXME: There is also value in printing properties with the plain printer.
  4388. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
  4389. const char* test_case_name,
  4390. const TestInfo& test_info) {
  4391. const TestResult& result = *test_info.result();
  4392. const std::string kTestcase = "testcase";
  4393. if (test_info.is_in_another_shard()) {
  4394. return;
  4395. }
  4396. *stream << " <testcase";
  4397. OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
  4398. if (test_info.value_param() != NULL) {
  4399. OutputXmlAttribute(stream, kTestcase, "value_param",
  4400. test_info.value_param());
  4401. }
  4402. if (test_info.type_param() != NULL) {
  4403. OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
  4404. }
  4405. if (GTEST_FLAG(list_tests)) {
  4406. OutputXmlAttribute(stream, kTestcase, "file", test_info.file());
  4407. OutputXmlAttribute(stream, kTestcase, "line",
  4408. StreamableToString(test_info.line()));
  4409. *stream << " />\n";
  4410. return;
  4411. }
  4412. OutputXmlAttribute(stream, kTestcase, "status",
  4413. test_info.should_run() ? "run" : "notrun");
  4414. OutputXmlAttribute(stream, kTestcase, "time",
  4415. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  4416. OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
  4417. int failures = 0;
  4418. for (int i = 0; i < result.total_part_count(); ++i) {
  4419. const TestPartResult& part = result.GetTestPartResult(i);
  4420. if (part.failed()) {
  4421. if (++failures == 1) {
  4422. *stream << ">\n";
  4423. }
  4424. const std::string location =
  4425. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  4426. part.line_number());
  4427. const std::string summary = location + "\n" + part.summary();
  4428. *stream << " <failure message=\""
  4429. << EscapeXmlAttribute(summary.c_str())
  4430. << "\" type=\"\">";
  4431. const std::string detail = location + "\n" + part.message();
  4432. OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
  4433. *stream << "</failure>\n";
  4434. }
  4435. }
  4436. if (failures == 0 && result.test_property_count() == 0) {
  4437. *stream << " />\n";
  4438. } else {
  4439. if (failures == 0) {
  4440. *stream << ">\n";
  4441. }
  4442. OutputXmlTestProperties(stream, result);
  4443. *stream << " </testcase>\n";
  4444. }
  4445. }
  4446. // Prints an XML representation of a TestCase object
  4447. void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
  4448. const TestCase& test_case) {
  4449. const std::string kTestsuite = "testsuite";
  4450. *stream << " <" << kTestsuite;
  4451. OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
  4452. OutputXmlAttribute(stream, kTestsuite, "tests",
  4453. StreamableToString(test_case.reportable_test_count()));
  4454. if (!GTEST_FLAG(list_tests)) {
  4455. OutputXmlAttribute(stream, kTestsuite, "failures",
  4456. StreamableToString(test_case.failed_test_count()));
  4457. OutputXmlAttribute(
  4458. stream, kTestsuite, "disabled",
  4459. StreamableToString(test_case.reportable_disabled_test_count()));
  4460. OutputXmlAttribute(stream, kTestsuite, "errors", "0");
  4461. OutputXmlAttribute(stream, kTestsuite, "time",
  4462. FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
  4463. *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result());
  4464. }
  4465. *stream << ">\n";
  4466. for (int i = 0; i < test_case.total_test_count(); ++i) {
  4467. if (test_case.GetTestInfo(i)->is_reportable())
  4468. OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
  4469. }
  4470. *stream << " </" << kTestsuite << ">\n";
  4471. }
  4472. // Prints an XML summary of unit_test to output stream out.
  4473. void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
  4474. const UnitTest& unit_test) {
  4475. const std::string kTestsuites = "testsuites";
  4476. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  4477. *stream << "<" << kTestsuites;
  4478. OutputXmlAttribute(stream, kTestsuites, "tests",
  4479. StreamableToString(unit_test.reportable_test_count()));
  4480. OutputXmlAttribute(stream, kTestsuites, "failures",
  4481. StreamableToString(unit_test.failed_test_count()));
  4482. OutputXmlAttribute(
  4483. stream, kTestsuites, "disabled",
  4484. StreamableToString(unit_test.reportable_disabled_test_count()));
  4485. OutputXmlAttribute(stream, kTestsuites, "errors", "0");
  4486. OutputXmlAttribute(
  4487. stream, kTestsuites, "timestamp",
  4488. FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
  4489. OutputXmlAttribute(stream, kTestsuites, "time",
  4490. FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
  4491. if (GTEST_FLAG(shuffle)) {
  4492. OutputXmlAttribute(stream, kTestsuites, "random_seed",
  4493. StreamableToString(unit_test.random_seed()));
  4494. }
  4495. *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
  4496. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  4497. *stream << ">\n";
  4498. for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  4499. if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
  4500. PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
  4501. }
  4502. *stream << "</" << kTestsuites << ">\n";
  4503. }
  4504. void XmlUnitTestResultPrinter::PrintXmlTestsList(
  4505. std::ostream* stream, const std::vector<TestCase*>& test_cases) {
  4506. const std::string kTestsuites = "testsuites";
  4507. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  4508. *stream << "<" << kTestsuites;
  4509. int total_tests = 0;
  4510. for (size_t i = 0; i < test_cases.size(); ++i) {
  4511. total_tests += test_cases[i]->total_test_count();
  4512. }
  4513. OutputXmlAttribute(stream, kTestsuites, "tests",
  4514. StreamableToString(total_tests));
  4515. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  4516. *stream << ">\n";
  4517. for (size_t i = 0; i < test_cases.size(); ++i) {
  4518. PrintXmlTestCase(stream, *test_cases[i]);
  4519. }
  4520. *stream << "</" << kTestsuites << ">\n";
  4521. }
  4522. // Produces a string representing the test properties in a result as space
  4523. // delimited XML attributes based on the property key="value" pairs.
  4524. std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
  4525. const TestResult& result) {
  4526. Message attributes;
  4527. for (int i = 0; i < result.test_property_count(); ++i) {
  4528. const TestProperty& property = result.GetTestProperty(i);
  4529. attributes << " " << property.key() << "="
  4530. << "\"" << EscapeXmlAttribute(property.value()) << "\"";
  4531. }
  4532. return attributes.GetString();
  4533. }
  4534. void XmlUnitTestResultPrinter::OutputXmlTestProperties(
  4535. std::ostream* stream, const TestResult& result) {
  4536. const std::string kProperties = "properties";
  4537. const std::string kProperty = "property";
  4538. if (result.test_property_count() <= 0) {
  4539. return;
  4540. }
  4541. *stream << "<" << kProperties << ">\n";
  4542. for (int i = 0; i < result.test_property_count(); ++i) {
  4543. const TestProperty& property = result.GetTestProperty(i);
  4544. *stream << "<" << kProperty;
  4545. *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
  4546. *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
  4547. *stream << "/>\n";
  4548. }
  4549. *stream << "</" << kProperties << ">\n";
  4550. }
  4551. // End XmlUnitTestResultPrinter
  4552. // This class generates an JSON output file.
  4553. class JsonUnitTestResultPrinter : public EmptyTestEventListener {
  4554. public:
  4555. explicit JsonUnitTestResultPrinter(const char* output_file);
  4556. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  4557. // Prints an JSON summary of all unit tests.
  4558. static void PrintJsonTestList(::std::ostream* stream,
  4559. const std::vector<TestCase*>& test_cases);
  4560. private:
  4561. // Returns an JSON-escaped copy of the input string str.
  4562. static std::string EscapeJson(const std::string& str);
  4563. //// Verifies that the given attribute belongs to the given element and
  4564. //// streams the attribute as JSON.
  4565. static void OutputJsonKey(std::ostream* stream,
  4566. const std::string& element_name,
  4567. const std::string& name,
  4568. const std::string& value,
  4569. const std::string& indent,
  4570. bool comma = true);
  4571. static void OutputJsonKey(std::ostream* stream,
  4572. const std::string& element_name,
  4573. const std::string& name,
  4574. int value,
  4575. const std::string& indent,
  4576. bool comma = true);
  4577. // Streams a JSON representation of a TestInfo object.
  4578. static void OutputJsonTestInfo(::std::ostream* stream,
  4579. const char* test_case_name,
  4580. const TestInfo& test_info);
  4581. // Prints a JSON representation of a TestCase object
  4582. static void PrintJsonTestCase(::std::ostream* stream,
  4583. const TestCase& test_case);
  4584. // Prints a JSON summary of unit_test to output stream out.
  4585. static void PrintJsonUnitTest(::std::ostream* stream,
  4586. const UnitTest& unit_test);
  4587. // Produces a string representing the test properties in a result as
  4588. // a JSON dictionary.
  4589. static std::string TestPropertiesAsJson(const TestResult& result,
  4590. const std::string& indent);
  4591. // The output file.
  4592. const std::string output_file_;
  4593. GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
  4594. };
  4595. // Creates a new JsonUnitTestResultPrinter.
  4596. JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
  4597. : output_file_(output_file) {
  4598. if (output_file_.empty()) {
  4599. GTEST_LOG_(FATAL) << "JSON output file may not be null";
  4600. }
  4601. }
  4602. void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4603. int /*iteration*/) {
  4604. FILE* jsonout = OpenFileForWriting(output_file_);
  4605. std::stringstream stream;
  4606. PrintJsonUnitTest(&stream, unit_test);
  4607. fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
  4608. fclose(jsonout);
  4609. }
  4610. // Returns an JSON-escaped copy of the input string str.
  4611. std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
  4612. Message m;
  4613. for (size_t i = 0; i < str.size(); ++i) {
  4614. const char ch = str[i];
  4615. switch (ch) {
  4616. case '\\':
  4617. case '"':
  4618. case '/':
  4619. m << '\\' << ch;
  4620. break;
  4621. case '\b':
  4622. m << "\\b";
  4623. break;
  4624. case '\t':
  4625. m << "\\t";
  4626. break;
  4627. case '\n':
  4628. m << "\\n";
  4629. break;
  4630. case '\f':
  4631. m << "\\f";
  4632. break;
  4633. case '\r':
  4634. m << "\\r";
  4635. break;
  4636. default:
  4637. if (ch < ' ') {
  4638. m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
  4639. } else {
  4640. m << ch;
  4641. }
  4642. break;
  4643. }
  4644. }
  4645. return m.GetString();
  4646. }
  4647. // The following routines generate an JSON representation of a UnitTest
  4648. // object.
  4649. // Formats the given time in milliseconds as seconds.
  4650. static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
  4651. ::std::stringstream ss;
  4652. ss << (static_cast<double>(ms) * 1e-3) << "s";
  4653. return ss.str();
  4654. }
  4655. // Converts the given epoch time in milliseconds to a date string in the
  4656. // RFC3339 format, without the timezone information.
  4657. static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
  4658. struct tm time_struct;
  4659. if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  4660. return "";
  4661. // YYYY-MM-DDThh:mm:ss
  4662. return StreamableToString(time_struct.tm_year + 1900) + "-" +
  4663. String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  4664. String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  4665. String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  4666. String::FormatIntWidth2(time_struct.tm_min) + ":" +
  4667. String::FormatIntWidth2(time_struct.tm_sec) + "Z";
  4668. }
  4669. static inline std::string Indent(int width) {
  4670. return std::string(width, ' ');
  4671. }
  4672. void JsonUnitTestResultPrinter::OutputJsonKey(
  4673. std::ostream* stream,
  4674. const std::string& element_name,
  4675. const std::string& name,
  4676. const std::string& value,
  4677. const std::string& indent,
  4678. bool comma) {
  4679. const std::vector<std::string>& allowed_names =
  4680. GetReservedAttributesForElement(element_name);
  4681. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4682. allowed_names.end())
  4683. << "Key \"" << name << "\" is not allowed for value \"" << element_name
  4684. << "\".";
  4685. *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
  4686. if (comma)
  4687. *stream << ",\n";
  4688. }
  4689. void JsonUnitTestResultPrinter::OutputJsonKey(
  4690. std::ostream* stream,
  4691. const std::string& element_name,
  4692. const std::string& name,
  4693. int value,
  4694. const std::string& indent,
  4695. bool comma) {
  4696. const std::vector<std::string>& allowed_names =
  4697. GetReservedAttributesForElement(element_name);
  4698. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4699. allowed_names.end())
  4700. << "Key \"" << name << "\" is not allowed for value \"" << element_name
  4701. << "\".";
  4702. *stream << indent << "\"" << name << "\": " << StreamableToString(value);
  4703. if (comma)
  4704. *stream << ",\n";
  4705. }
  4706. // Prints a JSON representation of a TestInfo object.
  4707. void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
  4708. const char* test_case_name,
  4709. const TestInfo& test_info) {
  4710. const TestResult& result = *test_info.result();
  4711. const std::string kTestcase = "testcase";
  4712. const std::string kIndent = Indent(10);
  4713. *stream << Indent(8) << "{\n";
  4714. OutputJsonKey(stream, kTestcase, "name", test_info.name(), kIndent);
  4715. if (test_info.value_param() != NULL) {
  4716. OutputJsonKey(stream, kTestcase, "value_param",
  4717. test_info.value_param(), kIndent);
  4718. }
  4719. if (test_info.type_param() != NULL) {
  4720. OutputJsonKey(stream, kTestcase, "type_param", test_info.type_param(),
  4721. kIndent);
  4722. }
  4723. if (GTEST_FLAG(list_tests)) {
  4724. OutputJsonKey(stream, kTestcase, "file", test_info.file(), kIndent);
  4725. OutputJsonKey(stream, kTestcase, "line", test_info.line(), kIndent, false);
  4726. *stream << "\n" << Indent(8) << "}";
  4727. return;
  4728. }
  4729. OutputJsonKey(stream, kTestcase, "status",
  4730. test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
  4731. OutputJsonKey(stream, kTestcase, "time",
  4732. FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
  4733. OutputJsonKey(stream, kTestcase, "classname", test_case_name, kIndent, false);
  4734. *stream << TestPropertiesAsJson(result, kIndent);
  4735. int failures = 0;
  4736. for (int i = 0; i < result.total_part_count(); ++i) {
  4737. const TestPartResult& part = result.GetTestPartResult(i);
  4738. if (part.failed()) {
  4739. *stream << ",\n";
  4740. if (++failures == 1) {
  4741. *stream << kIndent << "\"" << "failures" << "\": [\n";
  4742. }
  4743. const std::string location =
  4744. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  4745. part.line_number());
  4746. const std::string message = EscapeJson(location + "\n" + part.message());
  4747. *stream << kIndent << " {\n"
  4748. << kIndent << " \"failure\": \"" << message << "\",\n"
  4749. << kIndent << " \"type\": \"\"\n"
  4750. << kIndent << " }";
  4751. }
  4752. }
  4753. if (failures > 0)
  4754. *stream << "\n" << kIndent << "]";
  4755. *stream << "\n" << Indent(8) << "}";
  4756. }
  4757. // Prints an JSON representation of a TestCase object
  4758. void JsonUnitTestResultPrinter::PrintJsonTestCase(std::ostream* stream,
  4759. const TestCase& test_case) {
  4760. const std::string kTestsuite = "testsuite";
  4761. const std::string kIndent = Indent(6);
  4762. *stream << Indent(4) << "{\n";
  4763. OutputJsonKey(stream, kTestsuite, "name", test_case.name(), kIndent);
  4764. OutputJsonKey(stream, kTestsuite, "tests", test_case.reportable_test_count(),
  4765. kIndent);
  4766. if (!GTEST_FLAG(list_tests)) {
  4767. OutputJsonKey(stream, kTestsuite, "failures", test_case.failed_test_count(),
  4768. kIndent);
  4769. OutputJsonKey(stream, kTestsuite, "disabled",
  4770. test_case.reportable_disabled_test_count(), kIndent);
  4771. OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
  4772. OutputJsonKey(stream, kTestsuite, "time",
  4773. FormatTimeInMillisAsDuration(test_case.elapsed_time()),
  4774. kIndent, false);
  4775. *stream << TestPropertiesAsJson(test_case.ad_hoc_test_result(), kIndent)
  4776. << ",\n";
  4777. }
  4778. *stream << kIndent << "\"" << kTestsuite << "\": [\n";
  4779. bool comma = false;
  4780. for (int i = 0; i < test_case.total_test_count(); ++i) {
  4781. if (test_case.GetTestInfo(i)->is_reportable()) {
  4782. if (comma) {
  4783. *stream << ",\n";
  4784. } else {
  4785. comma = true;
  4786. }
  4787. OutputJsonTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
  4788. }
  4789. }
  4790. *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
  4791. }
  4792. // Prints a JSON summary of unit_test to output stream out.
  4793. void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
  4794. const UnitTest& unit_test) {
  4795. const std::string kTestsuites = "testsuites";
  4796. const std::string kIndent = Indent(2);
  4797. *stream << "{\n";
  4798. OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
  4799. kIndent);
  4800. OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
  4801. kIndent);
  4802. OutputJsonKey(stream, kTestsuites, "disabled",
  4803. unit_test.reportable_disabled_test_count(), kIndent);
  4804. OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
  4805. if (GTEST_FLAG(shuffle)) {
  4806. OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
  4807. kIndent);
  4808. }
  4809. OutputJsonKey(stream, kTestsuites, "timestamp",
  4810. FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
  4811. kIndent);
  4812. OutputJsonKey(stream, kTestsuites, "time",
  4813. FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
  4814. false);
  4815. *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
  4816. << ",\n";
  4817. OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  4818. *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  4819. bool comma = false;
  4820. for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  4821. if (unit_test.GetTestCase(i)->reportable_test_count() > 0) {
  4822. if (comma) {
  4823. *stream << ",\n";
  4824. } else {
  4825. comma = true;
  4826. }
  4827. PrintJsonTestCase(stream, *unit_test.GetTestCase(i));
  4828. }
  4829. }
  4830. *stream << "\n" << kIndent << "]\n" << "}\n";
  4831. }
  4832. void JsonUnitTestResultPrinter::PrintJsonTestList(
  4833. std::ostream* stream, const std::vector<TestCase*>& test_cases) {
  4834. const std::string kTestsuites = "testsuites";
  4835. const std::string kIndent = Indent(2);
  4836. *stream << "{\n";
  4837. int total_tests = 0;
  4838. for (size_t i = 0; i < test_cases.size(); ++i) {
  4839. total_tests += test_cases[i]->total_test_count();
  4840. }
  4841. OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
  4842. OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  4843. *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  4844. for (size_t i = 0; i < test_cases.size(); ++i) {
  4845. if (i != 0) {
  4846. *stream << ",\n";
  4847. }
  4848. PrintJsonTestCase(stream, *test_cases[i]);
  4849. }
  4850. *stream << "\n"
  4851. << kIndent << "]\n"
  4852. << "}\n";
  4853. }
  4854. // Produces a string representing the test properties in a result as
  4855. // a JSON dictionary.
  4856. std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
  4857. const TestResult& result, const std::string& indent) {
  4858. Message attributes;
  4859. for (int i = 0; i < result.test_property_count(); ++i) {
  4860. const TestProperty& property = result.GetTestProperty(i);
  4861. attributes << ",\n" << indent << "\"" << property.key() << "\": "
  4862. << "\"" << EscapeJson(property.value()) << "\"";
  4863. }
  4864. return attributes.GetString();
  4865. }
  4866. // End JsonUnitTestResultPrinter
  4867. #if GTEST_CAN_STREAM_RESULTS_
  4868. // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
  4869. // replaces them by "%xx" where xx is their hexadecimal value. For
  4870. // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
  4871. // in both time and space -- important as the input str may contain an
  4872. // arbitrarily long test failure message and stack trace.
  4873. std::string StreamingListener::UrlEncode(const char* str) {
  4874. std::string result;
  4875. result.reserve(strlen(str) + 1);
  4876. for (char ch = *str; ch != '\0'; ch = *++str) {
  4877. switch (ch) {
  4878. case '%':
  4879. case '=':
  4880. case '&':
  4881. case '\n':
  4882. result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
  4883. break;
  4884. default:
  4885. result.push_back(ch);
  4886. break;
  4887. }
  4888. }
  4889. return result;
  4890. }
  4891. void StreamingListener::SocketWriter::MakeConnection() {
  4892. GTEST_CHECK_(sockfd_ == -1)
  4893. << "MakeConnection() can't be called when there is already a connection.";
  4894. addrinfo hints;
  4895. memset(&hints, 0, sizeof(hints));
  4896. hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
  4897. hints.ai_socktype = SOCK_STREAM;
  4898. addrinfo* servinfo = NULL;
  4899. // Use the getaddrinfo() to get a linked list of IP addresses for
  4900. // the given host name.
  4901. const int error_num = getaddrinfo(
  4902. host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
  4903. if (error_num != 0) {
  4904. GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
  4905. << gai_strerror(error_num);
  4906. }
  4907. // Loop through all the results and connect to the first we can.
  4908. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
  4909. cur_addr = cur_addr->ai_next) {
  4910. sockfd_ = socket(
  4911. cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
  4912. if (sockfd_ != -1) {
  4913. // Connect the client socket to the server socket.
  4914. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
  4915. close(sockfd_);
  4916. sockfd_ = -1;
  4917. }
  4918. }
  4919. }
  4920. freeaddrinfo(servinfo); // all done with this structure
  4921. if (sockfd_ == -1) {
  4922. GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
  4923. << host_name_ << ":" << port_num_;
  4924. }
  4925. }
  4926. // End of class Streaming Listener
  4927. #endif // GTEST_CAN_STREAM_RESULTS__
  4928. // class OsStackTraceGetter
  4929. const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
  4930. "... " GTEST_NAME_ " internal frames ...";
  4931. std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
  4932. GTEST_LOCK_EXCLUDED_(mutex_) {
  4933. #if GTEST_HAS_ABSL
  4934. std::string result;
  4935. if (max_depth <= 0) {
  4936. return result;
  4937. }
  4938. max_depth = std::min(max_depth, kMaxStackTraceDepth);
  4939. std::vector<void*> raw_stack(max_depth);
  4940. // Skips the frames requested by the caller, plus this function.
  4941. const int raw_stack_size =
  4942. absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
  4943. void* caller_frame = nullptr;
  4944. {
  4945. MutexLock lock(&mutex_);
  4946. caller_frame = caller_frame_;
  4947. }
  4948. for (int i = 0; i < raw_stack_size; ++i) {
  4949. if (raw_stack[i] == caller_frame &&
  4950. !GTEST_FLAG(show_internal_stack_frames)) {
  4951. // Add a marker to the trace and stop adding frames.
  4952. absl::StrAppend(&result, kElidedFramesMarker, "\n");
  4953. break;
  4954. }
  4955. char tmp[1024];
  4956. const char* symbol = "(unknown)";
  4957. if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
  4958. symbol = tmp;
  4959. }
  4960. char line[1024];
  4961. snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
  4962. result += line;
  4963. }
  4964. return result;
  4965. #else // !GTEST_HAS_ABSL
  4966. static_cast<void>(max_depth);
  4967. static_cast<void>(skip_count);
  4968. return "";
  4969. #endif // GTEST_HAS_ABSL
  4970. }
  4971. void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
  4972. #if GTEST_HAS_ABSL
  4973. void* caller_frame = nullptr;
  4974. if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
  4975. caller_frame = nullptr;
  4976. }
  4977. MutexLock lock(&mutex_);
  4978. caller_frame_ = caller_frame;
  4979. #endif // GTEST_HAS_ABSL
  4980. }
  4981. // A helper class that creates the premature-exit file in its
  4982. // constructor and deletes the file in its destructor.
  4983. class ScopedPrematureExitFile {
  4984. public:
  4985. explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
  4986. : premature_exit_filepath_(premature_exit_filepath ?
  4987. premature_exit_filepath : "") {
  4988. // If a path to the premature-exit file is specified...
  4989. if (!premature_exit_filepath_.empty()) {
  4990. // create the file with a single "0" character in it. I/O
  4991. // errors are ignored as there's nothing better we can do and we
  4992. // don't want to fail the test because of this.
  4993. FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
  4994. fwrite("0", 1, 1, pfile);
  4995. fclose(pfile);
  4996. }
  4997. }
  4998. ~ScopedPrematureExitFile() {
  4999. if (!premature_exit_filepath_.empty()) {
  5000. int retval = remove(premature_exit_filepath_.c_str());
  5001. if (retval) {
  5002. GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
  5003. << premature_exit_filepath_ << "\" with error "
  5004. << retval;
  5005. }
  5006. }
  5007. }
  5008. private:
  5009. const std::string premature_exit_filepath_;
  5010. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
  5011. };
  5012. } // namespace internal
  5013. // class TestEventListeners
  5014. TestEventListeners::TestEventListeners()
  5015. : repeater_(new internal::TestEventRepeater()),
  5016. default_result_printer_(NULL),
  5017. default_xml_generator_(NULL) {
  5018. }
  5019. TestEventListeners::~TestEventListeners() { delete repeater_; }
  5020. // Returns the standard listener responsible for the default console
  5021. // output. Can be removed from the listeners list to shut down default
  5022. // console output. Note that removing this object from the listener list
  5023. // with Release transfers its ownership to the user.
  5024. void TestEventListeners::Append(TestEventListener* listener) {
  5025. repeater_->Append(listener);
  5026. }
  5027. // Removes the given event listener from the list and returns it. It then
  5028. // becomes the caller's responsibility to delete the listener. Returns
  5029. // NULL if the listener is not found in the list.
  5030. TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
  5031. if (listener == default_result_printer_)
  5032. default_result_printer_ = NULL;
  5033. else if (listener == default_xml_generator_)
  5034. default_xml_generator_ = NULL;
  5035. return repeater_->Release(listener);
  5036. }
  5037. // Returns repeater that broadcasts the TestEventListener events to all
  5038. // subscribers.
  5039. TestEventListener* TestEventListeners::repeater() { return repeater_; }
  5040. // Sets the default_result_printer attribute to the provided listener.
  5041. // The listener is also added to the listener list and previous
  5042. // default_result_printer is removed from it and deleted. The listener can
  5043. // also be NULL in which case it will not be added to the list. Does
  5044. // nothing if the previous and the current listener objects are the same.
  5045. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
  5046. if (default_result_printer_ != listener) {
  5047. // It is an error to pass this method a listener that is already in the
  5048. // list.
  5049. delete Release(default_result_printer_);
  5050. default_result_printer_ = listener;
  5051. if (listener != NULL)
  5052. Append(listener);
  5053. }
  5054. }
  5055. // Sets the default_xml_generator attribute to the provided listener. The
  5056. // listener is also added to the listener list and previous
  5057. // default_xml_generator is removed from it and deleted. The listener can
  5058. // also be NULL in which case it will not be added to the list. Does
  5059. // nothing if the previous and the current listener objects are the same.
  5060. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
  5061. if (default_xml_generator_ != listener) {
  5062. // It is an error to pass this method a listener that is already in the
  5063. // list.
  5064. delete Release(default_xml_generator_);
  5065. default_xml_generator_ = listener;
  5066. if (listener != NULL)
  5067. Append(listener);
  5068. }
  5069. }
  5070. // Controls whether events will be forwarded by the repeater to the
  5071. // listeners in the list.
  5072. bool TestEventListeners::EventForwardingEnabled() const {
  5073. return repeater_->forwarding_enabled();
  5074. }
  5075. void TestEventListeners::SuppressEventForwarding() {
  5076. repeater_->set_forwarding_enabled(false);
  5077. }
  5078. // class UnitTest
  5079. // Gets the singleton UnitTest object. The first time this method is
  5080. // called, a UnitTest object is constructed and returned. Consecutive
  5081. // calls will return the same object.
  5082. //
  5083. // We don't protect this under mutex_ as a user is not supposed to
  5084. // call this before main() starts, from which point on the return
  5085. // value will never change.
  5086. UnitTest* UnitTest::GetInstance() {
  5087. // When compiled with MSVC 7.1 in optimized mode, destroying the
  5088. // UnitTest object upon exiting the program messes up the exit code,
  5089. // causing successful tests to appear failed. We have to use a
  5090. // different implementation in this case to bypass the compiler bug.
  5091. // This implementation makes the compiler happy, at the cost of
  5092. // leaking the UnitTest object.
  5093. // CodeGear C++Builder insists on a public destructor for the
  5094. // default implementation. Use this implementation to keep good OO
  5095. // design with private destructor.
  5096. #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  5097. static UnitTest* const instance = new UnitTest;
  5098. return instance;
  5099. #else
  5100. static UnitTest instance;
  5101. return &instance;
  5102. #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  5103. }
  5104. // Gets the number of successful test cases.
  5105. int UnitTest::successful_test_case_count() const {
  5106. return impl()->successful_test_case_count();
  5107. }
  5108. // Gets the number of failed test cases.
  5109. int UnitTest::failed_test_case_count() const {
  5110. return impl()->failed_test_case_count();
  5111. }
  5112. // Gets the number of all test cases.
  5113. int UnitTest::total_test_case_count() const {
  5114. return impl()->total_test_case_count();
  5115. }
  5116. // Gets the number of all test cases that contain at least one test
  5117. // that should run.
  5118. int UnitTest::test_case_to_run_count() const {
  5119. return impl()->test_case_to_run_count();
  5120. }
  5121. // Gets the number of successful tests.
  5122. int UnitTest::successful_test_count() const {
  5123. return impl()->successful_test_count();
  5124. }
  5125. // Gets the number of failed tests.
  5126. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
  5127. // Gets the number of disabled tests that will be reported in the XML report.
  5128. int UnitTest::reportable_disabled_test_count() const {
  5129. return impl()->reportable_disabled_test_count();
  5130. }
  5131. // Gets the number of disabled tests.
  5132. int UnitTest::disabled_test_count() const {
  5133. return impl()->disabled_test_count();
  5134. }
  5135. // Gets the number of tests to be printed in the XML report.
  5136. int UnitTest::reportable_test_count() const {
  5137. return impl()->reportable_test_count();
  5138. }
  5139. // Gets the number of all tests.
  5140. int UnitTest::total_test_count() const { return impl()->total_test_count(); }
  5141. // Gets the number of tests that should run.
  5142. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
  5143. // Gets the time of the test program start, in ms from the start of the
  5144. // UNIX epoch.
  5145. internal::TimeInMillis UnitTest::start_timestamp() const {
  5146. return impl()->start_timestamp();
  5147. }
  5148. // Gets the elapsed time, in milliseconds.
  5149. internal::TimeInMillis UnitTest::elapsed_time() const {
  5150. return impl()->elapsed_time();
  5151. }
  5152. // Returns true iff the unit test passed (i.e. all test cases passed).
  5153. bool UnitTest::Passed() const { return impl()->Passed(); }
  5154. // Returns true iff the unit test failed (i.e. some test case failed
  5155. // or something outside of all tests failed).
  5156. bool UnitTest::Failed() const { return impl()->Failed(); }
  5157. // Gets the i-th test case among all the test cases. i can range from 0 to
  5158. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  5159. const TestCase* UnitTest::GetTestCase(int i) const {
  5160. return impl()->GetTestCase(i);
  5161. }
  5162. // Returns the TestResult containing information on test failures and
  5163. // properties logged outside of individual test cases.
  5164. const TestResult& UnitTest::ad_hoc_test_result() const {
  5165. return *impl()->ad_hoc_test_result();
  5166. }
  5167. // Gets the i-th test case among all the test cases. i can range from 0 to
  5168. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  5169. TestCase* UnitTest::GetMutableTestCase(int i) {
  5170. return impl()->GetMutableTestCase(i);
  5171. }
  5172. // Returns the list of event listeners that can be used to track events
  5173. // inside Google Test.
  5174. TestEventListeners& UnitTest::listeners() {
  5175. return *impl()->listeners();
  5176. }
  5177. // Registers and returns a global test environment. When a test
  5178. // program is run, all global test environments will be set-up in the
  5179. // order they were registered. After all tests in the program have
  5180. // finished, all global test environments will be torn-down in the
  5181. // *reverse* order they were registered.
  5182. //
  5183. // The UnitTest object takes ownership of the given environment.
  5184. //
  5185. // We don't protect this under mutex_, as we only support calling it
  5186. // from the main thread.
  5187. Environment* UnitTest::AddEnvironment(Environment* env) {
  5188. if (env == NULL) {
  5189. return NULL;
  5190. }
  5191. impl_->environments().push_back(env);
  5192. return env;
  5193. }
  5194. // Adds a TestPartResult to the current TestResult object. All Google Test
  5195. // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
  5196. // this to report their results. The user code should use the
  5197. // assertion macros instead of calling this directly.
  5198. void UnitTest::AddTestPartResult(
  5199. TestPartResult::Type result_type,
  5200. const char* file_name,
  5201. int line_number,
  5202. const std::string& message,
  5203. const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
  5204. Message msg;
  5205. msg << message;
  5206. internal::MutexLock lock(&mutex_);
  5207. if (impl_->gtest_trace_stack().size() > 0) {
  5208. msg << "\n" << GTEST_NAME_ << " trace:";
  5209. for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
  5210. i > 0; --i) {
  5211. const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
  5212. msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
  5213. << " " << trace.message;
  5214. }
  5215. }
  5216. if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
  5217. msg << internal::kStackTraceMarker << os_stack_trace;
  5218. }
  5219. const TestPartResult result =
  5220. TestPartResult(result_type, file_name, line_number,
  5221. msg.GetString().c_str());
  5222. impl_->GetTestPartResultReporterForCurrentThread()->
  5223. ReportTestPartResult(result);
  5224. if (result_type != TestPartResult::kSuccess) {
  5225. // gtest_break_on_failure takes precedence over
  5226. // gtest_throw_on_failure. This allows a user to set the latter
  5227. // in the code (perhaps in order to use Google Test assertions
  5228. // with another testing framework) and specify the former on the
  5229. // command line for debugging.
  5230. if (GTEST_FLAG(break_on_failure)) {
  5231. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  5232. // Using DebugBreak on Windows allows gtest to still break into a debugger
  5233. // when a failure happens and both the --gtest_break_on_failure and
  5234. // the --gtest_catch_exceptions flags are specified.
  5235. DebugBreak();
  5236. #elif (!defined(__native_client__)) && \
  5237. ((defined(__clang__) || defined(__GNUC__)) && \
  5238. (defined(__x86_64__) || defined(__i386__)))
  5239. // with clang/gcc we can achieve the same effect on x86 by invoking int3
  5240. asm("int3");
  5241. #else
  5242. // Dereference NULL through a volatile pointer to prevent the compiler
  5243. // from removing. We use this rather than abort() or __builtin_trap() for
  5244. // portability: Symbian doesn't implement abort() well, and some debuggers
  5245. // don't correctly trap abort().
  5246. *static_cast<volatile int*>(NULL) = 1;
  5247. #endif // GTEST_OS_WINDOWS
  5248. } else if (GTEST_FLAG(throw_on_failure)) {
  5249. #if GTEST_HAS_EXCEPTIONS
  5250. throw internal::GoogleTestFailureException(result);
  5251. #else
  5252. // We cannot call abort() as it generates a pop-up in debug mode
  5253. // that cannot be suppressed in VC 7.1 or below.
  5254. exit(1);
  5255. #endif
  5256. }
  5257. }
  5258. }
  5259. // Adds a TestProperty to the current TestResult object when invoked from
  5260. // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
  5261. // from SetUpTestCase or TearDownTestCase, or to the global property set
  5262. // when invoked elsewhere. If the result already contains a property with
  5263. // the same key, the value will be updated.
  5264. void UnitTest::RecordProperty(const std::string& key,
  5265. const std::string& value) {
  5266. impl_->RecordProperty(TestProperty(key, value));
  5267. }
  5268. // Runs all tests in this UnitTest object and prints the result.
  5269. // Returns 0 if successful, or 1 otherwise.
  5270. //
  5271. // We don't protect this under mutex_, as we only support calling it
  5272. // from the main thread.
  5273. int UnitTest::Run() {
  5274. const bool in_death_test_child_process =
  5275. internal::GTEST_FLAG(internal_run_death_test).length() > 0;
  5276. // Google Test implements this protocol for catching that a test
  5277. // program exits before returning control to Google Test:
  5278. //
  5279. // 1. Upon start, Google Test creates a file whose absolute path
  5280. // is specified by the environment variable
  5281. // TEST_PREMATURE_EXIT_FILE.
  5282. // 2. When Google Test has finished its work, it deletes the file.
  5283. //
  5284. // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
  5285. // running a Google-Test-based test program and check the existence
  5286. // of the file at the end of the test execution to see if it has
  5287. // exited prematurely.
  5288. // If we are in the child process of a death test, don't
  5289. // create/delete the premature exit file, as doing so is unnecessary
  5290. // and will confuse the parent process. Otherwise, create/delete
  5291. // the file upon entering/leaving this function. If the program
  5292. // somehow exits before this function has a chance to return, the
  5293. // premature-exit file will be left undeleted, causing a test runner
  5294. // that understands the premature-exit-file protocol to report the
  5295. // test as having failed.
  5296. const internal::ScopedPrematureExitFile premature_exit_file(
  5297. in_death_test_child_process ?
  5298. NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
  5299. // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
  5300. // used for the duration of the program.
  5301. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
  5302. #if GTEST_OS_WINDOWS
  5303. // Either the user wants Google Test to catch exceptions thrown by the
  5304. // tests or this is executing in the context of death test child
  5305. // process. In either case the user does not want to see pop-up dialogs
  5306. // about crashes - they are expected.
  5307. if (impl()->catch_exceptions() || in_death_test_child_process) {
  5308. # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  5309. // SetErrorMode doesn't exist on CE.
  5310. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
  5311. SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
  5312. # endif // !GTEST_OS_WINDOWS_MOBILE
  5313. # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
  5314. // Death test children can be terminated with _abort(). On Windows,
  5315. // _abort() can show a dialog with a warning message. This forces the
  5316. // abort message to go to stderr instead.
  5317. _set_error_mode(_OUT_TO_STDERR);
  5318. # endif
  5319. # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
  5320. // In the debug version, Visual Studio pops up a separate dialog
  5321. // offering a choice to debug the aborted program. We need to suppress
  5322. // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
  5323. // executed. Google Test will notify the user of any unexpected
  5324. // failure via stderr.
  5325. //
  5326. // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
  5327. // Users of prior VC versions shall suffer the agony and pain of
  5328. // clicking through the countless debug dialogs.
  5329. // FIXME: find a way to suppress the abort dialog() in the
  5330. // debug mode when compiled with VC 7.1 or lower.
  5331. if (!GTEST_FLAG(break_on_failure))
  5332. _set_abort_behavior(
  5333. 0x0, // Clear the following flags:
  5334. _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
  5335. # endif
  5336. }
  5337. #endif // GTEST_OS_WINDOWS
  5338. return internal::HandleExceptionsInMethodIfSupported(
  5339. impl(),
  5340. &internal::UnitTestImpl::RunAllTests,
  5341. "auxiliary test code (environments or event listeners)") ? 0 : 1;
  5342. }
  5343. // Returns the working directory when the first TEST() or TEST_F() was
  5344. // executed.
  5345. const char* UnitTest::original_working_dir() const {
  5346. return impl_->original_working_dir_.c_str();
  5347. }
  5348. // Returns the TestCase object for the test that's currently running,
  5349. // or NULL if no test is running.
  5350. const TestCase* UnitTest::current_test_case() const
  5351. GTEST_LOCK_EXCLUDED_(mutex_) {
  5352. internal::MutexLock lock(&mutex_);
  5353. return impl_->current_test_case();
  5354. }
  5355. // Returns the TestInfo object for the test that's currently running,
  5356. // or NULL if no test is running.
  5357. const TestInfo* UnitTest::current_test_info() const
  5358. GTEST_LOCK_EXCLUDED_(mutex_) {
  5359. internal::MutexLock lock(&mutex_);
  5360. return impl_->current_test_info();
  5361. }
  5362. // Returns the random seed used at the start of the current test run.
  5363. int UnitTest::random_seed() const { return impl_->random_seed(); }
  5364. // Returns ParameterizedTestCaseRegistry object used to keep track of
  5365. // value-parameterized tests and instantiate and register them.
  5366. internal::ParameterizedTestCaseRegistry&
  5367. UnitTest::parameterized_test_registry()
  5368. GTEST_LOCK_EXCLUDED_(mutex_) {
  5369. return impl_->parameterized_test_registry();
  5370. }
  5371. // Creates an empty UnitTest.
  5372. UnitTest::UnitTest() {
  5373. impl_ = new internal::UnitTestImpl(this);
  5374. }
  5375. // Destructor of UnitTest.
  5376. UnitTest::~UnitTest() {
  5377. delete impl_;
  5378. }
  5379. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  5380. // Google Test trace stack.
  5381. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
  5382. GTEST_LOCK_EXCLUDED_(mutex_) {
  5383. internal::MutexLock lock(&mutex_);
  5384. impl_->gtest_trace_stack().push_back(trace);
  5385. }
  5386. // Pops a trace from the per-thread Google Test trace stack.
  5387. void UnitTest::PopGTestTrace()
  5388. GTEST_LOCK_EXCLUDED_(mutex_) {
  5389. internal::MutexLock lock(&mutex_);
  5390. impl_->gtest_trace_stack().pop_back();
  5391. }
  5392. namespace internal {
  5393. UnitTestImpl::UnitTestImpl(UnitTest* parent)
  5394. : parent_(parent),
  5395. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
  5396. default_global_test_part_result_reporter_(this),
  5397. default_per_thread_test_part_result_reporter_(this),
  5398. GTEST_DISABLE_MSC_WARNINGS_POP_()
  5399. global_test_part_result_repoter_(
  5400. &default_global_test_part_result_reporter_),
  5401. per_thread_test_part_result_reporter_(
  5402. &default_per_thread_test_part_result_reporter_),
  5403. parameterized_test_registry_(),
  5404. parameterized_tests_registered_(false),
  5405. last_death_test_case_(-1),
  5406. current_test_case_(NULL),
  5407. current_test_info_(NULL),
  5408. ad_hoc_test_result_(),
  5409. os_stack_trace_getter_(NULL),
  5410. post_flag_parse_init_performed_(false),
  5411. random_seed_(0), // Will be overridden by the flag before first use.
  5412. random_(0), // Will be reseeded before first use.
  5413. start_timestamp_(0),
  5414. elapsed_time_(0),
  5415. #if GTEST_HAS_DEATH_TEST
  5416. death_test_factory_(new DefaultDeathTestFactory),
  5417. #endif
  5418. // Will be overridden by the flag before first use.
  5419. catch_exceptions_(false) {
  5420. listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
  5421. }
  5422. UnitTestImpl::~UnitTestImpl() {
  5423. // Deletes every TestCase.
  5424. ForEach(test_cases_, internal::Delete<TestCase>);
  5425. // Deletes every Environment.
  5426. ForEach(environments_, internal::Delete<Environment>);
  5427. delete os_stack_trace_getter_;
  5428. }
  5429. // Adds a TestProperty to the current TestResult object when invoked in a
  5430. // context of a test, to current test case's ad_hoc_test_result when invoke
  5431. // from SetUpTestCase/TearDownTestCase, or to the global property set
  5432. // otherwise. If the result already contains a property with the same key,
  5433. // the value will be updated.
  5434. void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
  5435. std::string xml_element;
  5436. TestResult* test_result; // TestResult appropriate for property recording.
  5437. if (current_test_info_ != NULL) {
  5438. xml_element = "testcase";
  5439. test_result = &(current_test_info_->result_);
  5440. } else if (current_test_case_ != NULL) {
  5441. xml_element = "testsuite";
  5442. test_result = &(current_test_case_->ad_hoc_test_result_);
  5443. } else {
  5444. xml_element = "testsuites";
  5445. test_result = &ad_hoc_test_result_;
  5446. }
  5447. test_result->RecordProperty(xml_element, test_property);
  5448. }
  5449. #if GTEST_HAS_DEATH_TEST
  5450. // Disables event forwarding if the control is currently in a death test
  5451. // subprocess. Must not be called before InitGoogleTest.
  5452. void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
  5453. if (internal_run_death_test_flag_.get() != NULL)
  5454. listeners()->SuppressEventForwarding();
  5455. }
  5456. #endif // GTEST_HAS_DEATH_TEST
  5457. // Initializes event listeners performing XML output as specified by
  5458. // UnitTestOptions. Must not be called before InitGoogleTest.
  5459. void UnitTestImpl::ConfigureXmlOutput() {
  5460. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  5461. if (output_format == "xml") {
  5462. listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
  5463. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  5464. } else if (output_format == "json") {
  5465. listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
  5466. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  5467. } else if (output_format != "") {
  5468. GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
  5469. << output_format << "\" ignored.";
  5470. }
  5471. }
  5472. #if GTEST_CAN_STREAM_RESULTS_
  5473. // Initializes event listeners for streaming test results in string form.
  5474. // Must not be called before InitGoogleTest.
  5475. void UnitTestImpl::ConfigureStreamingOutput() {
  5476. const std::string& target = GTEST_FLAG(stream_result_to);
  5477. if (!target.empty()) {
  5478. const size_t pos = target.find(':');
  5479. if (pos != std::string::npos) {
  5480. listeners()->Append(new StreamingListener(target.substr(0, pos),
  5481. target.substr(pos+1)));
  5482. } else {
  5483. GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
  5484. << "\" ignored.";
  5485. }
  5486. }
  5487. }
  5488. #endif // GTEST_CAN_STREAM_RESULTS_
  5489. // Performs initialization dependent upon flag values obtained in
  5490. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  5491. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  5492. // this function is also called from RunAllTests. Since this function can be
  5493. // called more than once, it has to be idempotent.
  5494. void UnitTestImpl::PostFlagParsingInit() {
  5495. // Ensures that this function does not execute more than once.
  5496. if (!post_flag_parse_init_performed_) {
  5497. post_flag_parse_init_performed_ = true;
  5498. #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  5499. // Register to send notifications about key process state changes.
  5500. listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
  5501. #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  5502. #if GTEST_HAS_DEATH_TEST
  5503. InitDeathTestSubprocessControlInfo();
  5504. SuppressTestEventsIfInSubprocess();
  5505. #endif // GTEST_HAS_DEATH_TEST
  5506. // Registers parameterized tests. This makes parameterized tests
  5507. // available to the UnitTest reflection API without running
  5508. // RUN_ALL_TESTS.
  5509. RegisterParameterizedTests();
  5510. // Configures listeners for XML output. This makes it possible for users
  5511. // to shut down the default XML output before invoking RUN_ALL_TESTS.
  5512. ConfigureXmlOutput();
  5513. #if GTEST_CAN_STREAM_RESULTS_
  5514. // Configures listeners for streaming test results to the specified server.
  5515. ConfigureStreamingOutput();
  5516. #endif // GTEST_CAN_STREAM_RESULTS_
  5517. #if GTEST_HAS_ABSL
  5518. if (GTEST_FLAG(install_failure_signal_handler)) {
  5519. absl::FailureSignalHandlerOptions options;
  5520. absl::InstallFailureSignalHandler(options);
  5521. }
  5522. #endif // GTEST_HAS_ABSL
  5523. }
  5524. }
  5525. // A predicate that checks the name of a TestCase against a known
  5526. // value.
  5527. //
  5528. // This is used for implementation of the UnitTest class only. We put
  5529. // it in the anonymous namespace to prevent polluting the outer
  5530. // namespace.
  5531. //
  5532. // TestCaseNameIs is copyable.
  5533. class TestCaseNameIs {
  5534. public:
  5535. // Constructor.
  5536. explicit TestCaseNameIs(const std::string& name)
  5537. : name_(name) {}
  5538. // Returns true iff the name of test_case matches name_.
  5539. bool operator()(const TestCase* test_case) const {
  5540. return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
  5541. }
  5542. private:
  5543. std::string name_;
  5544. };
  5545. // Finds and returns a TestCase with the given name. If one doesn't
  5546. // exist, creates one and returns it. It's the CALLER'S
  5547. // RESPONSIBILITY to ensure that this function is only called WHEN THE
  5548. // TESTS ARE NOT SHUFFLED.
  5549. //
  5550. // Arguments:
  5551. //
  5552. // test_case_name: name of the test case
  5553. // type_param: the name of the test case's type parameter, or NULL if
  5554. // this is not a typed or a type-parameterized test case.
  5555. // set_up_tc: pointer to the function that sets up the test case
  5556. // tear_down_tc: pointer to the function that tears down the test case
  5557. TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
  5558. const char* type_param,
  5559. Test::SetUpTestCaseFunc set_up_tc,
  5560. Test::TearDownTestCaseFunc tear_down_tc) {
  5561. // Can we find a TestCase with the given name?
  5562. const std::vector<TestCase*>::const_reverse_iterator test_case =
  5563. std::find_if(test_cases_.rbegin(), test_cases_.rend(),
  5564. TestCaseNameIs(test_case_name));
  5565. if (test_case != test_cases_.rend())
  5566. return *test_case;
  5567. // No. Let's create one.
  5568. TestCase* const new_test_case =
  5569. new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
  5570. // Is this a death test case?
  5571. if (internal::UnitTestOptions::MatchesFilter(test_case_name,
  5572. kDeathTestCaseFilter)) {
  5573. // Yes. Inserts the test case after the last death test case
  5574. // defined so far. This only works when the test cases haven't
  5575. // been shuffled. Otherwise we may end up running a death test
  5576. // after a non-death test.
  5577. ++last_death_test_case_;
  5578. test_cases_.insert(test_cases_.begin() + last_death_test_case_,
  5579. new_test_case);
  5580. } else {
  5581. // No. Appends to the end of the list.
  5582. test_cases_.push_back(new_test_case);
  5583. }
  5584. test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
  5585. return new_test_case;
  5586. }
  5587. // Helpers for setting up / tearing down the given environment. They
  5588. // are for use in the ForEach() function.
  5589. static void SetUpEnvironment(Environment* env) { env->SetUp(); }
  5590. static void TearDownEnvironment(Environment* env) { env->TearDown(); }
  5591. // Runs all tests in this UnitTest object, prints the result, and
  5592. // returns true if all tests are successful. If any exception is
  5593. // thrown during a test, the test is considered to be failed, but the
  5594. // rest of the tests will still be run.
  5595. //
  5596. // When parameterized tests are enabled, it expands and registers
  5597. // parameterized tests first in RegisterParameterizedTests().
  5598. // All other functions called from RunAllTests() may safely assume that
  5599. // parameterized tests are ready to be counted and run.
  5600. bool UnitTestImpl::RunAllTests() {
  5601. // True iff Google Test is initialized before RUN_ALL_TESTS() is called.
  5602. const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
  5603. // Do not run any test if the --help flag was specified.
  5604. if (g_help_flag)
  5605. return true;
  5606. // Repeats the call to the post-flag parsing initialization in case the
  5607. // user didn't call InitGoogleTest.
  5608. PostFlagParsingInit();
  5609. // Even if sharding is not on, test runners may want to use the
  5610. // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
  5611. // protocol.
  5612. internal::WriteToShardStatusFileIfNeeded();
  5613. // True iff we are in a subprocess for running a thread-safe-style
  5614. // death test.
  5615. bool in_subprocess_for_death_test = false;
  5616. #if GTEST_HAS_DEATH_TEST
  5617. in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
  5618. # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  5619. if (in_subprocess_for_death_test) {
  5620. GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
  5621. }
  5622. # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  5623. #endif // GTEST_HAS_DEATH_TEST
  5624. const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
  5625. in_subprocess_for_death_test);
  5626. // Compares the full test names with the filter to decide which
  5627. // tests to run.
  5628. const bool has_tests_to_run = FilterTests(should_shard
  5629. ? HONOR_SHARDING_PROTOCOL
  5630. : IGNORE_SHARDING_PROTOCOL) > 0;
  5631. // Lists the tests and exits if the --gtest_list_tests flag was specified.
  5632. if (GTEST_FLAG(list_tests)) {
  5633. // This must be called *after* FilterTests() has been called.
  5634. ListTestsMatchingFilter();
  5635. return true;
  5636. }
  5637. random_seed_ = GTEST_FLAG(shuffle) ?
  5638. GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
  5639. // True iff at least one test has failed.
  5640. bool failed = false;
  5641. TestEventListener* repeater = listeners()->repeater();
  5642. start_timestamp_ = GetTimeInMillis();
  5643. repeater->OnTestProgramStart(*parent_);
  5644. // How many times to repeat the tests? We don't want to repeat them
  5645. // when we are inside the subprocess of a death test.
  5646. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
  5647. // Repeats forever if the repeat count is negative.
  5648. const bool forever = repeat < 0;
  5649. for (int i = 0; forever || i != repeat; i++) {
  5650. // We want to preserve failures generated by ad-hoc test
  5651. // assertions executed before RUN_ALL_TESTS().
  5652. ClearNonAdHocTestResult();
  5653. const TimeInMillis start = GetTimeInMillis();
  5654. // Shuffles test cases and tests if requested.
  5655. if (has_tests_to_run && GTEST_FLAG(shuffle)) {
  5656. random()->Reseed(random_seed_);
  5657. // This should be done before calling OnTestIterationStart(),
  5658. // such that a test event listener can see the actual test order
  5659. // in the event.
  5660. ShuffleTests();
  5661. }
  5662. // Tells the unit test event listeners that the tests are about to start.
  5663. repeater->OnTestIterationStart(*parent_, i);
  5664. // Runs each test case if there is at least one test to run.
  5665. if (has_tests_to_run) {
  5666. // Sets up all environments beforehand.
  5667. repeater->OnEnvironmentsSetUpStart(*parent_);
  5668. ForEach(environments_, SetUpEnvironment);
  5669. repeater->OnEnvironmentsSetUpEnd(*parent_);
  5670. // Runs the tests only if there was no fatal failure during global
  5671. // set-up.
  5672. if (!Test::HasFatalFailure()) {
  5673. for (int test_index = 0; test_index < total_test_case_count();
  5674. test_index++) {
  5675. GetMutableTestCase(test_index)->Run();
  5676. }
  5677. }
  5678. // Tears down all environments in reverse order afterwards.
  5679. repeater->OnEnvironmentsTearDownStart(*parent_);
  5680. std::for_each(environments_.rbegin(), environments_.rend(),
  5681. TearDownEnvironment);
  5682. repeater->OnEnvironmentsTearDownEnd(*parent_);
  5683. }
  5684. elapsed_time_ = GetTimeInMillis() - start;
  5685. // Tells the unit test event listener that the tests have just finished.
  5686. repeater->OnTestIterationEnd(*parent_, i);
  5687. // Gets the result and clears it.
  5688. if (!Passed()) {
  5689. failed = true;
  5690. }
  5691. // Restores the original test order after the iteration. This
  5692. // allows the user to quickly repro a failure that happens in the
  5693. // N-th iteration without repeating the first (N - 1) iterations.
  5694. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
  5695. // case the user somehow changes the value of the flag somewhere
  5696. // (it's always safe to unshuffle the tests).
  5697. UnshuffleTests();
  5698. if (GTEST_FLAG(shuffle)) {
  5699. // Picks a new random seed for each iteration.
  5700. random_seed_ = GetNextRandomSeed(random_seed_);
  5701. }
  5702. }
  5703. repeater->OnTestProgramEnd(*parent_);
  5704. if (!gtest_is_initialized_before_run_all_tests) {
  5705. ColoredPrintf(
  5706. COLOR_RED,
  5707. "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
  5708. "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
  5709. "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
  5710. " will start to enforce the valid usage. "
  5711. "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
  5712. #if GTEST_FOR_GOOGLE_
  5713. ColoredPrintf(COLOR_RED,
  5714. "For more details, see http://wiki/Main/ValidGUnitMain.\n");
  5715. #endif // GTEST_FOR_GOOGLE_
  5716. }
  5717. return !failed;
  5718. }
  5719. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  5720. // if the variable is present. If a file already exists at this location, this
  5721. // function will write over it. If the variable is present, but the file cannot
  5722. // be created, prints an error and exits.
  5723. void WriteToShardStatusFileIfNeeded() {
  5724. const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
  5725. if (test_shard_file != NULL) {
  5726. FILE* const file = posix::FOpen(test_shard_file, "w");
  5727. if (file == NULL) {
  5728. ColoredPrintf(COLOR_RED,
  5729. "Could not write to the test shard status file \"%s\" "
  5730. "specified by the %s environment variable.\n",
  5731. test_shard_file, kTestShardStatusFile);
  5732. fflush(stdout);
  5733. exit(EXIT_FAILURE);
  5734. }
  5735. fclose(file);
  5736. }
  5737. }
  5738. // Checks whether sharding is enabled by examining the relevant
  5739. // environment variable values. If the variables are present,
  5740. // but inconsistent (i.e., shard_index >= total_shards), prints
  5741. // an error and exits. If in_subprocess_for_death_test, sharding is
  5742. // disabled because it must only be applied to the original test
  5743. // process. Otherwise, we could filter out death tests we intended to execute.
  5744. bool ShouldShard(const char* total_shards_env,
  5745. const char* shard_index_env,
  5746. bool in_subprocess_for_death_test) {
  5747. if (in_subprocess_for_death_test) {
  5748. return false;
  5749. }
  5750. const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
  5751. const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
  5752. if (total_shards == -1 && shard_index == -1) {
  5753. return false;
  5754. } else if (total_shards == -1 && shard_index != -1) {
  5755. const Message msg = Message()
  5756. << "Invalid environment variables: you have "
  5757. << kTestShardIndex << " = " << shard_index
  5758. << ", but have left " << kTestTotalShards << " unset.\n";
  5759. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5760. fflush(stdout);
  5761. exit(EXIT_FAILURE);
  5762. } else if (total_shards != -1 && shard_index == -1) {
  5763. const Message msg = Message()
  5764. << "Invalid environment variables: you have "
  5765. << kTestTotalShards << " = " << total_shards
  5766. << ", but have left " << kTestShardIndex << " unset.\n";
  5767. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5768. fflush(stdout);
  5769. exit(EXIT_FAILURE);
  5770. } else if (shard_index < 0 || shard_index >= total_shards) {
  5771. const Message msg = Message()
  5772. << "Invalid environment variables: we require 0 <= "
  5773. << kTestShardIndex << " < " << kTestTotalShards
  5774. << ", but you have " << kTestShardIndex << "=" << shard_index
  5775. << ", " << kTestTotalShards << "=" << total_shards << ".\n";
  5776. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5777. fflush(stdout);
  5778. exit(EXIT_FAILURE);
  5779. }
  5780. return total_shards > 1;
  5781. }
  5782. // Parses the environment variable var as an Int32. If it is unset,
  5783. // returns default_val. If it is not an Int32, prints an error
  5784. // and aborts.
  5785. Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
  5786. const char* str_val = posix::GetEnv(var);
  5787. if (str_val == NULL) {
  5788. return default_val;
  5789. }
  5790. Int32 result;
  5791. if (!ParseInt32(Message() << "The value of environment variable " << var,
  5792. str_val, &result)) {
  5793. exit(EXIT_FAILURE);
  5794. }
  5795. return result;
  5796. }
  5797. // Given the total number of shards, the shard index, and the test id,
  5798. // returns true iff the test should be run on this shard. The test id is
  5799. // some arbitrary but unique non-negative integer assigned to each test
  5800. // method. Assumes that 0 <= shard_index < total_shards.
  5801. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
  5802. return (test_id % total_shards) == shard_index;
  5803. }
  5804. // Compares the name of each test with the user-specified filter to
  5805. // decide whether the test should be run, then records the result in
  5806. // each TestCase and TestInfo object.
  5807. // If shard_tests == true, further filters tests based on sharding
  5808. // variables in the environment - see
  5809. // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
  5810. // . Returns the number of tests that should run.
  5811. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
  5812. const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
  5813. Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
  5814. const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
  5815. Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
  5816. // num_runnable_tests are the number of tests that will
  5817. // run across all shards (i.e., match filter and are not disabled).
  5818. // num_selected_tests are the number of tests to be run on
  5819. // this shard.
  5820. int num_runnable_tests = 0;
  5821. int num_selected_tests = 0;
  5822. for (size_t i = 0; i < test_cases_.size(); i++) {
  5823. TestCase* const test_case = test_cases_[i];
  5824. const std::string &test_case_name = test_case->name();
  5825. test_case->set_should_run(false);
  5826. for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  5827. TestInfo* const test_info = test_case->test_info_list()[j];
  5828. const std::string test_name(test_info->name());
  5829. // A test is disabled if test case name or test name matches
  5830. // kDisableTestFilter.
  5831. const bool is_disabled =
  5832. internal::UnitTestOptions::MatchesFilter(test_case_name,
  5833. kDisableTestFilter) ||
  5834. internal::UnitTestOptions::MatchesFilter(test_name,
  5835. kDisableTestFilter);
  5836. test_info->is_disabled_ = is_disabled;
  5837. const bool matches_filter =
  5838. internal::UnitTestOptions::FilterMatchesTest(test_case_name,
  5839. test_name);
  5840. test_info->matches_filter_ = matches_filter;
  5841. const bool is_runnable =
  5842. (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
  5843. matches_filter;
  5844. const bool is_in_another_shard =
  5845. shard_tests != IGNORE_SHARDING_PROTOCOL &&
  5846. !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
  5847. test_info->is_in_another_shard_ = is_in_another_shard;
  5848. const bool is_selected = is_runnable && !is_in_another_shard;
  5849. num_runnable_tests += is_runnable;
  5850. num_selected_tests += is_selected;
  5851. test_info->should_run_ = is_selected;
  5852. test_case->set_should_run(test_case->should_run() || is_selected);
  5853. }
  5854. }
  5855. return num_selected_tests;
  5856. }
  5857. // Prints the given C-string on a single line by replacing all '\n'
  5858. // characters with string "\\n". If the output takes more than
  5859. // max_length characters, only prints the first max_length characters
  5860. // and "...".
  5861. static void PrintOnOneLine(const char* str, int max_length) {
  5862. if (str != NULL) {
  5863. for (int i = 0; *str != '\0'; ++str) {
  5864. if (i >= max_length) {
  5865. printf("...");
  5866. break;
  5867. }
  5868. if (*str == '\n') {
  5869. printf("\\n");
  5870. i += 2;
  5871. } else {
  5872. printf("%c", *str);
  5873. ++i;
  5874. }
  5875. }
  5876. }
  5877. }
  5878. // Prints the names of the tests matching the user-specified filter flag.
  5879. void UnitTestImpl::ListTestsMatchingFilter() {
  5880. // Print at most this many characters for each type/value parameter.
  5881. const int kMaxParamLength = 250;
  5882. for (size_t i = 0; i < test_cases_.size(); i++) {
  5883. const TestCase* const test_case = test_cases_[i];
  5884. bool printed_test_case_name = false;
  5885. for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  5886. const TestInfo* const test_info =
  5887. test_case->test_info_list()[j];
  5888. if (test_info->matches_filter_) {
  5889. if (!printed_test_case_name) {
  5890. printed_test_case_name = true;
  5891. printf("%s.", test_case->name());
  5892. if (test_case->type_param() != NULL) {
  5893. printf(" # %s = ", kTypeParamLabel);
  5894. // We print the type parameter on a single line to make
  5895. // the output easy to parse by a program.
  5896. PrintOnOneLine(test_case->type_param(), kMaxParamLength);
  5897. }
  5898. printf("\n");
  5899. }
  5900. printf(" %s", test_info->name());
  5901. if (test_info->value_param() != NULL) {
  5902. printf(" # %s = ", kValueParamLabel);
  5903. // We print the value parameter on a single line to make the
  5904. // output easy to parse by a program.
  5905. PrintOnOneLine(test_info->value_param(), kMaxParamLength);
  5906. }
  5907. printf("\n");
  5908. }
  5909. }
  5910. }
  5911. fflush(stdout);
  5912. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  5913. if (output_format == "xml" || output_format == "json") {
  5914. FILE* fileout = OpenFileForWriting(
  5915. UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
  5916. std::stringstream stream;
  5917. if (output_format == "xml") {
  5918. XmlUnitTestResultPrinter(
  5919. UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  5920. .PrintXmlTestsList(&stream, test_cases_);
  5921. } else if (output_format == "json") {
  5922. JsonUnitTestResultPrinter(
  5923. UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  5924. .PrintJsonTestList(&stream, test_cases_);
  5925. }
  5926. fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
  5927. fclose(fileout);
  5928. }
  5929. }
  5930. // Sets the OS stack trace getter.
  5931. //
  5932. // Does nothing if the input and the current OS stack trace getter are
  5933. // the same; otherwise, deletes the old getter and makes the input the
  5934. // current getter.
  5935. void UnitTestImpl::set_os_stack_trace_getter(
  5936. OsStackTraceGetterInterface* getter) {
  5937. if (os_stack_trace_getter_ != getter) {
  5938. delete os_stack_trace_getter_;
  5939. os_stack_trace_getter_ = getter;
  5940. }
  5941. }
  5942. // Returns the current OS stack trace getter if it is not NULL;
  5943. // otherwise, creates an OsStackTraceGetter, makes it the current
  5944. // getter, and returns it.
  5945. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
  5946. if (os_stack_trace_getter_ == NULL) {
  5947. #ifdef GTEST_OS_STACK_TRACE_GETTER_
  5948. os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
  5949. #else
  5950. os_stack_trace_getter_ = new OsStackTraceGetter;
  5951. #endif // GTEST_OS_STACK_TRACE_GETTER_
  5952. }
  5953. return os_stack_trace_getter_;
  5954. }
  5955. // Returns the most specific TestResult currently running.
  5956. TestResult* UnitTestImpl::current_test_result() {
  5957. if (current_test_info_ != NULL) {
  5958. return &current_test_info_->result_;
  5959. }
  5960. if (current_test_case_ != NULL) {
  5961. return &current_test_case_->ad_hoc_test_result_;
  5962. }
  5963. return &ad_hoc_test_result_;
  5964. }
  5965. // Shuffles all test cases, and the tests within each test case,
  5966. // making sure that death tests are still run first.
  5967. void UnitTestImpl::ShuffleTests() {
  5968. // Shuffles the death test cases.
  5969. ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
  5970. // Shuffles the non-death test cases.
  5971. ShuffleRange(random(), last_death_test_case_ + 1,
  5972. static_cast<int>(test_cases_.size()), &test_case_indices_);
  5973. // Shuffles the tests inside each test case.
  5974. for (size_t i = 0; i < test_cases_.size(); i++) {
  5975. test_cases_[i]->ShuffleTests(random());
  5976. }
  5977. }
  5978. // Restores the test cases and tests to their order before the first shuffle.
  5979. void UnitTestImpl::UnshuffleTests() {
  5980. for (size_t i = 0; i < test_cases_.size(); i++) {
  5981. // Unshuffles the tests in each test case.
  5982. test_cases_[i]->UnshuffleTests();
  5983. // Resets the index of each test case.
  5984. test_case_indices_[i] = static_cast<int>(i);
  5985. }
  5986. }
  5987. // Returns the current OS stack trace as an std::string.
  5988. //
  5989. // The maximum number of stack frames to be included is specified by
  5990. // the gtest_stack_trace_depth flag. The skip_count parameter
  5991. // specifies the number of top frames to be skipped, which doesn't
  5992. // count against the number of frames to be included.
  5993. //
  5994. // For example, if Foo() calls Bar(), which in turn calls
  5995. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  5996. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  5997. std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
  5998. int skip_count) {
  5999. // We pass skip_count + 1 to skip this wrapper function in addition
  6000. // to what the user really wants to skip.
  6001. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
  6002. }
  6003. // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
  6004. // suppress unreachable code warnings.
  6005. namespace {
  6006. class ClassUniqueToAlwaysTrue {};
  6007. }
  6008. bool IsTrue(bool condition) { return condition; }
  6009. bool AlwaysTrue() {
  6010. #if GTEST_HAS_EXCEPTIONS
  6011. // This condition is always false so AlwaysTrue() never actually throws,
  6012. // but it makes the compiler think that it may throw.
  6013. if (IsTrue(false))
  6014. throw ClassUniqueToAlwaysTrue();
  6015. #endif // GTEST_HAS_EXCEPTIONS
  6016. return true;
  6017. }
  6018. // If *pstr starts with the given prefix, modifies *pstr to be right
  6019. // past the prefix and returns true; otherwise leaves *pstr unchanged
  6020. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  6021. bool SkipPrefix(const char* prefix, const char** pstr) {
  6022. const size_t prefix_len = strlen(prefix);
  6023. if (strncmp(*pstr, prefix, prefix_len) == 0) {
  6024. *pstr += prefix_len;
  6025. return true;
  6026. }
  6027. return false;
  6028. }
  6029. // Parses a string as a command line flag. The string should have
  6030. // the format "--flag=value". When def_optional is true, the "=value"
  6031. // part can be omitted.
  6032. //
  6033. // Returns the value of the flag, or NULL if the parsing failed.
  6034. static const char* ParseFlagValue(const char* str, const char* flag,
  6035. bool def_optional) {
  6036. // str and flag must not be NULL.
  6037. if (str == NULL || flag == NULL) return NULL;
  6038. // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
  6039. const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
  6040. const size_t flag_len = flag_str.length();
  6041. if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
  6042. // Skips the flag name.
  6043. const char* flag_end = str + flag_len;
  6044. // When def_optional is true, it's OK to not have a "=value" part.
  6045. if (def_optional && (flag_end[0] == '\0')) {
  6046. return flag_end;
  6047. }
  6048. // If def_optional is true and there are more characters after the
  6049. // flag name, or if def_optional is false, there must be a '=' after
  6050. // the flag name.
  6051. if (flag_end[0] != '=') return NULL;
  6052. // Returns the string after "=".
  6053. return flag_end + 1;
  6054. }
  6055. // Parses a string for a bool flag, in the form of either
  6056. // "--flag=value" or "--flag".
  6057. //
  6058. // In the former case, the value is taken as true as long as it does
  6059. // not start with '0', 'f', or 'F'.
  6060. //
  6061. // In the latter case, the value is taken as true.
  6062. //
  6063. // On success, stores the value of the flag in *value, and returns
  6064. // true. On failure, returns false without changing *value.
  6065. static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
  6066. // Gets the value of the flag as a string.
  6067. const char* const value_str = ParseFlagValue(str, flag, true);
  6068. // Aborts if the parsing failed.
  6069. if (value_str == NULL) return false;
  6070. // Converts the string value to a bool.
  6071. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  6072. return true;
  6073. }
  6074. // Parses a string for an Int32 flag, in the form of
  6075. // "--flag=value".
  6076. //
  6077. // On success, stores the value of the flag in *value, and returns
  6078. // true. On failure, returns false without changing *value.
  6079. bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
  6080. // Gets the value of the flag as a string.
  6081. const char* const value_str = ParseFlagValue(str, flag, false);
  6082. // Aborts if the parsing failed.
  6083. if (value_str == NULL) return false;
  6084. // Sets *value to the value of the flag.
  6085. return ParseInt32(Message() << "The value of flag --" << flag,
  6086. value_str, value);
  6087. }
  6088. // Parses a string for a string flag, in the form of
  6089. // "--flag=value".
  6090. //
  6091. // On success, stores the value of the flag in *value, and returns
  6092. // true. On failure, returns false without changing *value.
  6093. template <typename String>
  6094. static bool ParseStringFlag(const char* str, const char* flag, String* value) {
  6095. // Gets the value of the flag as a string.
  6096. const char* const value_str = ParseFlagValue(str, flag, false);
  6097. // Aborts if the parsing failed.
  6098. if (value_str == NULL) return false;
  6099. // Sets *value to the value of the flag.
  6100. *value = value_str;
  6101. return true;
  6102. }
  6103. // Determines whether a string has a prefix that Google Test uses for its
  6104. // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
  6105. // If Google Test detects that a command line flag has its prefix but is not
  6106. // recognized, it will print its help message. Flags starting with
  6107. // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
  6108. // internal flags and do not trigger the help message.
  6109. static bool HasGoogleTestFlagPrefix(const char* str) {
  6110. return (SkipPrefix("--", &str) ||
  6111. SkipPrefix("-", &str) ||
  6112. SkipPrefix("/", &str)) &&
  6113. !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
  6114. (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
  6115. SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
  6116. }
  6117. // Prints a string containing code-encoded text. The following escape
  6118. // sequences can be used in the string to control the text color:
  6119. //
  6120. // @@ prints a single '@' character.
  6121. // @R changes the color to red.
  6122. // @G changes the color to green.
  6123. // @Y changes the color to yellow.
  6124. // @D changes to the default terminal text color.
  6125. //
  6126. // FIXME: Write tests for this once we add stdout
  6127. // capturing to Google Test.
  6128. static void PrintColorEncoded(const char* str) {
  6129. GTestColor color = COLOR_DEFAULT; // The current color.
  6130. // Conceptually, we split the string into segments divided by escape
  6131. // sequences. Then we print one segment at a time. At the end of
  6132. // each iteration, the str pointer advances to the beginning of the
  6133. // next segment.
  6134. for (;;) {
  6135. const char* p = strchr(str, '@');
  6136. if (p == NULL) {
  6137. ColoredPrintf(color, "%s", str);
  6138. return;
  6139. }
  6140. ColoredPrintf(color, "%s", std::string(str, p).c_str());
  6141. const char ch = p[1];
  6142. str = p + 2;
  6143. if (ch == '@') {
  6144. ColoredPrintf(color, "@");
  6145. } else if (ch == 'D') {
  6146. color = COLOR_DEFAULT;
  6147. } else if (ch == 'R') {
  6148. color = COLOR_RED;
  6149. } else if (ch == 'G') {
  6150. color = COLOR_GREEN;
  6151. } else if (ch == 'Y') {
  6152. color = COLOR_YELLOW;
  6153. } else {
  6154. --str;
  6155. }
  6156. }
  6157. }
  6158. static const char kColorEncodedHelpMessage[] =
  6159. "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
  6160. "following command line flags to control its behavior:\n"
  6161. "\n"
  6162. "Test Selection:\n"
  6163. " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
  6164. " List the names of all tests instead of running them. The name of\n"
  6165. " TEST(Foo, Bar) is \"Foo.Bar\".\n"
  6166. " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
  6167. "[@G-@YNEGATIVE_PATTERNS]@D\n"
  6168. " Run only the tests whose name matches one of the positive patterns but\n"
  6169. " none of the negative patterns. '?' matches any single character; '*'\n"
  6170. " matches any substring; ':' separates two patterns.\n"
  6171. " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
  6172. " Run all disabled tests too.\n"
  6173. "\n"
  6174. "Test Execution:\n"
  6175. " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
  6176. " Run the tests repeatedly; use a negative count to repeat forever.\n"
  6177. " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
  6178. " Randomize tests' orders on every iteration.\n"
  6179. " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
  6180. " Random number seed to use for shuffling test orders (between 1 and\n"
  6181. " 99999, or 0 to use a seed based on the current time).\n"
  6182. "\n"
  6183. "Test Output:\n"
  6184. " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
  6185. " Enable/disable colored output. The default is @Gauto@D.\n"
  6186. " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
  6187. " Don't print the elapsed time of each test.\n"
  6188. " @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
  6189. GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
  6190. " Generate a JSON or XML report in the given directory or with the given\n"
  6191. " file name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
  6192. # if GTEST_CAN_STREAM_RESULTS_
  6193. " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
  6194. " Stream test results to the given server.\n"
  6195. # endif // GTEST_CAN_STREAM_RESULTS_
  6196. "\n"
  6197. "Assertion Behavior:\n"
  6198. # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  6199. " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
  6200. " Set the default death test style.\n"
  6201. # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  6202. " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
  6203. " Turn assertion failures into debugger break-points.\n"
  6204. " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
  6205. " Turn assertion failures into C++ exceptions for use by an external\n"
  6206. " test framework.\n"
  6207. " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
  6208. " Do not report exceptions as test failures. Instead, allow them\n"
  6209. " to crash the program or throw a pop-up (on Windows).\n"
  6210. "\n"
  6211. "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
  6212. "the corresponding\n"
  6213. "environment variable of a flag (all letters in upper-case). For example, to\n"
  6214. "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
  6215. "color=no@D or set\n"
  6216. "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
  6217. "\n"
  6218. "For more information, please read the " GTEST_NAME_ " documentation at\n"
  6219. "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
  6220. "(not one in your own code or tests), please report it to\n"
  6221. "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
  6222. static bool ParseGoogleTestFlag(const char* const arg) {
  6223. return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
  6224. &GTEST_FLAG(also_run_disabled_tests)) ||
  6225. ParseBoolFlag(arg, kBreakOnFailureFlag,
  6226. &GTEST_FLAG(break_on_failure)) ||
  6227. ParseBoolFlag(arg, kCatchExceptionsFlag,
  6228. &GTEST_FLAG(catch_exceptions)) ||
  6229. ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
  6230. ParseStringFlag(arg, kDeathTestStyleFlag,
  6231. &GTEST_FLAG(death_test_style)) ||
  6232. ParseBoolFlag(arg, kDeathTestUseFork,
  6233. &GTEST_FLAG(death_test_use_fork)) ||
  6234. ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
  6235. ParseStringFlag(arg, kInternalRunDeathTestFlag,
  6236. &GTEST_FLAG(internal_run_death_test)) ||
  6237. ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
  6238. ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
  6239. ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
  6240. ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
  6241. ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
  6242. ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
  6243. ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
  6244. ParseInt32Flag(arg, kStackTraceDepthFlag,
  6245. &GTEST_FLAG(stack_trace_depth)) ||
  6246. ParseStringFlag(arg, kStreamResultToFlag,
  6247. &GTEST_FLAG(stream_result_to)) ||
  6248. ParseBoolFlag(arg, kThrowOnFailureFlag,
  6249. &GTEST_FLAG(throw_on_failure));
  6250. }
  6251. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  6252. static void LoadFlagsFromFile(const std::string& path) {
  6253. FILE* flagfile = posix::FOpen(path.c_str(), "r");
  6254. if (!flagfile) {
  6255. GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
  6256. << "\"";
  6257. }
  6258. std::string contents(ReadEntireFile(flagfile));
  6259. posix::FClose(flagfile);
  6260. std::vector<std::string> lines;
  6261. SplitString(contents, '\n', &lines);
  6262. for (size_t i = 0; i < lines.size(); ++i) {
  6263. if (lines[i].empty())
  6264. continue;
  6265. if (!ParseGoogleTestFlag(lines[i].c_str()))
  6266. g_help_flag = true;
  6267. }
  6268. }
  6269. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  6270. // Parses the command line for Google Test flags, without initializing
  6271. // other parts of Google Test. The type parameter CharType can be
  6272. // instantiated to either char or wchar_t.
  6273. template <typename CharType>
  6274. void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
  6275. for (int i = 1; i < *argc; i++) {
  6276. const std::string arg_string = StreamableToString(argv[i]);
  6277. const char* const arg = arg_string.c_str();
  6278. using internal::ParseBoolFlag;
  6279. using internal::ParseInt32Flag;
  6280. using internal::ParseStringFlag;
  6281. bool remove_flag = false;
  6282. if (ParseGoogleTestFlag(arg)) {
  6283. remove_flag = true;
  6284. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  6285. } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
  6286. LoadFlagsFromFile(GTEST_FLAG(flagfile));
  6287. remove_flag = true;
  6288. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  6289. } else if (arg_string == "--help" || arg_string == "-h" ||
  6290. arg_string == "-?" || arg_string == "/?" ||
  6291. HasGoogleTestFlagPrefix(arg)) {
  6292. // Both help flag and unrecognized Google Test flags (excluding
  6293. // internal ones) trigger help display.
  6294. g_help_flag = true;
  6295. }
  6296. if (remove_flag) {
  6297. // Shift the remainder of the argv list left by one. Note
  6298. // that argv has (*argc + 1) elements, the last one always being
  6299. // NULL. The following loop moves the trailing NULL element as
  6300. // well.
  6301. for (int j = i; j != *argc; j++) {
  6302. argv[j] = argv[j + 1];
  6303. }
  6304. // Decrements the argument count.
  6305. (*argc)--;
  6306. // We also need to decrement the iterator as we just removed
  6307. // an element.
  6308. i--;
  6309. }
  6310. }
  6311. if (g_help_flag) {
  6312. // We print the help here instead of in RUN_ALL_TESTS(), as the
  6313. // latter may not be called at all if the user is using Google
  6314. // Test with another testing framework.
  6315. PrintColorEncoded(kColorEncodedHelpMessage);
  6316. }
  6317. }
  6318. // Parses the command line for Google Test flags, without initializing
  6319. // other parts of Google Test.
  6320. void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
  6321. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  6322. // Fix the value of *_NSGetArgc() on macOS, but iff
  6323. // *_NSGetArgv() == argv
  6324. // Only applicable to char** version of argv
  6325. #if GTEST_OS_MAC
  6326. #ifndef GTEST_OS_IOS
  6327. if (*_NSGetArgv() == argv) {
  6328. *_NSGetArgc() = *argc;
  6329. }
  6330. #endif
  6331. #endif
  6332. }
  6333. void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
  6334. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  6335. }
  6336. // The internal implementation of InitGoogleTest().
  6337. //
  6338. // The type parameter CharType can be instantiated to either char or
  6339. // wchar_t.
  6340. template <typename CharType>
  6341. void InitGoogleTestImpl(int* argc, CharType** argv) {
  6342. // We don't want to run the initialization code twice.
  6343. if (GTestIsInitialized()) return;
  6344. if (*argc <= 0) return;
  6345. g_argvs.clear();
  6346. for (int i = 0; i != *argc; i++) {
  6347. g_argvs.push_back(StreamableToString(argv[i]));
  6348. }
  6349. #if GTEST_HAS_ABSL
  6350. absl::InitializeSymbolizer(g_argvs[0].c_str());
  6351. #endif // GTEST_HAS_ABSL
  6352. ParseGoogleTestFlagsOnly(argc, argv);
  6353. GetUnitTestImpl()->PostFlagParsingInit();
  6354. }
  6355. } // namespace internal
  6356. // Initializes Google Test. This must be called before calling
  6357. // RUN_ALL_TESTS(). In particular, it parses a command line for the
  6358. // flags that Google Test recognizes. Whenever a Google Test flag is
  6359. // seen, it is removed from argv, and *argc is decremented.
  6360. //
  6361. // No value is returned. Instead, the Google Test flag variables are
  6362. // updated.
  6363. //
  6364. // Calling the function for the second time has no user-visible effect.
  6365. void InitGoogleTest(int* argc, char** argv) {
  6366. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6367. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  6368. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6369. internal::InitGoogleTestImpl(argc, argv);
  6370. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6371. }
  6372. // This overloaded version can be used in Windows programs compiled in
  6373. // UNICODE mode.
  6374. void InitGoogleTest(int* argc, wchar_t** argv) {
  6375. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6376. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  6377. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6378. internal::InitGoogleTestImpl(argc, argv);
  6379. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6380. }
  6381. std::string TempDir() {
  6382. #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
  6383. return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
  6384. #endif
  6385. #if GTEST_OS_WINDOWS_MOBILE
  6386. return "\\temp\\";
  6387. #elif GTEST_OS_WINDOWS
  6388. const char* temp_dir = internal::posix::GetEnv("TEMP");
  6389. if (temp_dir == NULL || temp_dir[0] == '\0')
  6390. return "\\temp\\";
  6391. else if (temp_dir[strlen(temp_dir) - 1] == '\\')
  6392. return temp_dir;
  6393. else
  6394. return std::string(temp_dir) + "\\";
  6395. #elif GTEST_OS_LINUX_ANDROID
  6396. return "/sdcard/";
  6397. #else
  6398. return "/tmp/";
  6399. #endif // GTEST_OS_WINDOWS_MOBILE
  6400. }
  6401. // Class ScopedTrace
  6402. // Pushes the given source file location and message onto a per-thread
  6403. // trace stack maintained by Google Test.
  6404. void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
  6405. internal::TraceInfo trace;
  6406. trace.file = file;
  6407. trace.line = line;
  6408. trace.message.swap(message);
  6409. UnitTest::GetInstance()->PushGTestTrace(trace);
  6410. }
  6411. // Pops the info pushed by the c'tor.
  6412. ScopedTrace::~ScopedTrace()
  6413. GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
  6414. UnitTest::GetInstance()->PopGTestTrace();
  6415. }
  6416. } // namespace testing
  6417. // Copyright 2005, Google Inc.
  6418. // All rights reserved.
  6419. //
  6420. // Redistribution and use in source and binary forms, with or without
  6421. // modification, are permitted provided that the following conditions are
  6422. // met:
  6423. //
  6424. // * Redistributions of source code must retain the above copyright
  6425. // notice, this list of conditions and the following disclaimer.
  6426. // * Redistributions in binary form must reproduce the above
  6427. // copyright notice, this list of conditions and the following disclaimer
  6428. // in the documentation and/or other materials provided with the
  6429. // distribution.
  6430. // * Neither the name of Google Inc. nor the names of its
  6431. // contributors may be used to endorse or promote products derived from
  6432. // this software without specific prior written permission.
  6433. //
  6434. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6435. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6436. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6437. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6438. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6439. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6440. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6441. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6442. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6443. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6444. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6445. //
  6446. // This file implements death tests.
  6447. #if GTEST_HAS_DEATH_TEST
  6448. # if GTEST_OS_MAC
  6449. # include <crt_externs.h>
  6450. # endif // GTEST_OS_MAC
  6451. # include <errno.h>
  6452. # include <fcntl.h>
  6453. # include <limits.h>
  6454. # if GTEST_OS_LINUX
  6455. # include <signal.h>
  6456. # endif // GTEST_OS_LINUX
  6457. # include <stdarg.h>
  6458. # if GTEST_OS_WINDOWS
  6459. # include <windows.h>
  6460. # else
  6461. # include <sys/mman.h>
  6462. # include <sys/wait.h>
  6463. # endif // GTEST_OS_WINDOWS
  6464. # if GTEST_OS_QNX
  6465. # include <spawn.h>
  6466. # endif // GTEST_OS_QNX
  6467. # if GTEST_OS_FUCHSIA
  6468. # include <lib/fdio/io.h>
  6469. # include <lib/fdio/spawn.h>
  6470. # include <zircon/processargs.h>
  6471. # include <zircon/syscalls.h>
  6472. # include <zircon/syscalls/port.h>
  6473. # endif // GTEST_OS_FUCHSIA
  6474. #endif // GTEST_HAS_DEATH_TEST
  6475. namespace testing {
  6476. // Constants.
  6477. // The default death test style.
  6478. //
  6479. // This is defined in internal/gtest-port.h as "fast", but can be overridden by
  6480. // a definition in internal/custom/gtest-port.h. The recommended value, which is
  6481. // used internally at Google, is "threadsafe".
  6482. static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
  6483. GTEST_DEFINE_string_(
  6484. death_test_style,
  6485. internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
  6486. "Indicates how to run a death test in a forked child process: "
  6487. "\"threadsafe\" (child process re-executes the test binary "
  6488. "from the beginning, running only the specific death test) or "
  6489. "\"fast\" (child process runs the death test immediately "
  6490. "after forking).");
  6491. GTEST_DEFINE_bool_(
  6492. death_test_use_fork,
  6493. internal::BoolFromGTestEnv("death_test_use_fork", false),
  6494. "Instructs to use fork()/_exit() instead of clone() in death tests. "
  6495. "Ignored and always uses fork() on POSIX systems where clone() is not "
  6496. "implemented. Useful when running under valgrind or similar tools if "
  6497. "those do not support clone(). Valgrind 3.3.1 will just fail if "
  6498. "it sees an unsupported combination of clone() flags. "
  6499. "It is not recommended to use this flag w/o valgrind though it will "
  6500. "work in 99% of the cases. Once valgrind is fixed, this flag will "
  6501. "most likely be removed.");
  6502. namespace internal {
  6503. GTEST_DEFINE_string_(
  6504. internal_run_death_test, "",
  6505. "Indicates the file, line number, temporal index of "
  6506. "the single death test to run, and a file descriptor to "
  6507. "which a success code may be sent, all separated by "
  6508. "the '|' characters. This flag is specified if and only if the current "
  6509. "process is a sub-process launched for running a thread-safe "
  6510. "death test. FOR INTERNAL USE ONLY.");
  6511. } // namespace internal
  6512. #if GTEST_HAS_DEATH_TEST
  6513. namespace internal {
  6514. // Valid only for fast death tests. Indicates the code is running in the
  6515. // child process of a fast style death test.
  6516. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6517. static bool g_in_fast_death_test_child = false;
  6518. # endif
  6519. // Returns a Boolean value indicating whether the caller is currently
  6520. // executing in the context of the death test child process. Tools such as
  6521. // Valgrind heap checkers may need this to modify their behavior in death
  6522. // tests. IMPORTANT: This is an internal utility. Using it may break the
  6523. // implementation of death tests. User code MUST NOT use it.
  6524. bool InDeathTestChild() {
  6525. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6526. // On Windows and Fuchsia, death tests are thread-safe regardless of the value
  6527. // of the death_test_style flag.
  6528. return !GTEST_FLAG(internal_run_death_test).empty();
  6529. # else
  6530. if (GTEST_FLAG(death_test_style) == "threadsafe")
  6531. return !GTEST_FLAG(internal_run_death_test).empty();
  6532. else
  6533. return g_in_fast_death_test_child;
  6534. #endif
  6535. }
  6536. } // namespace internal
  6537. // ExitedWithCode constructor.
  6538. ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
  6539. }
  6540. // ExitedWithCode function-call operator.
  6541. bool ExitedWithCode::operator()(int exit_status) const {
  6542. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6543. return exit_status == exit_code_;
  6544. # else
  6545. return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
  6546. # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6547. }
  6548. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6549. // KilledBySignal constructor.
  6550. KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
  6551. }
  6552. // KilledBySignal function-call operator.
  6553. bool KilledBySignal::operator()(int exit_status) const {
  6554. # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
  6555. {
  6556. bool result;
  6557. if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
  6558. return result;
  6559. }
  6560. }
  6561. # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
  6562. return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
  6563. }
  6564. # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6565. namespace internal {
  6566. // Utilities needed for death tests.
  6567. // Generates a textual description of a given exit code, in the format
  6568. // specified by wait(2).
  6569. static std::string ExitSummary(int exit_code) {
  6570. Message m;
  6571. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6572. m << "Exited with exit status " << exit_code;
  6573. # else
  6574. if (WIFEXITED(exit_code)) {
  6575. m << "Exited with exit status " << WEXITSTATUS(exit_code);
  6576. } else if (WIFSIGNALED(exit_code)) {
  6577. m << "Terminated by signal " << WTERMSIG(exit_code);
  6578. }
  6579. # ifdef WCOREDUMP
  6580. if (WCOREDUMP(exit_code)) {
  6581. m << " (core dumped)";
  6582. }
  6583. # endif
  6584. # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6585. return m.GetString();
  6586. }
  6587. // Returns true if exit_status describes a process that was terminated
  6588. // by a signal, or exited normally with a nonzero exit code.
  6589. bool ExitedUnsuccessfully(int exit_status) {
  6590. return !ExitedWithCode(0)(exit_status);
  6591. }
  6592. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6593. // Generates a textual failure message when a death test finds more than
  6594. // one thread running, or cannot determine the number of threads, prior
  6595. // to executing the given statement. It is the responsibility of the
  6596. // caller not to pass a thread_count of 1.
  6597. static std::string DeathTestThreadWarning(size_t thread_count) {
  6598. Message msg;
  6599. msg << "Death tests use fork(), which is unsafe particularly"
  6600. << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
  6601. if (thread_count == 0) {
  6602. msg << "couldn't detect the number of threads.";
  6603. } else {
  6604. msg << "detected " << thread_count << " threads.";
  6605. }
  6606. msg << " See "
  6607. "https://github.com/google/googletest/blob/master/googletest/docs/"
  6608. "advanced.md#death-tests-and-threads"
  6609. << " for more explanation and suggested solutions, especially if"
  6610. << " this is the last message you see before your test times out.";
  6611. return msg.GetString();
  6612. }
  6613. # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6614. // Flag characters for reporting a death test that did not die.
  6615. static const char kDeathTestLived = 'L';
  6616. static const char kDeathTestReturned = 'R';
  6617. static const char kDeathTestThrew = 'T';
  6618. static const char kDeathTestInternalError = 'I';
  6619. #if GTEST_OS_FUCHSIA
  6620. // File descriptor used for the pipe in the child process.
  6621. static const int kFuchsiaReadPipeFd = 3;
  6622. #endif
  6623. // An enumeration describing all of the possible ways that a death test can
  6624. // conclude. DIED means that the process died while executing the test
  6625. // code; LIVED means that process lived beyond the end of the test code;
  6626. // RETURNED means that the test statement attempted to execute a return
  6627. // statement, which is not allowed; THREW means that the test statement
  6628. // returned control by throwing an exception. IN_PROGRESS means the test
  6629. // has not yet concluded.
  6630. // FIXME: Unify names and possibly values for
  6631. // AbortReason, DeathTestOutcome, and flag characters above.
  6632. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
  6633. // Routine for aborting the program which is safe to call from an
  6634. // exec-style death test child process, in which case the error
  6635. // message is propagated back to the parent process. Otherwise, the
  6636. // message is simply printed to stderr. In either case, the program
  6637. // then exits with status 1.
  6638. static void DeathTestAbort(const std::string& message) {
  6639. // On a POSIX system, this function may be called from a threadsafe-style
  6640. // death test child process, which operates on a very small stack. Use
  6641. // the heap for any additional non-minuscule memory requirements.
  6642. const InternalRunDeathTestFlag* const flag =
  6643. GetUnitTestImpl()->internal_run_death_test_flag();
  6644. if (flag != NULL) {
  6645. FILE* parent = posix::FDOpen(flag->write_fd(), "w");
  6646. fputc(kDeathTestInternalError, parent);
  6647. fprintf(parent, "%s", message.c_str());
  6648. fflush(parent);
  6649. _exit(1);
  6650. } else {
  6651. fprintf(stderr, "%s", message.c_str());
  6652. fflush(stderr);
  6653. posix::Abort();
  6654. }
  6655. }
  6656. // A replacement for CHECK that calls DeathTestAbort if the assertion
  6657. // fails.
  6658. # define GTEST_DEATH_TEST_CHECK_(expression) \
  6659. do { \
  6660. if (!::testing::internal::IsTrue(expression)) { \
  6661. DeathTestAbort( \
  6662. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  6663. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  6664. + #expression); \
  6665. } \
  6666. } while (::testing::internal::AlwaysFalse())
  6667. // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
  6668. // evaluating any system call that fulfills two conditions: it must return
  6669. // -1 on failure, and set errno to EINTR when it is interrupted and
  6670. // should be tried again. The macro expands to a loop that repeatedly
  6671. // evaluates the expression as long as it evaluates to -1 and sets
  6672. // errno to EINTR. If the expression evaluates to -1 but errno is
  6673. // something other than EINTR, DeathTestAbort is called.
  6674. # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
  6675. do { \
  6676. int gtest_retval; \
  6677. do { \
  6678. gtest_retval = (expression); \
  6679. } while (gtest_retval == -1 && errno == EINTR); \
  6680. if (gtest_retval == -1) { \
  6681. DeathTestAbort( \
  6682. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  6683. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  6684. + #expression + " != -1"); \
  6685. } \
  6686. } while (::testing::internal::AlwaysFalse())
  6687. // Returns the message describing the last system error in errno.
  6688. std::string GetLastErrnoDescription() {
  6689. return errno == 0 ? "" : posix::StrError(errno);
  6690. }
  6691. // This is called from a death test parent process to read a failure
  6692. // message from the death test child process and log it with the FATAL
  6693. // severity. On Windows, the message is read from a pipe handle. On other
  6694. // platforms, it is read from a file descriptor.
  6695. static void FailFromInternalError(int fd) {
  6696. Message error;
  6697. char buffer[256];
  6698. int num_read;
  6699. do {
  6700. while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
  6701. buffer[num_read] = '\0';
  6702. error << buffer;
  6703. }
  6704. } while (num_read == -1 && errno == EINTR);
  6705. if (num_read == 0) {
  6706. GTEST_LOG_(FATAL) << error.GetString();
  6707. } else {
  6708. const int last_error = errno;
  6709. GTEST_LOG_(FATAL) << "Error while reading death test internal: "
  6710. << GetLastErrnoDescription() << " [" << last_error << "]";
  6711. }
  6712. }
  6713. // Death test constructor. Increments the running death test count
  6714. // for the current test.
  6715. DeathTest::DeathTest() {
  6716. TestInfo* const info = GetUnitTestImpl()->current_test_info();
  6717. if (info == NULL) {
  6718. DeathTestAbort("Cannot run a death test outside of a TEST or "
  6719. "TEST_F construct");
  6720. }
  6721. }
  6722. // Creates and returns a death test by dispatching to the current
  6723. // death test factory.
  6724. bool DeathTest::Create(const char* statement, const RE* regex,
  6725. const char* file, int line, DeathTest** test) {
  6726. return GetUnitTestImpl()->death_test_factory()->Create(
  6727. statement, regex, file, line, test);
  6728. }
  6729. const char* DeathTest::LastMessage() {
  6730. return last_death_test_message_.c_str();
  6731. }
  6732. void DeathTest::set_last_death_test_message(const std::string& message) {
  6733. last_death_test_message_ = message;
  6734. }
  6735. std::string DeathTest::last_death_test_message_;
  6736. // Provides cross platform implementation for some death functionality.
  6737. class DeathTestImpl : public DeathTest {
  6738. protected:
  6739. DeathTestImpl(const char* a_statement, const RE* a_regex)
  6740. : statement_(a_statement),
  6741. regex_(a_regex),
  6742. spawned_(false),
  6743. status_(-1),
  6744. outcome_(IN_PROGRESS),
  6745. read_fd_(-1),
  6746. write_fd_(-1) {}
  6747. // read_fd_ is expected to be closed and cleared by a derived class.
  6748. ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
  6749. void Abort(AbortReason reason);
  6750. virtual bool Passed(bool status_ok);
  6751. const char* statement() const { return statement_; }
  6752. const RE* regex() const { return regex_; }
  6753. bool spawned() const { return spawned_; }
  6754. void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
  6755. int status() const { return status_; }
  6756. void set_status(int a_status) { status_ = a_status; }
  6757. DeathTestOutcome outcome() const { return outcome_; }
  6758. void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
  6759. int read_fd() const { return read_fd_; }
  6760. void set_read_fd(int fd) { read_fd_ = fd; }
  6761. int write_fd() const { return write_fd_; }
  6762. void set_write_fd(int fd) { write_fd_ = fd; }
  6763. // Called in the parent process only. Reads the result code of the death
  6764. // test child process via a pipe, interprets it to set the outcome_
  6765. // member, and closes read_fd_. Outputs diagnostics and terminates in
  6766. // case of unexpected codes.
  6767. void ReadAndInterpretStatusByte();
  6768. private:
  6769. // The textual content of the code this object is testing. This class
  6770. // doesn't own this string and should not attempt to delete it.
  6771. const char* const statement_;
  6772. // The regular expression which test output must match. DeathTestImpl
  6773. // doesn't own this object and should not attempt to delete it.
  6774. const RE* const regex_;
  6775. // True if the death test child process has been successfully spawned.
  6776. bool spawned_;
  6777. // The exit status of the child process.
  6778. int status_;
  6779. // How the death test concluded.
  6780. DeathTestOutcome outcome_;
  6781. // Descriptor to the read end of the pipe to the child process. It is
  6782. // always -1 in the child process. The child keeps its write end of the
  6783. // pipe in write_fd_.
  6784. int read_fd_;
  6785. // Descriptor to the child's write end of the pipe to the parent process.
  6786. // It is always -1 in the parent process. The parent keeps its end of the
  6787. // pipe in read_fd_.
  6788. int write_fd_;
  6789. };
  6790. // Called in the parent process only. Reads the result code of the death
  6791. // test child process via a pipe, interprets it to set the outcome_
  6792. // member, and closes read_fd_. Outputs diagnostics and terminates in
  6793. // case of unexpected codes.
  6794. void DeathTestImpl::ReadAndInterpretStatusByte() {
  6795. char flag;
  6796. int bytes_read;
  6797. // The read() here blocks until data is available (signifying the
  6798. // failure of the death test) or until the pipe is closed (signifying
  6799. // its success), so it's okay to call this in the parent before
  6800. // the child process has exited.
  6801. do {
  6802. bytes_read = posix::Read(read_fd(), &flag, 1);
  6803. } while (bytes_read == -1 && errno == EINTR);
  6804. if (bytes_read == 0) {
  6805. set_outcome(DIED);
  6806. } else if (bytes_read == 1) {
  6807. switch (flag) {
  6808. case kDeathTestReturned:
  6809. set_outcome(RETURNED);
  6810. break;
  6811. case kDeathTestThrew:
  6812. set_outcome(THREW);
  6813. break;
  6814. case kDeathTestLived:
  6815. set_outcome(LIVED);
  6816. break;
  6817. case kDeathTestInternalError:
  6818. FailFromInternalError(read_fd()); // Does not return.
  6819. break;
  6820. default:
  6821. GTEST_LOG_(FATAL) << "Death test child process reported "
  6822. << "unexpected status byte ("
  6823. << static_cast<unsigned int>(flag) << ")";
  6824. }
  6825. } else {
  6826. GTEST_LOG_(FATAL) << "Read from death test child process failed: "
  6827. << GetLastErrnoDescription();
  6828. }
  6829. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
  6830. set_read_fd(-1);
  6831. }
  6832. // Signals that the death test code which should have exited, didn't.
  6833. // Should be called only in a death test child process.
  6834. // Writes a status byte to the child's status file descriptor, then
  6835. // calls _exit(1).
  6836. void DeathTestImpl::Abort(AbortReason reason) {
  6837. // The parent process considers the death test to be a failure if
  6838. // it finds any data in our pipe. So, here we write a single flag byte
  6839. // to the pipe, then exit.
  6840. const char status_ch =
  6841. reason == TEST_DID_NOT_DIE ? kDeathTestLived :
  6842. reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
  6843. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
  6844. // We are leaking the descriptor here because on some platforms (i.e.,
  6845. // when built as Windows DLL), destructors of global objects will still
  6846. // run after calling _exit(). On such systems, write_fd_ will be
  6847. // indirectly closed from the destructor of UnitTestImpl, causing double
  6848. // close if it is also closed here. On debug configurations, double close
  6849. // may assert. As there are no in-process buffers to flush here, we are
  6850. // relying on the OS to close the descriptor after the process terminates
  6851. // when the destructors are not run.
  6852. _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
  6853. }
  6854. // Returns an indented copy of stderr output for a death test.
  6855. // This makes distinguishing death test output lines from regular log lines
  6856. // much easier.
  6857. static ::std::string FormatDeathTestOutput(const ::std::string& output) {
  6858. ::std::string ret;
  6859. for (size_t at = 0; ; ) {
  6860. const size_t line_end = output.find('\n', at);
  6861. ret += "[ DEATH ] ";
  6862. if (line_end == ::std::string::npos) {
  6863. ret += output.substr(at);
  6864. break;
  6865. }
  6866. ret += output.substr(at, line_end + 1 - at);
  6867. at = line_end + 1;
  6868. }
  6869. return ret;
  6870. }
  6871. // Assesses the success or failure of a death test, using both private
  6872. // members which have previously been set, and one argument:
  6873. //
  6874. // Private data members:
  6875. // outcome: An enumeration describing how the death test
  6876. // concluded: DIED, LIVED, THREW, or RETURNED. The death test
  6877. // fails in the latter three cases.
  6878. // status: The exit status of the child process. On *nix, it is in the
  6879. // in the format specified by wait(2). On Windows, this is the
  6880. // value supplied to the ExitProcess() API or a numeric code
  6881. // of the exception that terminated the program.
  6882. // regex: A regular expression object to be applied to
  6883. // the test's captured standard error output; the death test
  6884. // fails if it does not match.
  6885. //
  6886. // Argument:
  6887. // status_ok: true if exit_status is acceptable in the context of
  6888. // this particular death test, which fails if it is false
  6889. //
  6890. // Returns true iff all of the above conditions are met. Otherwise, the
  6891. // first failing condition, in the order given above, is the one that is
  6892. // reported. Also sets the last death test message string.
  6893. bool DeathTestImpl::Passed(bool status_ok) {
  6894. if (!spawned())
  6895. return false;
  6896. const std::string error_message = GetCapturedStderr();
  6897. bool success = false;
  6898. Message buffer;
  6899. buffer << "Death test: " << statement() << "\n";
  6900. switch (outcome()) {
  6901. case LIVED:
  6902. buffer << " Result: failed to die.\n"
  6903. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6904. break;
  6905. case THREW:
  6906. buffer << " Result: threw an exception.\n"
  6907. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6908. break;
  6909. case RETURNED:
  6910. buffer << " Result: illegal return in test statement.\n"
  6911. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6912. break;
  6913. case DIED:
  6914. if (status_ok) {
  6915. # if GTEST_USES_PCRE
  6916. // PCRE regexes support embedded NULs.
  6917. const bool matched = RE::PartialMatch(error_message, *regex());
  6918. # else
  6919. const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
  6920. # endif // GTEST_USES_PCRE
  6921. if (matched) {
  6922. success = true;
  6923. } else {
  6924. buffer << " Result: died but not with expected error.\n"
  6925. << " Expected: " << regex()->pattern() << "\n"
  6926. << "Actual msg:\n" << FormatDeathTestOutput(error_message);
  6927. }
  6928. } else {
  6929. buffer << " Result: died but not with expected exit code:\n"
  6930. << " " << ExitSummary(status()) << "\n"
  6931. << "Actual msg:\n" << FormatDeathTestOutput(error_message);
  6932. }
  6933. break;
  6934. case IN_PROGRESS:
  6935. default:
  6936. GTEST_LOG_(FATAL)
  6937. << "DeathTest::Passed somehow called before conclusion of test";
  6938. }
  6939. DeathTest::set_last_death_test_message(buffer.GetString());
  6940. return success;
  6941. }
  6942. # if GTEST_OS_WINDOWS
  6943. // WindowsDeathTest implements death tests on Windows. Due to the
  6944. // specifics of starting new processes on Windows, death tests there are
  6945. // always threadsafe, and Google Test considers the
  6946. // --gtest_death_test_style=fast setting to be equivalent to
  6947. // --gtest_death_test_style=threadsafe there.
  6948. //
  6949. // A few implementation notes: Like the Linux version, the Windows
  6950. // implementation uses pipes for child-to-parent communication. But due to
  6951. // the specifics of pipes on Windows, some extra steps are required:
  6952. //
  6953. // 1. The parent creates a communication pipe and stores handles to both
  6954. // ends of it.
  6955. // 2. The parent starts the child and provides it with the information
  6956. // necessary to acquire the handle to the write end of the pipe.
  6957. // 3. The child acquires the write end of the pipe and signals the parent
  6958. // using a Windows event.
  6959. // 4. Now the parent can release the write end of the pipe on its side. If
  6960. // this is done before step 3, the object's reference count goes down to
  6961. // 0 and it is destroyed, preventing the child from acquiring it. The
  6962. // parent now has to release it, or read operations on the read end of
  6963. // the pipe will not return when the child terminates.
  6964. // 5. The parent reads child's output through the pipe (outcome code and
  6965. // any possible error messages) from the pipe, and its stderr and then
  6966. // determines whether to fail the test.
  6967. //
  6968. // Note: to distinguish Win32 API calls from the local method and function
  6969. // calls, the former are explicitly resolved in the global namespace.
  6970. //
  6971. class WindowsDeathTest : public DeathTestImpl {
  6972. public:
  6973. WindowsDeathTest(const char* a_statement,
  6974. const RE* a_regex,
  6975. const char* file,
  6976. int line)
  6977. : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
  6978. // All of these virtual functions are inherited from DeathTest.
  6979. virtual int Wait();
  6980. virtual TestRole AssumeRole();
  6981. private:
  6982. // The name of the file in which the death test is located.
  6983. const char* const file_;
  6984. // The line number on which the death test is located.
  6985. const int line_;
  6986. // Handle to the write end of the pipe to the child process.
  6987. AutoHandle write_handle_;
  6988. // Child process handle.
  6989. AutoHandle child_handle_;
  6990. // Event the child process uses to signal the parent that it has
  6991. // acquired the handle to the write end of the pipe. After seeing this
  6992. // event the parent can release its own handles to make sure its
  6993. // ReadFile() calls return when the child terminates.
  6994. AutoHandle event_handle_;
  6995. };
  6996. // Waits for the child in a death test to exit, returning its exit
  6997. // status, or 0 if no child process exists. As a side effect, sets the
  6998. // outcome data member.
  6999. int WindowsDeathTest::Wait() {
  7000. if (!spawned())
  7001. return 0;
  7002. // Wait until the child either signals that it has acquired the write end
  7003. // of the pipe or it dies.
  7004. const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
  7005. switch (::WaitForMultipleObjects(2,
  7006. wait_handles,
  7007. FALSE, // Waits for any of the handles.
  7008. INFINITE)) {
  7009. case WAIT_OBJECT_0:
  7010. case WAIT_OBJECT_0 + 1:
  7011. break;
  7012. default:
  7013. GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
  7014. }
  7015. // The child has acquired the write end of the pipe or exited.
  7016. // We release the handle on our side and continue.
  7017. write_handle_.Reset();
  7018. event_handle_.Reset();
  7019. ReadAndInterpretStatusByte();
  7020. // Waits for the child process to exit if it haven't already. This
  7021. // returns immediately if the child has already exited, regardless of
  7022. // whether previous calls to WaitForMultipleObjects synchronized on this
  7023. // handle or not.
  7024. GTEST_DEATH_TEST_CHECK_(
  7025. WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
  7026. INFINITE));
  7027. DWORD status_code;
  7028. GTEST_DEATH_TEST_CHECK_(
  7029. ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
  7030. child_handle_.Reset();
  7031. set_status(static_cast<int>(status_code));
  7032. return status();
  7033. }
  7034. // The AssumeRole process for a Windows death test. It creates a child
  7035. // process with the same executable as the current process to run the
  7036. // death test. The child process is given the --gtest_filter and
  7037. // --gtest_internal_run_death_test flags such that it knows to run the
  7038. // current death test only.
  7039. DeathTest::TestRole WindowsDeathTest::AssumeRole() {
  7040. const UnitTestImpl* const impl = GetUnitTestImpl();
  7041. const InternalRunDeathTestFlag* const flag =
  7042. impl->internal_run_death_test_flag();
  7043. const TestInfo* const info = impl->current_test_info();
  7044. const int death_test_index = info->result()->death_test_count();
  7045. if (flag != NULL) {
  7046. // ParseInternalRunDeathTestFlag() has performed all the necessary
  7047. // processing.
  7048. set_write_fd(flag->write_fd());
  7049. return EXECUTE_TEST;
  7050. }
  7051. // WindowsDeathTest uses an anonymous pipe to communicate results of
  7052. // a death test.
  7053. SECURITY_ATTRIBUTES handles_are_inheritable = {
  7054. sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
  7055. HANDLE read_handle, write_handle;
  7056. GTEST_DEATH_TEST_CHECK_(
  7057. ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
  7058. 0) // Default buffer size.
  7059. != FALSE);
  7060. set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
  7061. O_RDONLY));
  7062. write_handle_.Reset(write_handle);
  7063. event_handle_.Reset(::CreateEvent(
  7064. &handles_are_inheritable,
  7065. TRUE, // The event will automatically reset to non-signaled state.
  7066. FALSE, // The initial state is non-signalled.
  7067. NULL)); // The even is unnamed.
  7068. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
  7069. const std::string filter_flag =
  7070. std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
  7071. info->test_case_name() + "." + info->name();
  7072. const std::string internal_flag =
  7073. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
  7074. "=" + file_ + "|" + StreamableToString(line_) + "|" +
  7075. StreamableToString(death_test_index) + "|" +
  7076. StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
  7077. // size_t has the same width as pointers on both 32-bit and 64-bit
  7078. // Windows platforms.
  7079. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
  7080. "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
  7081. "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
  7082. char executable_path[_MAX_PATH + 1]; // NOLINT
  7083. GTEST_DEATH_TEST_CHECK_(
  7084. _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
  7085. executable_path,
  7086. _MAX_PATH));
  7087. std::string command_line =
  7088. std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
  7089. internal_flag + "\"";
  7090. DeathTest::set_last_death_test_message("");
  7091. CaptureStderr();
  7092. // Flush the log buffers since the log streams are shared with the child.
  7093. FlushInfoLog();
  7094. // The child process will share the standard handles with the parent.
  7095. STARTUPINFOA startup_info;
  7096. memset(&startup_info, 0, sizeof(STARTUPINFO));
  7097. startup_info.dwFlags = STARTF_USESTDHANDLES;
  7098. startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
  7099. startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
  7100. startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
  7101. PROCESS_INFORMATION process_info;
  7102. GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
  7103. executable_path,
  7104. const_cast<char*>(command_line.c_str()),
  7105. NULL, // Retuned process handle is not inheritable.
  7106. NULL, // Retuned thread handle is not inheritable.
  7107. TRUE, // Child inherits all inheritable handles (for write_handle_).
  7108. 0x0, // Default creation flags.
  7109. NULL, // Inherit the parent's environment.
  7110. UnitTest::GetInstance()->original_working_dir(),
  7111. &startup_info,
  7112. &process_info) != FALSE);
  7113. child_handle_.Reset(process_info.hProcess);
  7114. ::CloseHandle(process_info.hThread);
  7115. set_spawned(true);
  7116. return OVERSEE_TEST;
  7117. }
  7118. # elif GTEST_OS_FUCHSIA
  7119. class FuchsiaDeathTest : public DeathTestImpl {
  7120. public:
  7121. FuchsiaDeathTest(const char* a_statement,
  7122. const RE* a_regex,
  7123. const char* file,
  7124. int line)
  7125. : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
  7126. virtual ~FuchsiaDeathTest() {
  7127. zx_status_t status = zx_handle_close(child_process_);
  7128. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7129. status = zx_handle_close(port_);
  7130. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7131. }
  7132. // All of these virtual functions are inherited from DeathTest.
  7133. virtual int Wait();
  7134. virtual TestRole AssumeRole();
  7135. private:
  7136. // The name of the file in which the death test is located.
  7137. const char* const file_;
  7138. // The line number on which the death test is located.
  7139. const int line_;
  7140. zx_handle_t child_process_ = ZX_HANDLE_INVALID;
  7141. zx_handle_t port_ = ZX_HANDLE_INVALID;
  7142. };
  7143. // Utility class for accumulating command-line arguments.
  7144. class Arguments {
  7145. public:
  7146. Arguments() {
  7147. args_.push_back(NULL);
  7148. }
  7149. ~Arguments() {
  7150. for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
  7151. ++i) {
  7152. free(*i);
  7153. }
  7154. }
  7155. void AddArgument(const char* argument) {
  7156. args_.insert(args_.end() - 1, posix::StrDup(argument));
  7157. }
  7158. template <typename Str>
  7159. void AddArguments(const ::std::vector<Str>& arguments) {
  7160. for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
  7161. i != arguments.end();
  7162. ++i) {
  7163. args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
  7164. }
  7165. }
  7166. char* const* Argv() {
  7167. return &args_[0];
  7168. }
  7169. int size() {
  7170. return args_.size() - 1;
  7171. }
  7172. private:
  7173. std::vector<char*> args_;
  7174. };
  7175. // Waits for the child in a death test to exit, returning its exit
  7176. // status, or 0 if no child process exists. As a side effect, sets the
  7177. // outcome data member.
  7178. int FuchsiaDeathTest::Wait() {
  7179. if (!spawned())
  7180. return 0;
  7181. // Register to wait for the child process to terminate.
  7182. zx_status_t status_zx;
  7183. status_zx = zx_object_wait_async(child_process_,
  7184. port_,
  7185. 0 /* key */,
  7186. ZX_PROCESS_TERMINATED,
  7187. ZX_WAIT_ASYNC_ONCE);
  7188. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7189. // Wait for it to terminate, or an exception to be received.
  7190. zx_port_packet_t packet;
  7191. status_zx = zx_port_wait(port_, ZX_TIME_INFINITE, &packet);
  7192. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7193. if (ZX_PKT_IS_EXCEPTION(packet.type)) {
  7194. // Process encountered an exception. Kill it directly rather than letting
  7195. // other handlers process the event.
  7196. status_zx = zx_task_kill(child_process_);
  7197. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7198. // Now wait for |child_process_| to terminate.
  7199. zx_signals_t signals = 0;
  7200. status_zx = zx_object_wait_one(
  7201. child_process_, ZX_PROCESS_TERMINATED, ZX_TIME_INFINITE, &signals);
  7202. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7203. GTEST_DEATH_TEST_CHECK_(signals & ZX_PROCESS_TERMINATED);
  7204. } else {
  7205. // Process terminated.
  7206. GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
  7207. GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
  7208. }
  7209. ReadAndInterpretStatusByte();
  7210. zx_info_process_t buffer;
  7211. status_zx = zx_object_get_info(
  7212. child_process_,
  7213. ZX_INFO_PROCESS,
  7214. &buffer,
  7215. sizeof(buffer),
  7216. nullptr,
  7217. nullptr);
  7218. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7219. GTEST_DEATH_TEST_CHECK_(buffer.exited);
  7220. set_status(buffer.return_code);
  7221. return status();
  7222. }
  7223. // The AssumeRole process for a Fuchsia death test. It creates a child
  7224. // process with the same executable as the current process to run the
  7225. // death test. The child process is given the --gtest_filter and
  7226. // --gtest_internal_run_death_test flags such that it knows to run the
  7227. // current death test only.
  7228. DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
  7229. const UnitTestImpl* const impl = GetUnitTestImpl();
  7230. const InternalRunDeathTestFlag* const flag =
  7231. impl->internal_run_death_test_flag();
  7232. const TestInfo* const info = impl->current_test_info();
  7233. const int death_test_index = info->result()->death_test_count();
  7234. if (flag != NULL) {
  7235. // ParseInternalRunDeathTestFlag() has performed all the necessary
  7236. // processing.
  7237. set_write_fd(kFuchsiaReadPipeFd);
  7238. return EXECUTE_TEST;
  7239. }
  7240. CaptureStderr();
  7241. // Flush the log buffers since the log streams are shared with the child.
  7242. FlushInfoLog();
  7243. // Build the child process command line.
  7244. const std::string filter_flag =
  7245. std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
  7246. + info->test_case_name() + "." + info->name();
  7247. const std::string internal_flag =
  7248. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
  7249. + file_ + "|"
  7250. + StreamableToString(line_) + "|"
  7251. + StreamableToString(death_test_index);
  7252. Arguments args;
  7253. args.AddArguments(GetInjectableArgvs());
  7254. args.AddArgument(filter_flag.c_str());
  7255. args.AddArgument(internal_flag.c_str());
  7256. // Build the pipe for communication with the child.
  7257. zx_status_t status;
  7258. zx_handle_t child_pipe_handle;
  7259. uint32_t type;
  7260. status = fdio_pipe_half(&child_pipe_handle, &type);
  7261. GTEST_DEATH_TEST_CHECK_(status >= 0);
  7262. set_read_fd(status);
  7263. // Set the pipe handle for the child.
  7264. fdio_spawn_action_t add_handle_action = {};
  7265. add_handle_action.action = FDIO_SPAWN_ACTION_ADD_HANDLE;
  7266. add_handle_action.h.id = PA_HND(type, kFuchsiaReadPipeFd);
  7267. add_handle_action.h.handle = child_pipe_handle;
  7268. // Spawn the child process.
  7269. status = fdio_spawn_etc(ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL,
  7270. args.Argv()[0], args.Argv(), nullptr, 1,
  7271. &add_handle_action, &child_process_, nullptr);
  7272. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7273. // Create an exception port and attach it to the |child_process_|, to allow
  7274. // us to suppress the system default exception handler from firing.
  7275. status = zx_port_create(0, &port_);
  7276. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7277. status = zx_task_bind_exception_port(
  7278. child_process_, port_, 0 /* key */, 0 /*options */);
  7279. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7280. set_spawned(true);
  7281. return OVERSEE_TEST;
  7282. }
  7283. #else // We are neither on Windows, nor on Fuchsia.
  7284. // ForkingDeathTest provides implementations for most of the abstract
  7285. // methods of the DeathTest interface. Only the AssumeRole method is
  7286. // left undefined.
  7287. class ForkingDeathTest : public DeathTestImpl {
  7288. public:
  7289. ForkingDeathTest(const char* statement, const RE* regex);
  7290. // All of these virtual functions are inherited from DeathTest.
  7291. virtual int Wait();
  7292. protected:
  7293. void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
  7294. private:
  7295. // PID of child process during death test; 0 in the child process itself.
  7296. pid_t child_pid_;
  7297. };
  7298. // Constructs a ForkingDeathTest.
  7299. ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
  7300. : DeathTestImpl(a_statement, a_regex),
  7301. child_pid_(-1) {}
  7302. // Waits for the child in a death test to exit, returning its exit
  7303. // status, or 0 if no child process exists. As a side effect, sets the
  7304. // outcome data member.
  7305. int ForkingDeathTest::Wait() {
  7306. if (!spawned())
  7307. return 0;
  7308. ReadAndInterpretStatusByte();
  7309. int status_value;
  7310. GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
  7311. set_status(status_value);
  7312. return status_value;
  7313. }
  7314. // A concrete death test class that forks, then immediately runs the test
  7315. // in the child process.
  7316. class NoExecDeathTest : public ForkingDeathTest {
  7317. public:
  7318. NoExecDeathTest(const char* a_statement, const RE* a_regex) :
  7319. ForkingDeathTest(a_statement, a_regex) { }
  7320. virtual TestRole AssumeRole();
  7321. };
  7322. // The AssumeRole process for a fork-and-run death test. It implements a
  7323. // straightforward fork, with a simple pipe to transmit the status byte.
  7324. DeathTest::TestRole NoExecDeathTest::AssumeRole() {
  7325. const size_t thread_count = GetThreadCount();
  7326. if (thread_count != 1) {
  7327. GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
  7328. }
  7329. int pipe_fd[2];
  7330. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  7331. DeathTest::set_last_death_test_message("");
  7332. CaptureStderr();
  7333. // When we fork the process below, the log file buffers are copied, but the
  7334. // file descriptors are shared. We flush all log files here so that closing
  7335. // the file descriptors in the child process doesn't throw off the
  7336. // synchronization between descriptors and buffers in the parent process.
  7337. // This is as close to the fork as possible to avoid a race condition in case
  7338. // there are multiple threads running before the death test, and another
  7339. // thread writes to the log file.
  7340. FlushInfoLog();
  7341. const pid_t child_pid = fork();
  7342. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  7343. set_child_pid(child_pid);
  7344. if (child_pid == 0) {
  7345. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
  7346. set_write_fd(pipe_fd[1]);
  7347. // Redirects all logging to stderr in the child process to prevent
  7348. // concurrent writes to the log files. We capture stderr in the parent
  7349. // process and append the child process' output to a log.
  7350. LogToStderr();
  7351. // Event forwarding to the listeners of event listener API mush be shut
  7352. // down in death test subprocesses.
  7353. GetUnitTestImpl()->listeners()->SuppressEventForwarding();
  7354. g_in_fast_death_test_child = true;
  7355. return EXECUTE_TEST;
  7356. } else {
  7357. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  7358. set_read_fd(pipe_fd[0]);
  7359. set_spawned(true);
  7360. return OVERSEE_TEST;
  7361. }
  7362. }
  7363. // A concrete death test class that forks and re-executes the main
  7364. // program from the beginning, with command-line flags set that cause
  7365. // only this specific death test to be run.
  7366. class ExecDeathTest : public ForkingDeathTest {
  7367. public:
  7368. ExecDeathTest(const char* a_statement, const RE* a_regex,
  7369. const char* file, int line) :
  7370. ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
  7371. virtual TestRole AssumeRole();
  7372. private:
  7373. static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
  7374. ::std::vector<std::string> args = GetInjectableArgvs();
  7375. # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
  7376. ::std::vector<std::string> extra_args =
  7377. GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
  7378. args.insert(args.end(), extra_args.begin(), extra_args.end());
  7379. # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
  7380. return args;
  7381. }
  7382. // The name of the file in which the death test is located.
  7383. const char* const file_;
  7384. // The line number on which the death test is located.
  7385. const int line_;
  7386. };
  7387. // Utility class for accumulating command-line arguments.
  7388. class Arguments {
  7389. public:
  7390. Arguments() {
  7391. args_.push_back(NULL);
  7392. }
  7393. ~Arguments() {
  7394. for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
  7395. ++i) {
  7396. free(*i);
  7397. }
  7398. }
  7399. void AddArgument(const char* argument) {
  7400. args_.insert(args_.end() - 1, posix::StrDup(argument));
  7401. }
  7402. template <typename Str>
  7403. void AddArguments(const ::std::vector<Str>& arguments) {
  7404. for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
  7405. i != arguments.end();
  7406. ++i) {
  7407. args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
  7408. }
  7409. }
  7410. char* const* Argv() {
  7411. return &args_[0];
  7412. }
  7413. private:
  7414. std::vector<char*> args_;
  7415. };
  7416. // A struct that encompasses the arguments to the child process of a
  7417. // threadsafe-style death test process.
  7418. struct ExecDeathTestArgs {
  7419. char* const* argv; // Command-line arguments for the child's call to exec
  7420. int close_fd; // File descriptor to close; the read end of a pipe
  7421. };
  7422. # if GTEST_OS_MAC
  7423. inline char** GetEnviron() {
  7424. // When Google Test is built as a framework on MacOS X, the environ variable
  7425. // is unavailable. Apple's documentation (man environ) recommends using
  7426. // _NSGetEnviron() instead.
  7427. return *_NSGetEnviron();
  7428. }
  7429. # else
  7430. // Some POSIX platforms expect you to declare environ. extern "C" makes
  7431. // it reside in the global namespace.
  7432. extern "C" char** environ;
  7433. inline char** GetEnviron() { return environ; }
  7434. # endif // GTEST_OS_MAC
  7435. # if !GTEST_OS_QNX
  7436. // The main function for a threadsafe-style death test child process.
  7437. // This function is called in a clone()-ed process and thus must avoid
  7438. // any potentially unsafe operations like malloc or libc functions.
  7439. static int ExecDeathTestChildMain(void* child_arg) {
  7440. ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
  7441. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
  7442. // We need to execute the test program in the same environment where
  7443. // it was originally invoked. Therefore we change to the original
  7444. // working directory first.
  7445. const char* const original_dir =
  7446. UnitTest::GetInstance()->original_working_dir();
  7447. // We can safely call chdir() as it's a direct system call.
  7448. if (chdir(original_dir) != 0) {
  7449. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  7450. GetLastErrnoDescription());
  7451. return EXIT_FAILURE;
  7452. }
  7453. // We can safely call execve() as it's a direct system call. We
  7454. // cannot use execvp() as it's a libc function and thus potentially
  7455. // unsafe. Since execve() doesn't search the PATH, the user must
  7456. // invoke the test program via a valid path that contains at least
  7457. // one path separator.
  7458. execve(args->argv[0], args->argv, GetEnviron());
  7459. DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
  7460. original_dir + " failed: " +
  7461. GetLastErrnoDescription());
  7462. return EXIT_FAILURE;
  7463. }
  7464. # endif // !GTEST_OS_QNX
  7465. # if GTEST_HAS_CLONE
  7466. // Two utility routines that together determine the direction the stack
  7467. // grows.
  7468. // This could be accomplished more elegantly by a single recursive
  7469. // function, but we want to guard against the unlikely possibility of
  7470. // a smart compiler optimizing the recursion away.
  7471. //
  7472. // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
  7473. // StackLowerThanAddress into StackGrowsDown, which then doesn't give
  7474. // correct answer.
  7475. static void StackLowerThanAddress(const void* ptr,
  7476. bool* result) GTEST_NO_INLINE_;
  7477. static void StackLowerThanAddress(const void* ptr, bool* result) {
  7478. int dummy;
  7479. *result = (&dummy < ptr);
  7480. }
  7481. // Make sure AddressSanitizer does not tamper with the stack here.
  7482. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  7483. static bool StackGrowsDown() {
  7484. int dummy;
  7485. bool result;
  7486. StackLowerThanAddress(&dummy, &result);
  7487. return result;
  7488. }
  7489. # endif // GTEST_HAS_CLONE
  7490. // Spawns a child process with the same executable as the current process in
  7491. // a thread-safe manner and instructs it to run the death test. The
  7492. // implementation uses fork(2) + exec. On systems where clone(2) is
  7493. // available, it is used instead, being slightly more thread-safe. On QNX,
  7494. // fork supports only single-threaded environments, so this function uses
  7495. // spawn(2) there instead. The function dies with an error message if
  7496. // anything goes wrong.
  7497. static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
  7498. ExecDeathTestArgs args = { argv, close_fd };
  7499. pid_t child_pid = -1;
  7500. # if GTEST_OS_QNX
  7501. // Obtains the current directory and sets it to be closed in the child
  7502. // process.
  7503. const int cwd_fd = open(".", O_RDONLY);
  7504. GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
  7505. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
  7506. // We need to execute the test program in the same environment where
  7507. // it was originally invoked. Therefore we change to the original
  7508. // working directory first.
  7509. const char* const original_dir =
  7510. UnitTest::GetInstance()->original_working_dir();
  7511. // We can safely call chdir() as it's a direct system call.
  7512. if (chdir(original_dir) != 0) {
  7513. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  7514. GetLastErrnoDescription());
  7515. return EXIT_FAILURE;
  7516. }
  7517. int fd_flags;
  7518. // Set close_fd to be closed after spawn.
  7519. GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
  7520. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
  7521. fd_flags | FD_CLOEXEC));
  7522. struct inheritance inherit = {0};
  7523. // spawn is a system call.
  7524. child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
  7525. // Restores the current working directory.
  7526. GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
  7527. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
  7528. # else // GTEST_OS_QNX
  7529. # if GTEST_OS_LINUX
  7530. // When a SIGPROF signal is received while fork() or clone() are executing,
  7531. // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
  7532. // it after the call to fork()/clone() is complete.
  7533. struct sigaction saved_sigprof_action;
  7534. struct sigaction ignore_sigprof_action;
  7535. memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
  7536. sigemptyset(&ignore_sigprof_action.sa_mask);
  7537. ignore_sigprof_action.sa_handler = SIG_IGN;
  7538. GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
  7539. SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
  7540. # endif // GTEST_OS_LINUX
  7541. # if GTEST_HAS_CLONE
  7542. const bool use_fork = GTEST_FLAG(death_test_use_fork);
  7543. if (!use_fork) {
  7544. static const bool stack_grows_down = StackGrowsDown();
  7545. const size_t stack_size = getpagesize();
  7546. // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
  7547. void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
  7548. MAP_ANON | MAP_PRIVATE, -1, 0);
  7549. GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
  7550. // Maximum stack alignment in bytes: For a downward-growing stack, this
  7551. // amount is subtracted from size of the stack space to get an address
  7552. // that is within the stack space and is aligned on all systems we care
  7553. // about. As far as I know there is no ABI with stack alignment greater
  7554. // than 64. We assume stack and stack_size already have alignment of
  7555. // kMaxStackAlignment.
  7556. const size_t kMaxStackAlignment = 64;
  7557. void* const stack_top =
  7558. static_cast<char*>(stack) +
  7559. (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
  7560. GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
  7561. reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
  7562. child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
  7563. GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
  7564. }
  7565. # else
  7566. const bool use_fork = true;
  7567. # endif // GTEST_HAS_CLONE
  7568. if (use_fork && (child_pid = fork()) == 0) {
  7569. ExecDeathTestChildMain(&args);
  7570. _exit(0);
  7571. }
  7572. # endif // GTEST_OS_QNX
  7573. # if GTEST_OS_LINUX
  7574. GTEST_DEATH_TEST_CHECK_SYSCALL_(
  7575. sigaction(SIGPROF, &saved_sigprof_action, NULL));
  7576. # endif // GTEST_OS_LINUX
  7577. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  7578. return child_pid;
  7579. }
  7580. // The AssumeRole process for a fork-and-exec death test. It re-executes the
  7581. // main program from the beginning, setting the --gtest_filter
  7582. // and --gtest_internal_run_death_test flags to cause only the current
  7583. // death test to be re-run.
  7584. DeathTest::TestRole ExecDeathTest::AssumeRole() {
  7585. const UnitTestImpl* const impl = GetUnitTestImpl();
  7586. const InternalRunDeathTestFlag* const flag =
  7587. impl->internal_run_death_test_flag();
  7588. const TestInfo* const info = impl->current_test_info();
  7589. const int death_test_index = info->result()->death_test_count();
  7590. if (flag != NULL) {
  7591. set_write_fd(flag->write_fd());
  7592. return EXECUTE_TEST;
  7593. }
  7594. int pipe_fd[2];
  7595. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  7596. // Clear the close-on-exec flag on the write end of the pipe, lest
  7597. // it be closed when the child process does an exec:
  7598. GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
  7599. const std::string filter_flag =
  7600. std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
  7601. + info->test_case_name() + "." + info->name();
  7602. const std::string internal_flag =
  7603. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
  7604. + file_ + "|" + StreamableToString(line_) + "|"
  7605. + StreamableToString(death_test_index) + "|"
  7606. + StreamableToString(pipe_fd[1]);
  7607. Arguments args;
  7608. args.AddArguments(GetArgvsForDeathTestChildProcess());
  7609. args.AddArgument(filter_flag.c_str());
  7610. args.AddArgument(internal_flag.c_str());
  7611. DeathTest::set_last_death_test_message("");
  7612. CaptureStderr();
  7613. // See the comment in NoExecDeathTest::AssumeRole for why the next line
  7614. // is necessary.
  7615. FlushInfoLog();
  7616. const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
  7617. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  7618. set_child_pid(child_pid);
  7619. set_read_fd(pipe_fd[0]);
  7620. set_spawned(true);
  7621. return OVERSEE_TEST;
  7622. }
  7623. # endif // !GTEST_OS_WINDOWS
  7624. // Creates a concrete DeathTest-derived class that depends on the
  7625. // --gtest_death_test_style flag, and sets the pointer pointed to
  7626. // by the "test" argument to its address. If the test should be
  7627. // skipped, sets that pointer to NULL. Returns true, unless the
  7628. // flag is set to an invalid value.
  7629. bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
  7630. const char* file, int line,
  7631. DeathTest** test) {
  7632. UnitTestImpl* const impl = GetUnitTestImpl();
  7633. const InternalRunDeathTestFlag* const flag =
  7634. impl->internal_run_death_test_flag();
  7635. const int death_test_index = impl->current_test_info()
  7636. ->increment_death_test_count();
  7637. if (flag != NULL) {
  7638. if (death_test_index > flag->index()) {
  7639. DeathTest::set_last_death_test_message(
  7640. "Death test count (" + StreamableToString(death_test_index)
  7641. + ") somehow exceeded expected maximum ("
  7642. + StreamableToString(flag->index()) + ")");
  7643. return false;
  7644. }
  7645. if (!(flag->file() == file && flag->line() == line &&
  7646. flag->index() == death_test_index)) {
  7647. *test = NULL;
  7648. return true;
  7649. }
  7650. }
  7651. # if GTEST_OS_WINDOWS
  7652. if (GTEST_FLAG(death_test_style) == "threadsafe" ||
  7653. GTEST_FLAG(death_test_style) == "fast") {
  7654. *test = new WindowsDeathTest(statement, regex, file, line);
  7655. }
  7656. # elif GTEST_OS_FUCHSIA
  7657. if (GTEST_FLAG(death_test_style) == "threadsafe" ||
  7658. GTEST_FLAG(death_test_style) == "fast") {
  7659. *test = new FuchsiaDeathTest(statement, regex, file, line);
  7660. }
  7661. # else
  7662. if (GTEST_FLAG(death_test_style) == "threadsafe") {
  7663. *test = new ExecDeathTest(statement, regex, file, line);
  7664. } else if (GTEST_FLAG(death_test_style) == "fast") {
  7665. *test = new NoExecDeathTest(statement, regex);
  7666. }
  7667. # endif // GTEST_OS_WINDOWS
  7668. else { // NOLINT - this is more readable than unbalanced brackets inside #if.
  7669. DeathTest::set_last_death_test_message(
  7670. "Unknown death test style \"" + GTEST_FLAG(death_test_style)
  7671. + "\" encountered");
  7672. return false;
  7673. }
  7674. return true;
  7675. }
  7676. # if GTEST_OS_WINDOWS
  7677. // Recreates the pipe and event handles from the provided parameters,
  7678. // signals the event, and returns a file descriptor wrapped around the pipe
  7679. // handle. This function is called in the child process only.
  7680. static int GetStatusFileDescriptor(unsigned int parent_process_id,
  7681. size_t write_handle_as_size_t,
  7682. size_t event_handle_as_size_t) {
  7683. AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
  7684. FALSE, // Non-inheritable.
  7685. parent_process_id));
  7686. if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
  7687. DeathTestAbort("Unable to open parent process " +
  7688. StreamableToString(parent_process_id));
  7689. }
  7690. // FIXME: Replace the following check with a
  7691. // compile-time assertion when available.
  7692. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
  7693. const HANDLE write_handle =
  7694. reinterpret_cast<HANDLE>(write_handle_as_size_t);
  7695. HANDLE dup_write_handle;
  7696. // The newly initialized handle is accessible only in the parent
  7697. // process. To obtain one accessible within the child, we need to use
  7698. // DuplicateHandle.
  7699. if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
  7700. ::GetCurrentProcess(), &dup_write_handle,
  7701. 0x0, // Requested privileges ignored since
  7702. // DUPLICATE_SAME_ACCESS is used.
  7703. FALSE, // Request non-inheritable handler.
  7704. DUPLICATE_SAME_ACCESS)) {
  7705. DeathTestAbort("Unable to duplicate the pipe handle " +
  7706. StreamableToString(write_handle_as_size_t) +
  7707. " from the parent process " +
  7708. StreamableToString(parent_process_id));
  7709. }
  7710. const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
  7711. HANDLE dup_event_handle;
  7712. if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
  7713. ::GetCurrentProcess(), &dup_event_handle,
  7714. 0x0,
  7715. FALSE,
  7716. DUPLICATE_SAME_ACCESS)) {
  7717. DeathTestAbort("Unable to duplicate the event handle " +
  7718. StreamableToString(event_handle_as_size_t) +
  7719. " from the parent process " +
  7720. StreamableToString(parent_process_id));
  7721. }
  7722. const int write_fd =
  7723. ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
  7724. if (write_fd == -1) {
  7725. DeathTestAbort("Unable to convert pipe handle " +
  7726. StreamableToString(write_handle_as_size_t) +
  7727. " to a file descriptor");
  7728. }
  7729. // Signals the parent that the write end of the pipe has been acquired
  7730. // so the parent can release its own write end.
  7731. ::SetEvent(dup_event_handle);
  7732. return write_fd;
  7733. }
  7734. # endif // GTEST_OS_WINDOWS
  7735. // Returns a newly created InternalRunDeathTestFlag object with fields
  7736. // initialized from the GTEST_FLAG(internal_run_death_test) flag if
  7737. // the flag is specified; otherwise returns NULL.
  7738. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
  7739. if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
  7740. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
  7741. // can use it here.
  7742. int line = -1;
  7743. int index = -1;
  7744. ::std::vector< ::std::string> fields;
  7745. SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
  7746. int write_fd = -1;
  7747. # if GTEST_OS_WINDOWS
  7748. unsigned int parent_process_id = 0;
  7749. size_t write_handle_as_size_t = 0;
  7750. size_t event_handle_as_size_t = 0;
  7751. if (fields.size() != 6
  7752. || !ParseNaturalNumber(fields[1], &line)
  7753. || !ParseNaturalNumber(fields[2], &index)
  7754. || !ParseNaturalNumber(fields[3], &parent_process_id)
  7755. || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
  7756. || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
  7757. DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
  7758. GTEST_FLAG(internal_run_death_test));
  7759. }
  7760. write_fd = GetStatusFileDescriptor(parent_process_id,
  7761. write_handle_as_size_t,
  7762. event_handle_as_size_t);
  7763. # elif GTEST_OS_FUCHSIA
  7764. if (fields.size() != 3
  7765. || !ParseNaturalNumber(fields[1], &line)
  7766. || !ParseNaturalNumber(fields[2], &index)) {
  7767. DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
  7768. + GTEST_FLAG(internal_run_death_test));
  7769. }
  7770. # else
  7771. if (fields.size() != 4
  7772. || !ParseNaturalNumber(fields[1], &line)
  7773. || !ParseNaturalNumber(fields[2], &index)
  7774. || !ParseNaturalNumber(fields[3], &write_fd)) {
  7775. DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
  7776. + GTEST_FLAG(internal_run_death_test));
  7777. }
  7778. # endif // GTEST_OS_WINDOWS
  7779. return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
  7780. }
  7781. } // namespace internal
  7782. #endif // GTEST_HAS_DEATH_TEST
  7783. } // namespace testing
  7784. // Copyright 2008, Google Inc.
  7785. // All rights reserved.
  7786. //
  7787. // Redistribution and use in source and binary forms, with or without
  7788. // modification, are permitted provided that the following conditions are
  7789. // met:
  7790. //
  7791. // * Redistributions of source code must retain the above copyright
  7792. // notice, this list of conditions and the following disclaimer.
  7793. // * Redistributions in binary form must reproduce the above
  7794. // copyright notice, this list of conditions and the following disclaimer
  7795. // in the documentation and/or other materials provided with the
  7796. // distribution.
  7797. // * Neither the name of Google Inc. nor the names of its
  7798. // contributors may be used to endorse or promote products derived from
  7799. // this software without specific prior written permission.
  7800. //
  7801. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7802. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7803. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7804. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7805. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7806. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7807. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7808. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7809. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7810. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7811. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7812. #include <stdlib.h>
  7813. #if GTEST_OS_WINDOWS_MOBILE
  7814. # include <windows.h>
  7815. #elif GTEST_OS_WINDOWS
  7816. # include <direct.h>
  7817. # include <io.h>
  7818. #elif GTEST_OS_SYMBIAN
  7819. // Symbian OpenC has PATH_MAX in sys/syslimits.h
  7820. # include <sys/syslimits.h>
  7821. #else
  7822. # include <limits.h>
  7823. # include <climits> // Some Linux distributions define PATH_MAX here.
  7824. #endif // GTEST_OS_WINDOWS_MOBILE
  7825. #if GTEST_OS_WINDOWS
  7826. # define GTEST_PATH_MAX_ _MAX_PATH
  7827. #elif defined(PATH_MAX)
  7828. # define GTEST_PATH_MAX_ PATH_MAX
  7829. #elif defined(_XOPEN_PATH_MAX)
  7830. # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
  7831. #else
  7832. # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
  7833. #endif // GTEST_OS_WINDOWS
  7834. namespace testing {
  7835. namespace internal {
  7836. #if GTEST_OS_WINDOWS
  7837. // On Windows, '\\' is the standard path separator, but many tools and the
  7838. // Windows API also accept '/' as an alternate path separator. Unless otherwise
  7839. // noted, a file path can contain either kind of path separators, or a mixture
  7840. // of them.
  7841. const char kPathSeparator = '\\';
  7842. const char kAlternatePathSeparator = '/';
  7843. const char kAlternatePathSeparatorString[] = "/";
  7844. # if GTEST_OS_WINDOWS_MOBILE
  7845. // Windows CE doesn't have a current directory. You should not use
  7846. // the current directory in tests on Windows CE, but this at least
  7847. // provides a reasonable fallback.
  7848. const char kCurrentDirectoryString[] = "\\";
  7849. // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
  7850. const DWORD kInvalidFileAttributes = 0xffffffff;
  7851. # else
  7852. const char kCurrentDirectoryString[] = ".\\";
  7853. # endif // GTEST_OS_WINDOWS_MOBILE
  7854. #else
  7855. const char kPathSeparator = '/';
  7856. const char kCurrentDirectoryString[] = "./";
  7857. #endif // GTEST_OS_WINDOWS
  7858. // Returns whether the given character is a valid path separator.
  7859. static bool IsPathSeparator(char c) {
  7860. #if GTEST_HAS_ALT_PATH_SEP_
  7861. return (c == kPathSeparator) || (c == kAlternatePathSeparator);
  7862. #else
  7863. return c == kPathSeparator;
  7864. #endif
  7865. }
  7866. // Returns the current working directory, or "" if unsuccessful.
  7867. FilePath FilePath::GetCurrentDir() {
  7868. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
  7869. // Windows CE doesn't have a current directory, so we just return
  7870. // something reasonable.
  7871. return FilePath(kCurrentDirectoryString);
  7872. #elif GTEST_OS_WINDOWS
  7873. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  7874. return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
  7875. #else
  7876. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  7877. char* result = getcwd(cwd, sizeof(cwd));
  7878. # if GTEST_OS_NACL
  7879. // getcwd will likely fail in NaCl due to the sandbox, so return something
  7880. // reasonable. The user may have provided a shim implementation for getcwd,
  7881. // however, so fallback only when failure is detected.
  7882. return FilePath(result == NULL ? kCurrentDirectoryString : cwd);
  7883. # endif // GTEST_OS_NACL
  7884. return FilePath(result == NULL ? "" : cwd);
  7885. #endif // GTEST_OS_WINDOWS_MOBILE
  7886. }
  7887. // Returns a copy of the FilePath with the case-insensitive extension removed.
  7888. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
  7889. // FilePath("dir/file"). If a case-insensitive extension is not
  7890. // found, returns a copy of the original FilePath.
  7891. FilePath FilePath::RemoveExtension(const char* extension) const {
  7892. const std::string dot_extension = std::string(".") + extension;
  7893. if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
  7894. return FilePath(pathname_.substr(
  7895. 0, pathname_.length() - dot_extension.length()));
  7896. }
  7897. return *this;
  7898. }
  7899. // Returns a pointer to the last occurrence of a valid path separator in
  7900. // the FilePath. On Windows, for example, both '/' and '\' are valid path
  7901. // separators. Returns NULL if no path separator was found.
  7902. const char* FilePath::FindLastPathSeparator() const {
  7903. const char* const last_sep = strrchr(c_str(), kPathSeparator);
  7904. #if GTEST_HAS_ALT_PATH_SEP_
  7905. const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
  7906. // Comparing two pointers of which only one is NULL is undefined.
  7907. if (last_alt_sep != NULL &&
  7908. (last_sep == NULL || last_alt_sep > last_sep)) {
  7909. return last_alt_sep;
  7910. }
  7911. #endif
  7912. return last_sep;
  7913. }
  7914. // Returns a copy of the FilePath with the directory part removed.
  7915. // Example: FilePath("path/to/file").RemoveDirectoryName() returns
  7916. // FilePath("file"). If there is no directory part ("just_a_file"), it returns
  7917. // the FilePath unmodified. If there is no file part ("just_a_dir/") it
  7918. // returns an empty FilePath ("").
  7919. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  7920. FilePath FilePath::RemoveDirectoryName() const {
  7921. const char* const last_sep = FindLastPathSeparator();
  7922. return last_sep ? FilePath(last_sep + 1) : *this;
  7923. }
  7924. // RemoveFileName returns the directory path with the filename removed.
  7925. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
  7926. // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
  7927. // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
  7928. // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
  7929. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  7930. FilePath FilePath::RemoveFileName() const {
  7931. const char* const last_sep = FindLastPathSeparator();
  7932. std::string dir;
  7933. if (last_sep) {
  7934. dir = std::string(c_str(), last_sep + 1 - c_str());
  7935. } else {
  7936. dir = kCurrentDirectoryString;
  7937. }
  7938. return FilePath(dir);
  7939. }
  7940. // Helper functions for naming files in a directory for xml output.
  7941. // Given directory = "dir", base_name = "test", number = 0,
  7942. // extension = "xml", returns "dir/test.xml". If number is greater
  7943. // than zero (e.g., 12), returns "dir/test_12.xml".
  7944. // On Windows platform, uses \ as the separator rather than /.
  7945. FilePath FilePath::MakeFileName(const FilePath& directory,
  7946. const FilePath& base_name,
  7947. int number,
  7948. const char* extension) {
  7949. std::string file;
  7950. if (number == 0) {
  7951. file = base_name.string() + "." + extension;
  7952. } else {
  7953. file = base_name.string() + "_" + StreamableToString(number)
  7954. + "." + extension;
  7955. }
  7956. return ConcatPaths(directory, FilePath(file));
  7957. }
  7958. // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
  7959. // On Windows, uses \ as the separator rather than /.
  7960. FilePath FilePath::ConcatPaths(const FilePath& directory,
  7961. const FilePath& relative_path) {
  7962. if (directory.IsEmpty())
  7963. return relative_path;
  7964. const FilePath dir(directory.RemoveTrailingPathSeparator());
  7965. return FilePath(dir.string() + kPathSeparator + relative_path.string());
  7966. }
  7967. // Returns true if pathname describes something findable in the file-system,
  7968. // either a file, directory, or whatever.
  7969. bool FilePath::FileOrDirectoryExists() const {
  7970. #if GTEST_OS_WINDOWS_MOBILE
  7971. LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
  7972. const DWORD attributes = GetFileAttributes(unicode);
  7973. delete [] unicode;
  7974. return attributes != kInvalidFileAttributes;
  7975. #else
  7976. posix::StatStruct file_stat;
  7977. return posix::Stat(pathname_.c_str(), &file_stat) == 0;
  7978. #endif // GTEST_OS_WINDOWS_MOBILE
  7979. }
  7980. // Returns true if pathname describes a directory in the file-system
  7981. // that exists.
  7982. bool FilePath::DirectoryExists() const {
  7983. bool result = false;
  7984. #if GTEST_OS_WINDOWS
  7985. // Don't strip off trailing separator if path is a root directory on
  7986. // Windows (like "C:\\").
  7987. const FilePath& path(IsRootDirectory() ? *this :
  7988. RemoveTrailingPathSeparator());
  7989. #else
  7990. const FilePath& path(*this);
  7991. #endif
  7992. #if GTEST_OS_WINDOWS_MOBILE
  7993. LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
  7994. const DWORD attributes = GetFileAttributes(unicode);
  7995. delete [] unicode;
  7996. if ((attributes != kInvalidFileAttributes) &&
  7997. (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  7998. result = true;
  7999. }
  8000. #else
  8001. posix::StatStruct file_stat;
  8002. result = posix::Stat(path.c_str(), &file_stat) == 0 &&
  8003. posix::IsDir(file_stat);
  8004. #endif // GTEST_OS_WINDOWS_MOBILE
  8005. return result;
  8006. }
  8007. // Returns true if pathname describes a root directory. (Windows has one
  8008. // root directory per disk drive.)
  8009. bool FilePath::IsRootDirectory() const {
  8010. #if GTEST_OS_WINDOWS
  8011. // FIXME: on Windows a network share like
  8012. // \\server\share can be a root directory, although it cannot be the
  8013. // current directory. Handle this properly.
  8014. return pathname_.length() == 3 && IsAbsolutePath();
  8015. #else
  8016. return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
  8017. #endif
  8018. }
  8019. // Returns true if pathname describes an absolute path.
  8020. bool FilePath::IsAbsolutePath() const {
  8021. const char* const name = pathname_.c_str();
  8022. #if GTEST_OS_WINDOWS
  8023. return pathname_.length() >= 3 &&
  8024. ((name[0] >= 'a' && name[0] <= 'z') ||
  8025. (name[0] >= 'A' && name[0] <= 'Z')) &&
  8026. name[1] == ':' &&
  8027. IsPathSeparator(name[2]);
  8028. #else
  8029. return IsPathSeparator(name[0]);
  8030. #endif
  8031. }
  8032. // Returns a pathname for a file that does not currently exist. The pathname
  8033. // will be directory/base_name.extension or
  8034. // directory/base_name_<number>.extension if directory/base_name.extension
  8035. // already exists. The number will be incremented until a pathname is found
  8036. // that does not already exist.
  8037. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
  8038. // There could be a race condition if two or more processes are calling this
  8039. // function at the same time -- they could both pick the same filename.
  8040. FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
  8041. const FilePath& base_name,
  8042. const char* extension) {
  8043. FilePath full_pathname;
  8044. int number = 0;
  8045. do {
  8046. full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
  8047. } while (full_pathname.FileOrDirectoryExists());
  8048. return full_pathname;
  8049. }
  8050. // Returns true if FilePath ends with a path separator, which indicates that
  8051. // it is intended to represent a directory. Returns false otherwise.
  8052. // This does NOT check that a directory (or file) actually exists.
  8053. bool FilePath::IsDirectory() const {
  8054. return !pathname_.empty() &&
  8055. IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
  8056. }
  8057. // Create directories so that path exists. Returns true if successful or if
  8058. // the directories already exist; returns false if unable to create directories
  8059. // for any reason.
  8060. bool FilePath::CreateDirectoriesRecursively() const {
  8061. if (!this->IsDirectory()) {
  8062. return false;
  8063. }
  8064. if (pathname_.length() == 0 || this->DirectoryExists()) {
  8065. return true;
  8066. }
  8067. const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
  8068. return parent.CreateDirectoriesRecursively() && this->CreateFolder();
  8069. }
  8070. // Create the directory so that path exists. Returns true if successful or
  8071. // if the directory already exists; returns false if unable to create the
  8072. // directory for any reason, including if the parent directory does not
  8073. // exist. Not named "CreateDirectory" because that's a macro on Windows.
  8074. bool FilePath::CreateFolder() const {
  8075. #if GTEST_OS_WINDOWS_MOBILE
  8076. FilePath removed_sep(this->RemoveTrailingPathSeparator());
  8077. LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
  8078. int result = CreateDirectory(unicode, NULL) ? 0 : -1;
  8079. delete [] unicode;
  8080. #elif GTEST_OS_WINDOWS
  8081. int result = _mkdir(pathname_.c_str());
  8082. #else
  8083. int result = mkdir(pathname_.c_str(), 0777);
  8084. #endif // GTEST_OS_WINDOWS_MOBILE
  8085. if (result == -1) {
  8086. return this->DirectoryExists(); // An error is OK if the directory exists.
  8087. }
  8088. return true; // No error.
  8089. }
  8090. // If input name has a trailing separator character, remove it and return the
  8091. // name, otherwise return the name string unmodified.
  8092. // On Windows platform, uses \ as the separator, other platforms use /.
  8093. FilePath FilePath::RemoveTrailingPathSeparator() const {
  8094. return IsDirectory()
  8095. ? FilePath(pathname_.substr(0, pathname_.length() - 1))
  8096. : *this;
  8097. }
  8098. // Removes any redundant separators that might be in the pathname.
  8099. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
  8100. // redundancies that might be in a pathname involving "." or "..".
  8101. // FIXME: handle Windows network shares (e.g. \\server\share).
  8102. void FilePath::Normalize() {
  8103. if (pathname_.c_str() == NULL) {
  8104. pathname_ = "";
  8105. return;
  8106. }
  8107. const char* src = pathname_.c_str();
  8108. char* const dest = new char[pathname_.length() + 1];
  8109. char* dest_ptr = dest;
  8110. memset(dest_ptr, 0, pathname_.length() + 1);
  8111. while (*src != '\0') {
  8112. *dest_ptr = *src;
  8113. if (!IsPathSeparator(*src)) {
  8114. src++;
  8115. } else {
  8116. #if GTEST_HAS_ALT_PATH_SEP_
  8117. if (*dest_ptr == kAlternatePathSeparator) {
  8118. *dest_ptr = kPathSeparator;
  8119. }
  8120. #endif
  8121. while (IsPathSeparator(*src))
  8122. src++;
  8123. }
  8124. dest_ptr++;
  8125. }
  8126. *dest_ptr = '\0';
  8127. pathname_ = dest;
  8128. delete[] dest;
  8129. }
  8130. } // namespace internal
  8131. } // namespace testing
  8132. // Copyright 2008, Google Inc.
  8133. // All rights reserved.
  8134. //
  8135. // Redistribution and use in source and binary forms, with or without
  8136. // modification, are permitted provided that the following conditions are
  8137. // met:
  8138. //
  8139. // * Redistributions of source code must retain the above copyright
  8140. // notice, this list of conditions and the following disclaimer.
  8141. // * Redistributions in binary form must reproduce the above
  8142. // copyright notice, this list of conditions and the following disclaimer
  8143. // in the documentation and/or other materials provided with the
  8144. // distribution.
  8145. // * Neither the name of Google Inc. nor the names of its
  8146. // contributors may be used to endorse or promote products derived from
  8147. // this software without specific prior written permission.
  8148. //
  8149. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8150. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8151. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8152. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8153. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8154. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8155. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8156. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8157. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8158. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8159. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8160. #include <limits.h>
  8161. #include <stdlib.h>
  8162. #include <stdio.h>
  8163. #include <string.h>
  8164. #include <fstream>
  8165. #if GTEST_OS_WINDOWS
  8166. # include <windows.h>
  8167. # include <io.h>
  8168. # include <sys/stat.h>
  8169. # include <map> // Used in ThreadLocal.
  8170. #else
  8171. # include <unistd.h>
  8172. #endif // GTEST_OS_WINDOWS
  8173. #if GTEST_OS_MAC
  8174. # include <mach/mach_init.h>
  8175. # include <mach/task.h>
  8176. # include <mach/vm_map.h>
  8177. #endif // GTEST_OS_MAC
  8178. #if GTEST_OS_QNX
  8179. # include <devctl.h>
  8180. # include <fcntl.h>
  8181. # include <sys/procfs.h>
  8182. #endif // GTEST_OS_QNX
  8183. #if GTEST_OS_AIX
  8184. # include <procinfo.h>
  8185. # include <sys/types.h>
  8186. #endif // GTEST_OS_AIX
  8187. #if GTEST_OS_FUCHSIA
  8188. # include <zircon/process.h>
  8189. # include <zircon/syscalls.h>
  8190. #endif // GTEST_OS_FUCHSIA
  8191. namespace testing {
  8192. namespace internal {
  8193. #if defined(_MSC_VER) || defined(__BORLANDC__)
  8194. // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
  8195. const int kStdOutFileno = 1;
  8196. const int kStdErrFileno = 2;
  8197. #else
  8198. const int kStdOutFileno = STDOUT_FILENO;
  8199. const int kStdErrFileno = STDERR_FILENO;
  8200. #endif // _MSC_VER
  8201. #if GTEST_OS_LINUX
  8202. namespace {
  8203. template <typename T>
  8204. T ReadProcFileField(const std::string& filename, int field) {
  8205. std::string dummy;
  8206. std::ifstream file(filename.c_str());
  8207. while (field-- > 0) {
  8208. file >> dummy;
  8209. }
  8210. T output = 0;
  8211. file >> output;
  8212. return output;
  8213. }
  8214. } // namespace
  8215. // Returns the number of active threads, or 0 when there is an error.
  8216. size_t GetThreadCount() {
  8217. const std::string filename =
  8218. (Message() << "/proc/" << getpid() << "/stat").GetString();
  8219. return ReadProcFileField<int>(filename, 19);
  8220. }
  8221. #elif GTEST_OS_MAC
  8222. size_t GetThreadCount() {
  8223. const task_t task = mach_task_self();
  8224. mach_msg_type_number_t thread_count;
  8225. thread_act_array_t thread_list;
  8226. const kern_return_t status = task_threads(task, &thread_list, &thread_count);
  8227. if (status == KERN_SUCCESS) {
  8228. // task_threads allocates resources in thread_list and we need to free them
  8229. // to avoid leaks.
  8230. vm_deallocate(task,
  8231. reinterpret_cast<vm_address_t>(thread_list),
  8232. sizeof(thread_t) * thread_count);
  8233. return static_cast<size_t>(thread_count);
  8234. } else {
  8235. return 0;
  8236. }
  8237. }
  8238. #elif GTEST_OS_QNX
  8239. // Returns the number of threads running in the process, or 0 to indicate that
  8240. // we cannot detect it.
  8241. size_t GetThreadCount() {
  8242. const int fd = open("/proc/self/as", O_RDONLY);
  8243. if (fd < 0) {
  8244. return 0;
  8245. }
  8246. procfs_info process_info;
  8247. const int status =
  8248. devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
  8249. close(fd);
  8250. if (status == EOK) {
  8251. return static_cast<size_t>(process_info.num_threads);
  8252. } else {
  8253. return 0;
  8254. }
  8255. }
  8256. #elif GTEST_OS_AIX
  8257. size_t GetThreadCount() {
  8258. struct procentry64 entry;
  8259. pid_t pid = getpid();
  8260. int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1);
  8261. if (status == 1) {
  8262. return entry.pi_thcount;
  8263. } else {
  8264. return 0;
  8265. }
  8266. }
  8267. #elif GTEST_OS_FUCHSIA
  8268. size_t GetThreadCount() {
  8269. int dummy_buffer;
  8270. size_t avail;
  8271. zx_status_t status = zx_object_get_info(
  8272. zx_process_self(),
  8273. ZX_INFO_PROCESS_THREADS,
  8274. &dummy_buffer,
  8275. 0,
  8276. nullptr,
  8277. &avail);
  8278. if (status == ZX_OK) {
  8279. return avail;
  8280. } else {
  8281. return 0;
  8282. }
  8283. }
  8284. #else
  8285. size_t GetThreadCount() {
  8286. // There's no portable way to detect the number of threads, so we just
  8287. // return 0 to indicate that we cannot detect it.
  8288. return 0;
  8289. }
  8290. #endif // GTEST_OS_LINUX
  8291. #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
  8292. void SleepMilliseconds(int n) {
  8293. ::Sleep(n);
  8294. }
  8295. AutoHandle::AutoHandle()
  8296. : handle_(INVALID_HANDLE_VALUE) {}
  8297. AutoHandle::AutoHandle(Handle handle)
  8298. : handle_(handle) {}
  8299. AutoHandle::~AutoHandle() {
  8300. Reset();
  8301. }
  8302. AutoHandle::Handle AutoHandle::Get() const {
  8303. return handle_;
  8304. }
  8305. void AutoHandle::Reset() {
  8306. Reset(INVALID_HANDLE_VALUE);
  8307. }
  8308. void AutoHandle::Reset(HANDLE handle) {
  8309. // Resetting with the same handle we already own is invalid.
  8310. if (handle_ != handle) {
  8311. if (IsCloseable()) {
  8312. ::CloseHandle(handle_);
  8313. }
  8314. handle_ = handle;
  8315. } else {
  8316. GTEST_CHECK_(!IsCloseable())
  8317. << "Resetting a valid handle to itself is likely a programmer error "
  8318. "and thus not allowed.";
  8319. }
  8320. }
  8321. bool AutoHandle::IsCloseable() const {
  8322. // Different Windows APIs may use either of these values to represent an
  8323. // invalid handle.
  8324. return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;
  8325. }
  8326. Notification::Notification()
  8327. : event_(::CreateEvent(NULL, // Default security attributes.
  8328. TRUE, // Do not reset automatically.
  8329. FALSE, // Initially unset.
  8330. NULL)) { // Anonymous event.
  8331. GTEST_CHECK_(event_.Get() != NULL);
  8332. }
  8333. void Notification::Notify() {
  8334. GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
  8335. }
  8336. void Notification::WaitForNotification() {
  8337. GTEST_CHECK_(
  8338. ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
  8339. }
  8340. Mutex::Mutex()
  8341. : owner_thread_id_(0),
  8342. type_(kDynamic),
  8343. critical_section_init_phase_(0),
  8344. critical_section_(new CRITICAL_SECTION) {
  8345. ::InitializeCriticalSection(critical_section_);
  8346. }
  8347. Mutex::~Mutex() {
  8348. // Static mutexes are leaked intentionally. It is not thread-safe to try
  8349. // to clean them up.
  8350. // FIXME: Switch to Slim Reader/Writer (SRW) Locks, which requires
  8351. // nothing to clean it up but is available only on Vista and later.
  8352. // https://docs.microsoft.com/en-us/windows/desktop/Sync/slim-reader-writer--srw--locks
  8353. if (type_ == kDynamic) {
  8354. ::DeleteCriticalSection(critical_section_);
  8355. delete critical_section_;
  8356. critical_section_ = NULL;
  8357. }
  8358. }
  8359. void Mutex::Lock() {
  8360. ThreadSafeLazyInit();
  8361. ::EnterCriticalSection(critical_section_);
  8362. owner_thread_id_ = ::GetCurrentThreadId();
  8363. }
  8364. void Mutex::Unlock() {
  8365. ThreadSafeLazyInit();
  8366. // We don't protect writing to owner_thread_id_ here, as it's the
  8367. // caller's responsibility to ensure that the current thread holds the
  8368. // mutex when this is called.
  8369. owner_thread_id_ = 0;
  8370. ::LeaveCriticalSection(critical_section_);
  8371. }
  8372. // Does nothing if the current thread holds the mutex. Otherwise, crashes
  8373. // with high probability.
  8374. void Mutex::AssertHeld() {
  8375. ThreadSafeLazyInit();
  8376. GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
  8377. << "The current thread is not holding the mutex @" << this;
  8378. }
  8379. namespace {
  8380. // Use the RAII idiom to flag mem allocs that are intentionally never
  8381. // deallocated. The motivation is to silence the false positive mem leaks
  8382. // that are reported by the debug version of MS's CRT which can only detect
  8383. // if an alloc is missing a matching deallocation.
  8384. // Example:
  8385. // MemoryIsNotDeallocated memory_is_not_deallocated;
  8386. // critical_section_ = new CRITICAL_SECTION;
  8387. //
  8388. class MemoryIsNotDeallocated
  8389. {
  8390. public:
  8391. MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
  8392. #ifdef _MSC_VER
  8393. old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  8394. // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
  8395. // doesn't report mem leak if there's no matching deallocation.
  8396. _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
  8397. #endif // _MSC_VER
  8398. }
  8399. ~MemoryIsNotDeallocated() {
  8400. #ifdef _MSC_VER
  8401. // Restore the original _CRTDBG_ALLOC_MEM_DF flag
  8402. _CrtSetDbgFlag(old_crtdbg_flag_);
  8403. #endif // _MSC_VER
  8404. }
  8405. private:
  8406. int old_crtdbg_flag_;
  8407. GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
  8408. };
  8409. } // namespace
  8410. // Initializes owner_thread_id_ and critical_section_ in static mutexes.
  8411. void Mutex::ThreadSafeLazyInit() {
  8412. // Dynamic mutexes are initialized in the constructor.
  8413. if (type_ == kStatic) {
  8414. switch (
  8415. ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
  8416. case 0:
  8417. // If critical_section_init_phase_ was 0 before the exchange, we
  8418. // are the first to test it and need to perform the initialization.
  8419. owner_thread_id_ = 0;
  8420. {
  8421. // Use RAII to flag that following mem alloc is never deallocated.
  8422. MemoryIsNotDeallocated memory_is_not_deallocated;
  8423. critical_section_ = new CRITICAL_SECTION;
  8424. }
  8425. ::InitializeCriticalSection(critical_section_);
  8426. // Updates the critical_section_init_phase_ to 2 to signal
  8427. // initialization complete.
  8428. GTEST_CHECK_(::InterlockedCompareExchange(
  8429. &critical_section_init_phase_, 2L, 1L) ==
  8430. 1L);
  8431. break;
  8432. case 1:
  8433. // Somebody else is already initializing the mutex; spin until they
  8434. // are done.
  8435. while (::InterlockedCompareExchange(&critical_section_init_phase_,
  8436. 2L,
  8437. 2L) != 2L) {
  8438. // Possibly yields the rest of the thread's time slice to other
  8439. // threads.
  8440. ::Sleep(0);
  8441. }
  8442. break;
  8443. case 2:
  8444. break; // The mutex is already initialized and ready for use.
  8445. default:
  8446. GTEST_CHECK_(false)
  8447. << "Unexpected value of critical_section_init_phase_ "
  8448. << "while initializing a static mutex.";
  8449. }
  8450. }
  8451. }
  8452. namespace {
  8453. class ThreadWithParamSupport : public ThreadWithParamBase {
  8454. public:
  8455. static HANDLE CreateThread(Runnable* runnable,
  8456. Notification* thread_can_start) {
  8457. ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
  8458. DWORD thread_id;
  8459. // FIXME: Consider to use _beginthreadex instead.
  8460. HANDLE thread_handle = ::CreateThread(
  8461. NULL, // Default security.
  8462. 0, // Default stack size.
  8463. &ThreadWithParamSupport::ThreadMain,
  8464. param, // Parameter to ThreadMainStatic
  8465. 0x0, // Default creation flags.
  8466. &thread_id); // Need a valid pointer for the call to work under Win98.
  8467. GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error "
  8468. << ::GetLastError() << ".";
  8469. if (thread_handle == NULL) {
  8470. delete param;
  8471. }
  8472. return thread_handle;
  8473. }
  8474. private:
  8475. struct ThreadMainParam {
  8476. ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
  8477. : runnable_(runnable),
  8478. thread_can_start_(thread_can_start) {
  8479. }
  8480. scoped_ptr<Runnable> runnable_;
  8481. // Does not own.
  8482. Notification* thread_can_start_;
  8483. };
  8484. static DWORD WINAPI ThreadMain(void* ptr) {
  8485. // Transfers ownership.
  8486. scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
  8487. if (param->thread_can_start_ != NULL)
  8488. param->thread_can_start_->WaitForNotification();
  8489. param->runnable_->Run();
  8490. return 0;
  8491. }
  8492. // Prohibit instantiation.
  8493. ThreadWithParamSupport();
  8494. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
  8495. };
  8496. } // namespace
  8497. ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
  8498. Notification* thread_can_start)
  8499. : thread_(ThreadWithParamSupport::CreateThread(runnable,
  8500. thread_can_start)) {
  8501. }
  8502. ThreadWithParamBase::~ThreadWithParamBase() {
  8503. Join();
  8504. }
  8505. void ThreadWithParamBase::Join() {
  8506. GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
  8507. << "Failed to join the thread with error " << ::GetLastError() << ".";
  8508. }
  8509. // Maps a thread to a set of ThreadIdToThreadLocals that have values
  8510. // instantiated on that thread and notifies them when the thread exits. A
  8511. // ThreadLocal instance is expected to persist until all threads it has
  8512. // values on have terminated.
  8513. class ThreadLocalRegistryImpl {
  8514. public:
  8515. // Registers thread_local_instance as having value on the current thread.
  8516. // Returns a value that can be used to identify the thread from other threads.
  8517. static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
  8518. const ThreadLocalBase* thread_local_instance) {
  8519. DWORD current_thread = ::GetCurrentThreadId();
  8520. MutexLock lock(&mutex_);
  8521. ThreadIdToThreadLocals* const thread_to_thread_locals =
  8522. GetThreadLocalsMapLocked();
  8523. ThreadIdToThreadLocals::iterator thread_local_pos =
  8524. thread_to_thread_locals->find(current_thread);
  8525. if (thread_local_pos == thread_to_thread_locals->end()) {
  8526. thread_local_pos = thread_to_thread_locals->insert(
  8527. std::make_pair(current_thread, ThreadLocalValues())).first;
  8528. StartWatcherThreadFor(current_thread);
  8529. }
  8530. ThreadLocalValues& thread_local_values = thread_local_pos->second;
  8531. ThreadLocalValues::iterator value_pos =
  8532. thread_local_values.find(thread_local_instance);
  8533. if (value_pos == thread_local_values.end()) {
  8534. value_pos =
  8535. thread_local_values
  8536. .insert(std::make_pair(
  8537. thread_local_instance,
  8538. linked_ptr<ThreadLocalValueHolderBase>(
  8539. thread_local_instance->NewValueForCurrentThread())))
  8540. .first;
  8541. }
  8542. return value_pos->second.get();
  8543. }
  8544. static void OnThreadLocalDestroyed(
  8545. const ThreadLocalBase* thread_local_instance) {
  8546. std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
  8547. // Clean up the ThreadLocalValues data structure while holding the lock, but
  8548. // defer the destruction of the ThreadLocalValueHolderBases.
  8549. {
  8550. MutexLock lock(&mutex_);
  8551. ThreadIdToThreadLocals* const thread_to_thread_locals =
  8552. GetThreadLocalsMapLocked();
  8553. for (ThreadIdToThreadLocals::iterator it =
  8554. thread_to_thread_locals->begin();
  8555. it != thread_to_thread_locals->end();
  8556. ++it) {
  8557. ThreadLocalValues& thread_local_values = it->second;
  8558. ThreadLocalValues::iterator value_pos =
  8559. thread_local_values.find(thread_local_instance);
  8560. if (value_pos != thread_local_values.end()) {
  8561. value_holders.push_back(value_pos->second);
  8562. thread_local_values.erase(value_pos);
  8563. // This 'if' can only be successful at most once, so theoretically we
  8564. // could break out of the loop here, but we don't bother doing so.
  8565. }
  8566. }
  8567. }
  8568. // Outside the lock, let the destructor for 'value_holders' deallocate the
  8569. // ThreadLocalValueHolderBases.
  8570. }
  8571. static void OnThreadExit(DWORD thread_id) {
  8572. GTEST_CHECK_(thread_id != 0) << ::GetLastError();
  8573. std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
  8574. // Clean up the ThreadIdToThreadLocals data structure while holding the
  8575. // lock, but defer the destruction of the ThreadLocalValueHolderBases.
  8576. {
  8577. MutexLock lock(&mutex_);
  8578. ThreadIdToThreadLocals* const thread_to_thread_locals =
  8579. GetThreadLocalsMapLocked();
  8580. ThreadIdToThreadLocals::iterator thread_local_pos =
  8581. thread_to_thread_locals->find(thread_id);
  8582. if (thread_local_pos != thread_to_thread_locals->end()) {
  8583. ThreadLocalValues& thread_local_values = thread_local_pos->second;
  8584. for (ThreadLocalValues::iterator value_pos =
  8585. thread_local_values.begin();
  8586. value_pos != thread_local_values.end();
  8587. ++value_pos) {
  8588. value_holders.push_back(value_pos->second);
  8589. }
  8590. thread_to_thread_locals->erase(thread_local_pos);
  8591. }
  8592. }
  8593. // Outside the lock, let the destructor for 'value_holders' deallocate the
  8594. // ThreadLocalValueHolderBases.
  8595. }
  8596. private:
  8597. // In a particular thread, maps a ThreadLocal object to its value.
  8598. typedef std::map<const ThreadLocalBase*,
  8599. linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
  8600. // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
  8601. // thread's ID.
  8602. typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
  8603. // Holds the thread id and thread handle that we pass from
  8604. // StartWatcherThreadFor to WatcherThreadFunc.
  8605. typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
  8606. static void StartWatcherThreadFor(DWORD thread_id) {
  8607. // The returned handle will be kept in thread_map and closed by
  8608. // watcher_thread in WatcherThreadFunc.
  8609. HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
  8610. FALSE,
  8611. thread_id);
  8612. GTEST_CHECK_(thread != NULL);
  8613. // We need to pass a valid thread ID pointer into CreateThread for it
  8614. // to work correctly under Win98.
  8615. DWORD watcher_thread_id;
  8616. HANDLE watcher_thread = ::CreateThread(
  8617. NULL, // Default security.
  8618. 0, // Default stack size
  8619. &ThreadLocalRegistryImpl::WatcherThreadFunc,
  8620. reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
  8621. CREATE_SUSPENDED,
  8622. &watcher_thread_id);
  8623. GTEST_CHECK_(watcher_thread != NULL);
  8624. // Give the watcher thread the same priority as ours to avoid being
  8625. // blocked by it.
  8626. ::SetThreadPriority(watcher_thread,
  8627. ::GetThreadPriority(::GetCurrentThread()));
  8628. ::ResumeThread(watcher_thread);
  8629. ::CloseHandle(watcher_thread);
  8630. }
  8631. // Monitors exit from a given thread and notifies those
  8632. // ThreadIdToThreadLocals about thread termination.
  8633. static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
  8634. const ThreadIdAndHandle* tah =
  8635. reinterpret_cast<const ThreadIdAndHandle*>(param);
  8636. GTEST_CHECK_(
  8637. ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
  8638. OnThreadExit(tah->first);
  8639. ::CloseHandle(tah->second);
  8640. delete tah;
  8641. return 0;
  8642. }
  8643. // Returns map of thread local instances.
  8644. static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
  8645. mutex_.AssertHeld();
  8646. MemoryIsNotDeallocated memory_is_not_deallocated;
  8647. static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
  8648. return map;
  8649. }
  8650. // Protects access to GetThreadLocalsMapLocked() and its return value.
  8651. static Mutex mutex_;
  8652. // Protects access to GetThreadMapLocked() and its return value.
  8653. static Mutex thread_map_mutex_;
  8654. };
  8655. Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
  8656. Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
  8657. ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
  8658. const ThreadLocalBase* thread_local_instance) {
  8659. return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
  8660. thread_local_instance);
  8661. }
  8662. void ThreadLocalRegistry::OnThreadLocalDestroyed(
  8663. const ThreadLocalBase* thread_local_instance) {
  8664. ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
  8665. }
  8666. #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
  8667. #if GTEST_USES_POSIX_RE
  8668. // Implements RE. Currently only needed for death tests.
  8669. RE::~RE() {
  8670. if (is_valid_) {
  8671. // regfree'ing an invalid regex might crash because the content
  8672. // of the regex is undefined. Since the regex's are essentially
  8673. // the same, one cannot be valid (or invalid) without the other
  8674. // being so too.
  8675. regfree(&partial_regex_);
  8676. regfree(&full_regex_);
  8677. }
  8678. free(const_cast<char*>(pattern_));
  8679. }
  8680. // Returns true iff regular expression re matches the entire str.
  8681. bool RE::FullMatch(const char* str, const RE& re) {
  8682. if (!re.is_valid_) return false;
  8683. regmatch_t match;
  8684. return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
  8685. }
  8686. // Returns true iff regular expression re matches a substring of str
  8687. // (including str itself).
  8688. bool RE::PartialMatch(const char* str, const RE& re) {
  8689. if (!re.is_valid_) return false;
  8690. regmatch_t match;
  8691. return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
  8692. }
  8693. // Initializes an RE from its string representation.
  8694. void RE::Init(const char* regex) {
  8695. pattern_ = posix::StrDup(regex);
  8696. // Reserves enough bytes to hold the regular expression used for a
  8697. // full match.
  8698. const size_t full_regex_len = strlen(regex) + 10;
  8699. char* const full_pattern = new char[full_regex_len];
  8700. snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
  8701. is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
  8702. // We want to call regcomp(&partial_regex_, ...) even if the
  8703. // previous expression returns false. Otherwise partial_regex_ may
  8704. // not be properly initialized can may cause trouble when it's
  8705. // freed.
  8706. //
  8707. // Some implementation of POSIX regex (e.g. on at least some
  8708. // versions of Cygwin) doesn't accept the empty string as a valid
  8709. // regex. We change it to an equivalent form "()" to be safe.
  8710. if (is_valid_) {
  8711. const char* const partial_regex = (*regex == '\0') ? "()" : regex;
  8712. is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
  8713. }
  8714. EXPECT_TRUE(is_valid_)
  8715. << "Regular expression \"" << regex
  8716. << "\" is not a valid POSIX Extended regular expression.";
  8717. delete[] full_pattern;
  8718. }
  8719. #elif GTEST_USES_SIMPLE_RE
  8720. // Returns true iff ch appears anywhere in str (excluding the
  8721. // terminating '\0' character).
  8722. bool IsInSet(char ch, const char* str) {
  8723. return ch != '\0' && strchr(str, ch) != NULL;
  8724. }
  8725. // Returns true iff ch belongs to the given classification. Unlike
  8726. // similar functions in <ctype.h>, these aren't affected by the
  8727. // current locale.
  8728. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
  8729. bool IsAsciiPunct(char ch) {
  8730. return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
  8731. }
  8732. bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
  8733. bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
  8734. bool IsAsciiWordChar(char ch) {
  8735. return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
  8736. ('0' <= ch && ch <= '9') || ch == '_';
  8737. }
  8738. // Returns true iff "\\c" is a supported escape sequence.
  8739. bool IsValidEscape(char c) {
  8740. return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
  8741. }
  8742. // Returns true iff the given atom (specified by escaped and pattern)
  8743. // matches ch. The result is undefined if the atom is invalid.
  8744. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
  8745. if (escaped) { // "\\p" where p is pattern_char.
  8746. switch (pattern_char) {
  8747. case 'd': return IsAsciiDigit(ch);
  8748. case 'D': return !IsAsciiDigit(ch);
  8749. case 'f': return ch == '\f';
  8750. case 'n': return ch == '\n';
  8751. case 'r': return ch == '\r';
  8752. case 's': return IsAsciiWhiteSpace(ch);
  8753. case 'S': return !IsAsciiWhiteSpace(ch);
  8754. case 't': return ch == '\t';
  8755. case 'v': return ch == '\v';
  8756. case 'w': return IsAsciiWordChar(ch);
  8757. case 'W': return !IsAsciiWordChar(ch);
  8758. }
  8759. return IsAsciiPunct(pattern_char) && pattern_char == ch;
  8760. }
  8761. return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
  8762. }
  8763. // Helper function used by ValidateRegex() to format error messages.
  8764. static std::string FormatRegexSyntaxError(const char* regex, int index) {
  8765. return (Message() << "Syntax error at index " << index
  8766. << " in simple regular expression \"" << regex << "\": ").GetString();
  8767. }
  8768. // Generates non-fatal failures and returns false if regex is invalid;
  8769. // otherwise returns true.
  8770. bool ValidateRegex(const char* regex) {
  8771. if (regex == NULL) {
  8772. // FIXME: fix the source file location in the
  8773. // assertion failures to match where the regex is used in user
  8774. // code.
  8775. ADD_FAILURE() << "NULL is not a valid simple regular expression.";
  8776. return false;
  8777. }
  8778. bool is_valid = true;
  8779. // True iff ?, *, or + can follow the previous atom.
  8780. bool prev_repeatable = false;
  8781. for (int i = 0; regex[i]; i++) {
  8782. if (regex[i] == '\\') { // An escape sequence
  8783. i++;
  8784. if (regex[i] == '\0') {
  8785. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  8786. << "'\\' cannot appear at the end.";
  8787. return false;
  8788. }
  8789. if (!IsValidEscape(regex[i])) {
  8790. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  8791. << "invalid escape sequence \"\\" << regex[i] << "\".";
  8792. is_valid = false;
  8793. }
  8794. prev_repeatable = true;
  8795. } else { // Not an escape sequence.
  8796. const char ch = regex[i];
  8797. if (ch == '^' && i > 0) {
  8798. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  8799. << "'^' can only appear at the beginning.";
  8800. is_valid = false;
  8801. } else if (ch == '$' && regex[i + 1] != '\0') {
  8802. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  8803. << "'$' can only appear at the end.";
  8804. is_valid = false;
  8805. } else if (IsInSet(ch, "()[]{}|")) {
  8806. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  8807. << "'" << ch << "' is unsupported.";
  8808. is_valid = false;
  8809. } else if (IsRepeat(ch) && !prev_repeatable) {
  8810. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  8811. << "'" << ch << "' can only follow a repeatable token.";
  8812. is_valid = false;
  8813. }
  8814. prev_repeatable = !IsInSet(ch, "^$?*+");
  8815. }
  8816. }
  8817. return is_valid;
  8818. }
  8819. // Matches a repeated regex atom followed by a valid simple regular
  8820. // expression. The regex atom is defined as c if escaped is false,
  8821. // or \c otherwise. repeat is the repetition meta character (?, *,
  8822. // or +). The behavior is undefined if str contains too many
  8823. // characters to be indexable by size_t, in which case the test will
  8824. // probably time out anyway. We are fine with this limitation as
  8825. // std::string has it too.
  8826. bool MatchRepetitionAndRegexAtHead(
  8827. bool escaped, char c, char repeat, const char* regex,
  8828. const char* str) {
  8829. const size_t min_count = (repeat == '+') ? 1 : 0;
  8830. const size_t max_count = (repeat == '?') ? 1 :
  8831. static_cast<size_t>(-1) - 1;
  8832. // We cannot call numeric_limits::max() as it conflicts with the
  8833. // max() macro on Windows.
  8834. for (size_t i = 0; i <= max_count; ++i) {
  8835. // We know that the atom matches each of the first i characters in str.
  8836. if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
  8837. // We have enough matches at the head, and the tail matches too.
  8838. // Since we only care about *whether* the pattern matches str
  8839. // (as opposed to *how* it matches), there is no need to find a
  8840. // greedy match.
  8841. return true;
  8842. }
  8843. if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
  8844. return false;
  8845. }
  8846. return false;
  8847. }
  8848. // Returns true iff regex matches a prefix of str. regex must be a
  8849. // valid simple regular expression and not start with "^", or the
  8850. // result is undefined.
  8851. bool MatchRegexAtHead(const char* regex, const char* str) {
  8852. if (*regex == '\0') // An empty regex matches a prefix of anything.
  8853. return true;
  8854. // "$" only matches the end of a string. Note that regex being
  8855. // valid guarantees that there's nothing after "$" in it.
  8856. if (*regex == '$')
  8857. return *str == '\0';
  8858. // Is the first thing in regex an escape sequence?
  8859. const bool escaped = *regex == '\\';
  8860. if (escaped)
  8861. ++regex;
  8862. if (IsRepeat(regex[1])) {
  8863. // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
  8864. // here's an indirect recursion. It terminates as the regex gets
  8865. // shorter in each recursion.
  8866. return MatchRepetitionAndRegexAtHead(
  8867. escaped, regex[0], regex[1], regex + 2, str);
  8868. } else {
  8869. // regex isn't empty, isn't "$", and doesn't start with a
  8870. // repetition. We match the first atom of regex with the first
  8871. // character of str and recurse.
  8872. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
  8873. MatchRegexAtHead(regex + 1, str + 1);
  8874. }
  8875. }
  8876. // Returns true iff regex matches any substring of str. regex must be
  8877. // a valid simple regular expression, or the result is undefined.
  8878. //
  8879. // The algorithm is recursive, but the recursion depth doesn't exceed
  8880. // the regex length, so we won't need to worry about running out of
  8881. // stack space normally. In rare cases the time complexity can be
  8882. // exponential with respect to the regex length + the string length,
  8883. // but usually it's must faster (often close to linear).
  8884. bool MatchRegexAnywhere(const char* regex, const char* str) {
  8885. if (regex == NULL || str == NULL)
  8886. return false;
  8887. if (*regex == '^')
  8888. return MatchRegexAtHead(regex + 1, str);
  8889. // A successful match can be anywhere in str.
  8890. do {
  8891. if (MatchRegexAtHead(regex, str))
  8892. return true;
  8893. } while (*str++ != '\0');
  8894. return false;
  8895. }
  8896. // Implements the RE class.
  8897. RE::~RE() {
  8898. free(const_cast<char*>(pattern_));
  8899. free(const_cast<char*>(full_pattern_));
  8900. }
  8901. // Returns true iff regular expression re matches the entire str.
  8902. bool RE::FullMatch(const char* str, const RE& re) {
  8903. return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
  8904. }
  8905. // Returns true iff regular expression re matches a substring of str
  8906. // (including str itself).
  8907. bool RE::PartialMatch(const char* str, const RE& re) {
  8908. return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
  8909. }
  8910. // Initializes an RE from its string representation.
  8911. void RE::Init(const char* regex) {
  8912. pattern_ = full_pattern_ = NULL;
  8913. if (regex != NULL) {
  8914. pattern_ = posix::StrDup(regex);
  8915. }
  8916. is_valid_ = ValidateRegex(regex);
  8917. if (!is_valid_) {
  8918. // No need to calculate the full pattern when the regex is invalid.
  8919. return;
  8920. }
  8921. const size_t len = strlen(regex);
  8922. // Reserves enough bytes to hold the regular expression used for a
  8923. // full match: we need space to prepend a '^', append a '$', and
  8924. // terminate the string with '\0'.
  8925. char* buffer = static_cast<char*>(malloc(len + 3));
  8926. full_pattern_ = buffer;
  8927. if (*regex != '^')
  8928. *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
  8929. // We don't use snprintf or strncpy, as they trigger a warning when
  8930. // compiled with VC++ 8.0.
  8931. memcpy(buffer, regex, len);
  8932. buffer += len;
  8933. if (len == 0 || regex[len - 1] != '$')
  8934. *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
  8935. *buffer = '\0';
  8936. }
  8937. #endif // GTEST_USES_POSIX_RE
  8938. const char kUnknownFile[] = "unknown file";
  8939. // Formats a source file path and a line number as they would appear
  8940. // in an error message from the compiler used to compile this code.
  8941. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
  8942. const std::string file_name(file == NULL ? kUnknownFile : file);
  8943. if (line < 0) {
  8944. return file_name + ":";
  8945. }
  8946. #ifdef _MSC_VER
  8947. return file_name + "(" + StreamableToString(line) + "):";
  8948. #else
  8949. return file_name + ":" + StreamableToString(line) + ":";
  8950. #endif // _MSC_VER
  8951. }
  8952. // Formats a file location for compiler-independent XML output.
  8953. // Although this function is not platform dependent, we put it next to
  8954. // FormatFileLocation in order to contrast the two functions.
  8955. // Note that FormatCompilerIndependentFileLocation() does NOT append colon
  8956. // to the file location it produces, unlike FormatFileLocation().
  8957. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
  8958. const char* file, int line) {
  8959. const std::string file_name(file == NULL ? kUnknownFile : file);
  8960. if (line < 0)
  8961. return file_name;
  8962. else
  8963. return file_name + ":" + StreamableToString(line);
  8964. }
  8965. GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
  8966. : severity_(severity) {
  8967. const char* const marker =
  8968. severity == GTEST_INFO ? "[ INFO ]" :
  8969. severity == GTEST_WARNING ? "[WARNING]" :
  8970. severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
  8971. GetStream() << ::std::endl << marker << " "
  8972. << FormatFileLocation(file, line).c_str() << ": ";
  8973. }
  8974. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  8975. GTestLog::~GTestLog() {
  8976. GetStream() << ::std::endl;
  8977. if (severity_ == GTEST_FATAL) {
  8978. fflush(stderr);
  8979. posix::Abort();
  8980. }
  8981. }
  8982. // Disable Microsoft deprecation warnings for POSIX functions called from
  8983. // this class (creat, dup, dup2, and close)
  8984. GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
  8985. #if GTEST_HAS_STREAM_REDIRECTION
  8986. // Object that captures an output stream (stdout/stderr).
  8987. class CapturedStream {
  8988. public:
  8989. // The ctor redirects the stream to a temporary file.
  8990. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
  8991. # if GTEST_OS_WINDOWS
  8992. char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  8993. char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  8994. ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
  8995. const UINT success = ::GetTempFileNameA(temp_dir_path,
  8996. "gtest_redir",
  8997. 0, // Generate unique file name.
  8998. temp_file_path);
  8999. GTEST_CHECK_(success != 0)
  9000. << "Unable to create a temporary file in " << temp_dir_path;
  9001. const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
  9002. GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
  9003. << temp_file_path;
  9004. filename_ = temp_file_path;
  9005. # else
  9006. // There's no guarantee that a test has write access to the current
  9007. // directory, so we create the temporary file in the /tmp directory
  9008. // instead. We use /tmp on most systems, and /sdcard on Android.
  9009. // That's because Android doesn't have /tmp.
  9010. # if GTEST_OS_LINUX_ANDROID
  9011. // Note: Android applications are expected to call the framework's
  9012. // Context.getExternalStorageDirectory() method through JNI to get
  9013. // the location of the world-writable SD Card directory. However,
  9014. // this requires a Context handle, which cannot be retrieved
  9015. // globally from native code. Doing so also precludes running the
  9016. // code as part of a regular standalone executable, which doesn't
  9017. // run in a Dalvik process (e.g. when running it through 'adb shell').
  9018. //
  9019. // The location /sdcard is directly accessible from native code
  9020. // and is the only location (unofficially) supported by the Android
  9021. // team. It's generally a symlink to the real SD Card mount point
  9022. // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
  9023. // other OEM-customized locations. Never rely on these, and always
  9024. // use /sdcard.
  9025. char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
  9026. # else
  9027. char name_template[] = "/tmp/captured_stream.XXXXXX";
  9028. # endif // GTEST_OS_LINUX_ANDROID
  9029. const int captured_fd = mkstemp(name_template);
  9030. filename_ = name_template;
  9031. # endif // GTEST_OS_WINDOWS
  9032. fflush(NULL);
  9033. dup2(captured_fd, fd_);
  9034. close(captured_fd);
  9035. }
  9036. ~CapturedStream() {
  9037. remove(filename_.c_str());
  9038. }
  9039. std::string GetCapturedString() {
  9040. if (uncaptured_fd_ != -1) {
  9041. // Restores the original stream.
  9042. fflush(NULL);
  9043. dup2(uncaptured_fd_, fd_);
  9044. close(uncaptured_fd_);
  9045. uncaptured_fd_ = -1;
  9046. }
  9047. FILE* const file = posix::FOpen(filename_.c_str(), "r");
  9048. const std::string content = ReadEntireFile(file);
  9049. posix::FClose(file);
  9050. return content;
  9051. }
  9052. private:
  9053. const int fd_; // A stream to capture.
  9054. int uncaptured_fd_;
  9055. // Name of the temporary file holding the stderr output.
  9056. ::std::string filename_;
  9057. GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
  9058. };
  9059. GTEST_DISABLE_MSC_DEPRECATED_POP_()
  9060. static CapturedStream* g_captured_stderr = NULL;
  9061. static CapturedStream* g_captured_stdout = NULL;
  9062. // Starts capturing an output stream (stdout/stderr).
  9063. static void CaptureStream(int fd, const char* stream_name,
  9064. CapturedStream** stream) {
  9065. if (*stream != NULL) {
  9066. GTEST_LOG_(FATAL) << "Only one " << stream_name
  9067. << " capturer can exist at a time.";
  9068. }
  9069. *stream = new CapturedStream(fd);
  9070. }
  9071. // Stops capturing the output stream and returns the captured string.
  9072. static std::string GetCapturedStream(CapturedStream** captured_stream) {
  9073. const std::string content = (*captured_stream)->GetCapturedString();
  9074. delete *captured_stream;
  9075. *captured_stream = NULL;
  9076. return content;
  9077. }
  9078. // Starts capturing stdout.
  9079. void CaptureStdout() {
  9080. CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
  9081. }
  9082. // Starts capturing stderr.
  9083. void CaptureStderr() {
  9084. CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
  9085. }
  9086. // Stops capturing stdout and returns the captured string.
  9087. std::string GetCapturedStdout() {
  9088. return GetCapturedStream(&g_captured_stdout);
  9089. }
  9090. // Stops capturing stderr and returns the captured string.
  9091. std::string GetCapturedStderr() {
  9092. return GetCapturedStream(&g_captured_stderr);
  9093. }
  9094. #endif // GTEST_HAS_STREAM_REDIRECTION
  9095. size_t GetFileSize(FILE* file) {
  9096. fseek(file, 0, SEEK_END);
  9097. return static_cast<size_t>(ftell(file));
  9098. }
  9099. std::string ReadEntireFile(FILE* file) {
  9100. const size_t file_size = GetFileSize(file);
  9101. char* const buffer = new char[file_size];
  9102. size_t bytes_last_read = 0; // # of bytes read in the last fread()
  9103. size_t bytes_read = 0; // # of bytes read so far
  9104. fseek(file, 0, SEEK_SET);
  9105. // Keeps reading the file until we cannot read further or the
  9106. // pre-determined file size is reached.
  9107. do {
  9108. bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
  9109. bytes_read += bytes_last_read;
  9110. } while (bytes_last_read > 0 && bytes_read < file_size);
  9111. const std::string content(buffer, bytes_read);
  9112. delete[] buffer;
  9113. return content;
  9114. }
  9115. #if GTEST_HAS_DEATH_TEST
  9116. static const std::vector<std::string>* g_injected_test_argvs = NULL; // Owned.
  9117. std::vector<std::string> GetInjectableArgvs() {
  9118. if (g_injected_test_argvs != NULL) {
  9119. return *g_injected_test_argvs;
  9120. }
  9121. return GetArgvs();
  9122. }
  9123. void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
  9124. if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
  9125. g_injected_test_argvs = new_argvs;
  9126. }
  9127. void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
  9128. SetInjectableArgvs(
  9129. new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
  9130. }
  9131. #if GTEST_HAS_GLOBAL_STRING
  9132. void SetInjectableArgvs(const std::vector< ::string>& new_argvs) {
  9133. SetInjectableArgvs(
  9134. new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
  9135. }
  9136. #endif // GTEST_HAS_GLOBAL_STRING
  9137. void ClearInjectableArgvs() {
  9138. delete g_injected_test_argvs;
  9139. g_injected_test_argvs = NULL;
  9140. }
  9141. #endif // GTEST_HAS_DEATH_TEST
  9142. #if GTEST_OS_WINDOWS_MOBILE
  9143. namespace posix {
  9144. void Abort() {
  9145. DebugBreak();
  9146. TerminateProcess(GetCurrentProcess(), 1);
  9147. }
  9148. } // namespace posix
  9149. #endif // GTEST_OS_WINDOWS_MOBILE
  9150. // Returns the name of the environment variable corresponding to the
  9151. // given flag. For example, FlagToEnvVar("foo") will return
  9152. // "GTEST_FOO" in the open-source version.
  9153. static std::string FlagToEnvVar(const char* flag) {
  9154. const std::string full_flag =
  9155. (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
  9156. Message env_var;
  9157. for (size_t i = 0; i != full_flag.length(); i++) {
  9158. env_var << ToUpper(full_flag.c_str()[i]);
  9159. }
  9160. return env_var.GetString();
  9161. }
  9162. // Parses 'str' for a 32-bit signed integer. If successful, writes
  9163. // the result to *value and returns true; otherwise leaves *value
  9164. // unchanged and returns false.
  9165. bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
  9166. // Parses the environment variable as a decimal integer.
  9167. char* end = NULL;
  9168. const long long_value = strtol(str, &end, 10); // NOLINT
  9169. // Has strtol() consumed all characters in the string?
  9170. if (*end != '\0') {
  9171. // No - an invalid character was encountered.
  9172. Message msg;
  9173. msg << "WARNING: " << src_text
  9174. << " is expected to be a 32-bit integer, but actually"
  9175. << " has value \"" << str << "\".\n";
  9176. printf("%s", msg.GetString().c_str());
  9177. fflush(stdout);
  9178. return false;
  9179. }
  9180. // Is the parsed value in the range of an Int32?
  9181. const Int32 result = static_cast<Int32>(long_value);
  9182. if (long_value == LONG_MAX || long_value == LONG_MIN ||
  9183. // The parsed value overflows as a long. (strtol() returns
  9184. // LONG_MAX or LONG_MIN when the input overflows.)
  9185. result != long_value
  9186. // The parsed value overflows as an Int32.
  9187. ) {
  9188. Message msg;
  9189. msg << "WARNING: " << src_text
  9190. << " is expected to be a 32-bit integer, but actually"
  9191. << " has value " << str << ", which overflows.\n";
  9192. printf("%s", msg.GetString().c_str());
  9193. fflush(stdout);
  9194. return false;
  9195. }
  9196. *value = result;
  9197. return true;
  9198. }
  9199. // Reads and returns the Boolean environment variable corresponding to
  9200. // the given flag; if it's not set, returns default_value.
  9201. //
  9202. // The value is considered true iff it's not "0".
  9203. bool BoolFromGTestEnv(const char* flag, bool default_value) {
  9204. #if defined(GTEST_GET_BOOL_FROM_ENV_)
  9205. return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
  9206. #else
  9207. const std::string env_var = FlagToEnvVar(flag);
  9208. const char* const string_value = posix::GetEnv(env_var.c_str());
  9209. return string_value == NULL ?
  9210. default_value : strcmp(string_value, "0") != 0;
  9211. #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
  9212. }
  9213. // Reads and returns a 32-bit integer stored in the environment
  9214. // variable corresponding to the given flag; if it isn't set or
  9215. // doesn't represent a valid 32-bit integer, returns default_value.
  9216. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
  9217. #if defined(GTEST_GET_INT32_FROM_ENV_)
  9218. return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
  9219. #else
  9220. const std::string env_var = FlagToEnvVar(flag);
  9221. const char* const string_value = posix::GetEnv(env_var.c_str());
  9222. if (string_value == NULL) {
  9223. // The environment variable is not set.
  9224. return default_value;
  9225. }
  9226. Int32 result = default_value;
  9227. if (!ParseInt32(Message() << "Environment variable " << env_var,
  9228. string_value, &result)) {
  9229. printf("The default value %s is used.\n",
  9230. (Message() << default_value).GetString().c_str());
  9231. fflush(stdout);
  9232. return default_value;
  9233. }
  9234. return result;
  9235. #endif // defined(GTEST_GET_INT32_FROM_ENV_)
  9236. }
  9237. // As a special case for the 'output' flag, if GTEST_OUTPUT is not
  9238. // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
  9239. // system. The value of XML_OUTPUT_FILE is a filename without the
  9240. // "xml:" prefix of GTEST_OUTPUT.
  9241. // Note that this is meant to be called at the call site so it does
  9242. // not check that the flag is 'output'
  9243. // In essence this checks an env variable called XML_OUTPUT_FILE
  9244. // and if it is set we prepend "xml:" to its value, if it not set we return ""
  9245. std::string OutputFlagAlsoCheckEnvVar(){
  9246. std::string default_value_for_output_flag = "";
  9247. const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
  9248. if (NULL != xml_output_file_env) {
  9249. default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
  9250. }
  9251. return default_value_for_output_flag;
  9252. }
  9253. // Reads and returns the string environment variable corresponding to
  9254. // the given flag; if it's not set, returns default_value.
  9255. const char* StringFromGTestEnv(const char* flag, const char* default_value) {
  9256. #if defined(GTEST_GET_STRING_FROM_ENV_)
  9257. return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
  9258. #else
  9259. const std::string env_var = FlagToEnvVar(flag);
  9260. const char* const value = posix::GetEnv(env_var.c_str());
  9261. return value == NULL ? default_value : value;
  9262. #endif // defined(GTEST_GET_STRING_FROM_ENV_)
  9263. }
  9264. } // namespace internal
  9265. } // namespace testing
  9266. // Copyright 2007, Google Inc.
  9267. // All rights reserved.
  9268. //
  9269. // Redistribution and use in source and binary forms, with or without
  9270. // modification, are permitted provided that the following conditions are
  9271. // met:
  9272. //
  9273. // * Redistributions of source code must retain the above copyright
  9274. // notice, this list of conditions and the following disclaimer.
  9275. // * Redistributions in binary form must reproduce the above
  9276. // copyright notice, this list of conditions and the following disclaimer
  9277. // in the documentation and/or other materials provided with the
  9278. // distribution.
  9279. // * Neither the name of Google Inc. nor the names of its
  9280. // contributors may be used to endorse or promote products derived from
  9281. // this software without specific prior written permission.
  9282. //
  9283. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  9284. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  9285. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  9286. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9287. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  9288. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9289. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  9290. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9291. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  9292. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  9293. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9294. // Google Test - The Google C++ Testing and Mocking Framework
  9295. //
  9296. // This file implements a universal value printer that can print a
  9297. // value of any type T:
  9298. //
  9299. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  9300. //
  9301. // It uses the << operator when possible, and prints the bytes in the
  9302. // object otherwise. A user can override its behavior for a class
  9303. // type Foo by defining either operator<<(::std::ostream&, const Foo&)
  9304. // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
  9305. // defines Foo.
  9306. #include <stdio.h>
  9307. #include <cctype>
  9308. #include <cwchar>
  9309. #include <ostream> // NOLINT
  9310. #include <string>
  9311. namespace testing {
  9312. namespace {
  9313. using ::std::ostream;
  9314. // Prints a segment of bytes in the given object.
  9315. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  9316. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  9317. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  9318. void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
  9319. size_t count, ostream* os) {
  9320. char text[5] = "";
  9321. for (size_t i = 0; i != count; i++) {
  9322. const size_t j = start + i;
  9323. if (i != 0) {
  9324. // Organizes the bytes into groups of 2 for easy parsing by
  9325. // human.
  9326. if ((j % 2) == 0)
  9327. *os << ' ';
  9328. else
  9329. *os << '-';
  9330. }
  9331. GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
  9332. *os << text;
  9333. }
  9334. }
  9335. // Prints the bytes in the given value to the given ostream.
  9336. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
  9337. ostream* os) {
  9338. // Tells the user how big the object is.
  9339. *os << count << "-byte object <";
  9340. const size_t kThreshold = 132;
  9341. const size_t kChunkSize = 64;
  9342. // If the object size is bigger than kThreshold, we'll have to omit
  9343. // some details by printing only the first and the last kChunkSize
  9344. // bytes.
  9345. // FIXME: let the user control the threshold using a flag.
  9346. if (count < kThreshold) {
  9347. PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
  9348. } else {
  9349. PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
  9350. *os << " ... ";
  9351. // Rounds up to 2-byte boundary.
  9352. const size_t resume_pos = (count - kChunkSize + 1)/2*2;
  9353. PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
  9354. }
  9355. *os << ">";
  9356. }
  9357. } // namespace
  9358. namespace internal2 {
  9359. // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
  9360. // given object. The delegation simplifies the implementation, which
  9361. // uses the << operator and thus is easier done outside of the
  9362. // ::testing::internal namespace, which contains a << operator that
  9363. // sometimes conflicts with the one in STL.
  9364. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
  9365. ostream* os) {
  9366. PrintBytesInObjectToImpl(obj_bytes, count, os);
  9367. }
  9368. } // namespace internal2
  9369. namespace internal {
  9370. // Depending on the value of a char (or wchar_t), we print it in one
  9371. // of three formats:
  9372. // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
  9373. // - as a hexadecimal escape sequence (e.g. '\x7F'), or
  9374. // - as a special escape sequence (e.g. '\r', '\n').
  9375. enum CharFormat {
  9376. kAsIs,
  9377. kHexEscape,
  9378. kSpecialEscape
  9379. };
  9380. // Returns true if c is a printable ASCII character. We test the
  9381. // value of c directly instead of calling isprint(), which is buggy on
  9382. // Windows Mobile.
  9383. inline bool IsPrintableAscii(wchar_t c) {
  9384. return 0x20 <= c && c <= 0x7E;
  9385. }
  9386. // Prints a wide or narrow char c as a character literal without the
  9387. // quotes, escaping it when necessary; returns how c was formatted.
  9388. // The template argument UnsignedChar is the unsigned version of Char,
  9389. // which is the type of c.
  9390. template <typename UnsignedChar, typename Char>
  9391. static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
  9392. switch (static_cast<wchar_t>(c)) {
  9393. case L'\0':
  9394. *os << "\\0";
  9395. break;
  9396. case L'\'':
  9397. *os << "\\'";
  9398. break;
  9399. case L'\\':
  9400. *os << "\\\\";
  9401. break;
  9402. case L'\a':
  9403. *os << "\\a";
  9404. break;
  9405. case L'\b':
  9406. *os << "\\b";
  9407. break;
  9408. case L'\f':
  9409. *os << "\\f";
  9410. break;
  9411. case L'\n':
  9412. *os << "\\n";
  9413. break;
  9414. case L'\r':
  9415. *os << "\\r";
  9416. break;
  9417. case L'\t':
  9418. *os << "\\t";
  9419. break;
  9420. case L'\v':
  9421. *os << "\\v";
  9422. break;
  9423. default:
  9424. if (IsPrintableAscii(c)) {
  9425. *os << static_cast<char>(c);
  9426. return kAsIs;
  9427. } else {
  9428. ostream::fmtflags flags = os->flags();
  9429. *os << "\\x" << std::hex << std::uppercase
  9430. << static_cast<int>(static_cast<UnsignedChar>(c));
  9431. os->flags(flags);
  9432. return kHexEscape;
  9433. }
  9434. }
  9435. return kSpecialEscape;
  9436. }
  9437. // Prints a wchar_t c as if it's part of a string literal, escaping it when
  9438. // necessary; returns how c was formatted.
  9439. static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
  9440. switch (c) {
  9441. case L'\'':
  9442. *os << "'";
  9443. return kAsIs;
  9444. case L'"':
  9445. *os << "\\\"";
  9446. return kSpecialEscape;
  9447. default:
  9448. return PrintAsCharLiteralTo<wchar_t>(c, os);
  9449. }
  9450. }
  9451. // Prints a char c as if it's part of a string literal, escaping it when
  9452. // necessary; returns how c was formatted.
  9453. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
  9454. return PrintAsStringLiteralTo(
  9455. static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
  9456. }
  9457. // Prints a wide or narrow character c and its code. '\0' is printed
  9458. // as "'\\0'", other unprintable characters are also properly escaped
  9459. // using the standard C++ escape sequence. The template argument
  9460. // UnsignedChar is the unsigned version of Char, which is the type of c.
  9461. template <typename UnsignedChar, typename Char>
  9462. void PrintCharAndCodeTo(Char c, ostream* os) {
  9463. // First, print c as a literal in the most readable form we can find.
  9464. *os << ((sizeof(c) > 1) ? "L'" : "'");
  9465. const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
  9466. *os << "'";
  9467. // To aid user debugging, we also print c's code in decimal, unless
  9468. // it's 0 (in which case c was printed as '\\0', making the code
  9469. // obvious).
  9470. if (c == 0)
  9471. return;
  9472. *os << " (" << static_cast<int>(c);
  9473. // For more convenience, we print c's code again in hexadecimal,
  9474. // unless c was already printed in the form '\x##' or the code is in
  9475. // [1, 9].
  9476. if (format == kHexEscape || (1 <= c && c <= 9)) {
  9477. // Do nothing.
  9478. } else {
  9479. *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
  9480. }
  9481. *os << ")";
  9482. }
  9483. void PrintTo(unsigned char c, ::std::ostream* os) {
  9484. PrintCharAndCodeTo<unsigned char>(c, os);
  9485. }
  9486. void PrintTo(signed char c, ::std::ostream* os) {
  9487. PrintCharAndCodeTo<unsigned char>(c, os);
  9488. }
  9489. // Prints a wchar_t as a symbol if it is printable or as its internal
  9490. // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
  9491. void PrintTo(wchar_t wc, ostream* os) {
  9492. PrintCharAndCodeTo<wchar_t>(wc, os);
  9493. }
  9494. // Prints the given array of characters to the ostream. CharType must be either
  9495. // char or wchar_t.
  9496. // The array starts at begin, the length is len, it may include '\0' characters
  9497. // and may not be NUL-terminated.
  9498. template <typename CharType>
  9499. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  9500. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  9501. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  9502. static CharFormat PrintCharsAsStringTo(
  9503. const CharType* begin, size_t len, ostream* os) {
  9504. const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
  9505. *os << kQuoteBegin;
  9506. bool is_previous_hex = false;
  9507. CharFormat print_format = kAsIs;
  9508. for (size_t index = 0; index < len; ++index) {
  9509. const CharType cur = begin[index];
  9510. if (is_previous_hex && IsXDigit(cur)) {
  9511. // Previous character is of '\x..' form and this character can be
  9512. // interpreted as another hexadecimal digit in its number. Break string to
  9513. // disambiguate.
  9514. *os << "\" " << kQuoteBegin;
  9515. }
  9516. is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
  9517. // Remember if any characters required hex escaping.
  9518. if (is_previous_hex) {
  9519. print_format = kHexEscape;
  9520. }
  9521. }
  9522. *os << "\"";
  9523. return print_format;
  9524. }
  9525. // Prints a (const) char/wchar_t array of 'len' elements, starting at address
  9526. // 'begin'. CharType must be either char or wchar_t.
  9527. template <typename CharType>
  9528. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  9529. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  9530. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  9531. static void UniversalPrintCharArray(
  9532. const CharType* begin, size_t len, ostream* os) {
  9533. // The code
  9534. // const char kFoo[] = "foo";
  9535. // generates an array of 4, not 3, elements, with the last one being '\0'.
  9536. //
  9537. // Therefore when printing a char array, we don't print the last element if
  9538. // it's '\0', such that the output matches the string literal as it's
  9539. // written in the source code.
  9540. if (len > 0 && begin[len - 1] == '\0') {
  9541. PrintCharsAsStringTo(begin, len - 1, os);
  9542. return;
  9543. }
  9544. // If, however, the last element in the array is not '\0', e.g.
  9545. // const char kFoo[] = { 'f', 'o', 'o' };
  9546. // we must print the entire array. We also print a message to indicate
  9547. // that the array is not NUL-terminated.
  9548. PrintCharsAsStringTo(begin, len, os);
  9549. *os << " (no terminating NUL)";
  9550. }
  9551. // Prints a (const) char array of 'len' elements, starting at address 'begin'.
  9552. void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
  9553. UniversalPrintCharArray(begin, len, os);
  9554. }
  9555. // Prints a (const) wchar_t array of 'len' elements, starting at address
  9556. // 'begin'.
  9557. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
  9558. UniversalPrintCharArray(begin, len, os);
  9559. }
  9560. // Prints the given C string to the ostream.
  9561. void PrintTo(const char* s, ostream* os) {
  9562. if (s == NULL) {
  9563. *os << "NULL";
  9564. } else {
  9565. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  9566. PrintCharsAsStringTo(s, strlen(s), os);
  9567. }
  9568. }
  9569. // MSVC compiler can be configured to define whar_t as a typedef
  9570. // of unsigned short. Defining an overload for const wchar_t* in that case
  9571. // would cause pointers to unsigned shorts be printed as wide strings,
  9572. // possibly accessing more memory than intended and causing invalid
  9573. // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
  9574. // wchar_t is implemented as a native type.
  9575. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  9576. // Prints the given wide C string to the ostream.
  9577. void PrintTo(const wchar_t* s, ostream* os) {
  9578. if (s == NULL) {
  9579. *os << "NULL";
  9580. } else {
  9581. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  9582. PrintCharsAsStringTo(s, std::wcslen(s), os);
  9583. }
  9584. }
  9585. #endif // wchar_t is native
  9586. namespace {
  9587. bool ContainsUnprintableControlCodes(const char* str, size_t length) {
  9588. const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
  9589. for (size_t i = 0; i < length; i++) {
  9590. unsigned char ch = *s++;
  9591. if (std::iscntrl(ch)) {
  9592. switch (ch) {
  9593. case '\t':
  9594. case '\n':
  9595. case '\r':
  9596. break;
  9597. default:
  9598. return true;
  9599. }
  9600. }
  9601. }
  9602. return false;
  9603. }
  9604. bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
  9605. bool IsValidUTF8(const char* str, size_t length) {
  9606. const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
  9607. for (size_t i = 0; i < length;) {
  9608. unsigned char lead = s[i++];
  9609. if (lead <= 0x7f) {
  9610. continue; // single-byte character (ASCII) 0..7F
  9611. }
  9612. if (lead < 0xc2) {
  9613. return false; // trail byte or non-shortest form
  9614. } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
  9615. ++i; // 2-byte character
  9616. } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
  9617. IsUTF8TrailByte(s[i]) &&
  9618. IsUTF8TrailByte(s[i + 1]) &&
  9619. // check for non-shortest form and surrogate
  9620. (lead != 0xe0 || s[i] >= 0xa0) &&
  9621. (lead != 0xed || s[i] < 0xa0)) {
  9622. i += 2; // 3-byte character
  9623. } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
  9624. IsUTF8TrailByte(s[i]) &&
  9625. IsUTF8TrailByte(s[i + 1]) &&
  9626. IsUTF8TrailByte(s[i + 2]) &&
  9627. // check for non-shortest form
  9628. (lead != 0xf0 || s[i] >= 0x90) &&
  9629. (lead != 0xf4 || s[i] < 0x90)) {
  9630. i += 3; // 4-byte character
  9631. } else {
  9632. return false;
  9633. }
  9634. }
  9635. return true;
  9636. }
  9637. void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
  9638. if (!ContainsUnprintableControlCodes(str, length) &&
  9639. IsValidUTF8(str, length)) {
  9640. *os << "\n As Text: \"" << str << "\"";
  9641. }
  9642. }
  9643. } // anonymous namespace
  9644. // Prints a ::string object.
  9645. #if GTEST_HAS_GLOBAL_STRING
  9646. void PrintStringTo(const ::string& s, ostream* os) {
  9647. if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
  9648. if (GTEST_FLAG(print_utf8)) {
  9649. ConditionalPrintAsText(s.data(), s.size(), os);
  9650. }
  9651. }
  9652. }
  9653. #endif // GTEST_HAS_GLOBAL_STRING
  9654. void PrintStringTo(const ::std::string& s, ostream* os) {
  9655. if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
  9656. if (GTEST_FLAG(print_utf8)) {
  9657. ConditionalPrintAsText(s.data(), s.size(), os);
  9658. }
  9659. }
  9660. }
  9661. // Prints a ::wstring object.
  9662. #if GTEST_HAS_GLOBAL_WSTRING
  9663. void PrintWideStringTo(const ::wstring& s, ostream* os) {
  9664. PrintCharsAsStringTo(s.data(), s.size(), os);
  9665. }
  9666. #endif // GTEST_HAS_GLOBAL_WSTRING
  9667. #if GTEST_HAS_STD_WSTRING
  9668. void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
  9669. PrintCharsAsStringTo(s.data(), s.size(), os);
  9670. }
  9671. #endif // GTEST_HAS_STD_WSTRING
  9672. } // namespace internal
  9673. } // namespace testing
  9674. // Copyright 2008, Google Inc.
  9675. // All rights reserved.
  9676. //
  9677. // Redistribution and use in source and binary forms, with or without
  9678. // modification, are permitted provided that the following conditions are
  9679. // met:
  9680. //
  9681. // * Redistributions of source code must retain the above copyright
  9682. // notice, this list of conditions and the following disclaimer.
  9683. // * Redistributions in binary form must reproduce the above
  9684. // copyright notice, this list of conditions and the following disclaimer
  9685. // in the documentation and/or other materials provided with the
  9686. // distribution.
  9687. // * Neither the name of Google Inc. nor the names of its
  9688. // contributors may be used to endorse or promote products derived from
  9689. // this software without specific prior written permission.
  9690. //
  9691. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  9692. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  9693. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  9694. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9695. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  9696. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9697. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  9698. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9699. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  9700. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  9701. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9702. //
  9703. // The Google C++ Testing and Mocking Framework (Google Test)
  9704. namespace testing {
  9705. using internal::GetUnitTestImpl;
  9706. // Gets the summary of the failure message by omitting the stack trace
  9707. // in it.
  9708. std::string TestPartResult::ExtractSummary(const char* message) {
  9709. const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
  9710. return stack_trace == NULL ? message :
  9711. std::string(message, stack_trace);
  9712. }
  9713. // Prints a TestPartResult object.
  9714. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
  9715. return os
  9716. << result.file_name() << ":" << result.line_number() << ": "
  9717. << (result.type() == TestPartResult::kSuccess ? "Success" :
  9718. result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
  9719. "Non-fatal failure") << ":\n"
  9720. << result.message() << std::endl;
  9721. }
  9722. // Appends a TestPartResult to the array.
  9723. void TestPartResultArray::Append(const TestPartResult& result) {
  9724. array_.push_back(result);
  9725. }
  9726. // Returns the TestPartResult at the given index (0-based).
  9727. const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
  9728. if (index < 0 || index >= size()) {
  9729. printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
  9730. internal::posix::Abort();
  9731. }
  9732. return array_[index];
  9733. }
  9734. // Returns the number of TestPartResult objects in the array.
  9735. int TestPartResultArray::size() const {
  9736. return static_cast<int>(array_.size());
  9737. }
  9738. namespace internal {
  9739. HasNewFatalFailureHelper::HasNewFatalFailureHelper()
  9740. : has_new_fatal_failure_(false),
  9741. original_reporter_(GetUnitTestImpl()->
  9742. GetTestPartResultReporterForCurrentThread()) {
  9743. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
  9744. }
  9745. HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
  9746. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
  9747. original_reporter_);
  9748. }
  9749. void HasNewFatalFailureHelper::ReportTestPartResult(
  9750. const TestPartResult& result) {
  9751. if (result.fatally_failed())
  9752. has_new_fatal_failure_ = true;
  9753. original_reporter_->ReportTestPartResult(result);
  9754. }
  9755. } // namespace internal
  9756. } // namespace testing
  9757. // Copyright 2008 Google Inc.
  9758. // All Rights Reserved.
  9759. //
  9760. // Redistribution and use in source and binary forms, with or without
  9761. // modification, are permitted provided that the following conditions are
  9762. // met:
  9763. //
  9764. // * Redistributions of source code must retain the above copyright
  9765. // notice, this list of conditions and the following disclaimer.
  9766. // * Redistributions in binary form must reproduce the above
  9767. // copyright notice, this list of conditions and the following disclaimer
  9768. // in the documentation and/or other materials provided with the
  9769. // distribution.
  9770. // * Neither the name of Google Inc. nor the names of its
  9771. // contributors may be used to endorse or promote products derived from
  9772. // this software without specific prior written permission.
  9773. //
  9774. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  9775. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  9776. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  9777. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9778. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  9779. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9780. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  9781. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9782. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  9783. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  9784. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9785. namespace testing {
  9786. namespace internal {
  9787. #if GTEST_HAS_TYPED_TEST_P
  9788. // Skips to the first non-space char in str. Returns an empty string if str
  9789. // contains only whitespace characters.
  9790. static const char* SkipSpaces(const char* str) {
  9791. while (IsSpace(*str))
  9792. str++;
  9793. return str;
  9794. }
  9795. static std::vector<std::string> SplitIntoTestNames(const char* src) {
  9796. std::vector<std::string> name_vec;
  9797. src = SkipSpaces(src);
  9798. for (; src != NULL; src = SkipComma(src)) {
  9799. name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
  9800. }
  9801. return name_vec;
  9802. }
  9803. // Verifies that registered_tests match the test names in
  9804. // registered_tests_; returns registered_tests if successful, or
  9805. // aborts the program otherwise.
  9806. const char* TypedTestCasePState::VerifyRegisteredTestNames(
  9807. const char* file, int line, const char* registered_tests) {
  9808. typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
  9809. registered_ = true;
  9810. std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
  9811. Message errors;
  9812. std::set<std::string> tests;
  9813. for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
  9814. name_it != name_vec.end(); ++name_it) {
  9815. const std::string& name = *name_it;
  9816. if (tests.count(name) != 0) {
  9817. errors << "Test " << name << " is listed more than once.\n";
  9818. continue;
  9819. }
  9820. bool found = false;
  9821. for (RegisteredTestIter it = registered_tests_.begin();
  9822. it != registered_tests_.end();
  9823. ++it) {
  9824. if (name == it->first) {
  9825. found = true;
  9826. break;
  9827. }
  9828. }
  9829. if (found) {
  9830. tests.insert(name);
  9831. } else {
  9832. errors << "No test named " << name
  9833. << " can be found in this test case.\n";
  9834. }
  9835. }
  9836. for (RegisteredTestIter it = registered_tests_.begin();
  9837. it != registered_tests_.end();
  9838. ++it) {
  9839. if (tests.count(it->first) == 0) {
  9840. errors << "You forgot to list test " << it->first << ".\n";
  9841. }
  9842. }
  9843. const std::string& errors_str = errors.GetString();
  9844. if (errors_str != "") {
  9845. fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
  9846. errors_str.c_str());
  9847. fflush(stderr);
  9848. posix::Abort();
  9849. }
  9850. return registered_tests;
  9851. }
  9852. #endif // GTEST_HAS_TYPED_TEST_P
  9853. } // namespace internal
  9854. } // namespace testing