gtest.cc 250 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795
  1. // Copyright 2005, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // The Google C++ Testing and Mocking Framework (Google Test)
  31. #include "gtest/gtest.h"
  32. #include <ctype.h>
  33. #include <stdarg.h>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <time.h>
  37. #include <wchar.h>
  38. #include <wctype.h>
  39. #include <algorithm>
  40. #include <chrono> // NOLINT
  41. #include <cmath>
  42. #include <cstdint>
  43. #include <initializer_list>
  44. #include <iomanip>
  45. #include <iterator>
  46. #include <limits>
  47. #include <list>
  48. #include <map>
  49. #include <ostream> // NOLINT
  50. #include <sstream>
  51. #include <unordered_set>
  52. #include <vector>
  53. #include "gtest/gtest-assertion-result.h"
  54. #include "gtest/gtest-spi.h"
  55. #include "gtest/internal/custom/gtest.h"
  56. #if GTEST_OS_LINUX
  57. #include <fcntl.h> // NOLINT
  58. #include <limits.h> // NOLINT
  59. #include <sched.h> // NOLINT
  60. // Declares vsnprintf(). This header is not available on Windows.
  61. #include <strings.h> // NOLINT
  62. #include <sys/mman.h> // NOLINT
  63. #include <sys/time.h> // NOLINT
  64. #include <unistd.h> // NOLINT
  65. #include <string>
  66. #elif GTEST_OS_ZOS
  67. #include <sys/time.h> // NOLINT
  68. // On z/OS we additionally need strings.h for strcasecmp.
  69. #include <strings.h> // NOLINT
  70. #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
  71. #include <windows.h> // NOLINT
  72. #undef min
  73. #elif GTEST_OS_WINDOWS // We are on Windows proper.
  74. #include <windows.h> // NOLINT
  75. #undef min
  76. #ifdef _MSC_VER
  77. #include <crtdbg.h> // NOLINT
  78. #endif
  79. #include <io.h> // NOLINT
  80. #include <sys/stat.h> // NOLINT
  81. #include <sys/timeb.h> // NOLINT
  82. #include <sys/types.h> // NOLINT
  83. #if GTEST_OS_WINDOWS_MINGW
  84. #include <sys/time.h> // NOLINT
  85. #endif // GTEST_OS_WINDOWS_MINGW
  86. #else
  87. // cpplint thinks that the header is already included, so we want to
  88. // silence it.
  89. #include <sys/time.h> // NOLINT
  90. #include <unistd.h> // NOLINT
  91. #endif // GTEST_OS_LINUX
  92. #if GTEST_HAS_EXCEPTIONS
  93. #include <stdexcept>
  94. #endif
  95. #if GTEST_CAN_STREAM_RESULTS_
  96. #include <arpa/inet.h> // NOLINT
  97. #include <netdb.h> // NOLINT
  98. #include <sys/socket.h> // NOLINT
  99. #include <sys/types.h> // NOLINT
  100. #endif
  101. #include "src/gtest-internal-inl.h"
  102. #if GTEST_OS_WINDOWS
  103. #define vsnprintf _vsnprintf
  104. #endif // GTEST_OS_WINDOWS
  105. #if GTEST_OS_MAC
  106. #ifndef GTEST_OS_IOS
  107. #include <crt_externs.h>
  108. #endif
  109. #endif
  110. #if GTEST_HAS_ABSL
  111. #include "absl/debugging/failure_signal_handler.h"
  112. #include "absl/debugging/stacktrace.h"
  113. #include "absl/debugging/symbolize.h"
  114. #include "absl/flags/parse.h"
  115. #include "absl/flags/usage.h"
  116. #include "absl/strings/str_cat.h"
  117. #include "absl/strings/str_replace.h"
  118. #endif // GTEST_HAS_ABSL
  119. namespace testing {
  120. using internal::CountIf;
  121. using internal::ForEach;
  122. using internal::GetElementOr;
  123. using internal::Shuffle;
  124. // Constants.
  125. // A test whose test suite name or test name matches this filter is
  126. // disabled and not run.
  127. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
  128. // A test suite whose name matches this filter is considered a death
  129. // test suite and will be run before test suites whose name doesn't
  130. // match this filter.
  131. static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
  132. // A test filter that matches everything.
  133. static const char kUniversalFilter[] = "*";
  134. // The default output format.
  135. static const char kDefaultOutputFormat[] = "xml";
  136. // The default output file.
  137. static const char kDefaultOutputFile[] = "test_detail";
  138. // The environment variable name for the test shard index.
  139. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
  140. // The environment variable name for the total number of test shards.
  141. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
  142. // The environment variable name for the test shard status file.
  143. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
  144. namespace internal {
  145. // The text used in failure messages to indicate the start of the
  146. // stack trace.
  147. const char kStackTraceMarker[] = "\nStack trace:\n";
  148. // g_help_flag is true if and only if the --help flag or an equivalent form
  149. // is specified on the command line.
  150. bool g_help_flag = false;
  151. // Utility function to Open File for Writing
  152. static FILE* OpenFileForWriting(const std::string& output_file) {
  153. FILE* fileout = nullptr;
  154. FilePath output_file_path(output_file);
  155. FilePath output_dir(output_file_path.RemoveFileName());
  156. if (output_dir.CreateDirectoriesRecursively()) {
  157. fileout = posix::FOpen(output_file.c_str(), "w");
  158. }
  159. if (fileout == nullptr) {
  160. GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
  161. }
  162. return fileout;
  163. }
  164. } // namespace internal
  165. // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
  166. // environment variable.
  167. static const char* GetDefaultFilter() {
  168. const char* const testbridge_test_only =
  169. internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
  170. if (testbridge_test_only != nullptr) {
  171. return testbridge_test_only;
  172. }
  173. return kUniversalFilter;
  174. }
  175. // Bazel passes in the argument to '--test_runner_fail_fast' via the
  176. // TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.
  177. static bool GetDefaultFailFast() {
  178. const char* const testbridge_test_runner_fail_fast =
  179. internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
  180. if (testbridge_test_runner_fail_fast != nullptr) {
  181. return strcmp(testbridge_test_runner_fail_fast, "1") == 0;
  182. }
  183. return false;
  184. }
  185. } // namespace testing
  186. GTEST_DEFINE_bool_(
  187. fail_fast,
  188. testing::internal::BoolFromGTestEnv("fail_fast",
  189. testing::GetDefaultFailFast()),
  190. "True if and only if a test failure should stop further test execution.");
  191. GTEST_DEFINE_bool_(
  192. also_run_disabled_tests,
  193. testing::internal::BoolFromGTestEnv("also_run_disabled_tests", false),
  194. "Run disabled tests too, in addition to the tests normally being run.");
  195. GTEST_DEFINE_bool_(
  196. break_on_failure,
  197. testing::internal::BoolFromGTestEnv("break_on_failure", false),
  198. "True if and only if a failed assertion should be a debugger "
  199. "break-point.");
  200. GTEST_DEFINE_bool_(catch_exceptions,
  201. testing::internal::BoolFromGTestEnv("catch_exceptions",
  202. true),
  203. "True if and only if " GTEST_NAME_
  204. " should catch exceptions and treat them as test failures.");
  205. GTEST_DEFINE_string_(
  206. color, testing::internal::StringFromGTestEnv("color", "auto"),
  207. "Whether to use colors in the output. Valid values: yes, no, "
  208. "and auto. 'auto' means to use colors if the output is "
  209. "being sent to a terminal and the TERM environment variable "
  210. "is set to a terminal type that supports colors.");
  211. GTEST_DEFINE_string_(
  212. filter,
  213. testing::internal::StringFromGTestEnv("filter",
  214. testing::GetDefaultFilter()),
  215. "A colon-separated list of glob (not regex) patterns "
  216. "for filtering the tests to run, optionally followed by a "
  217. "'-' and a : separated list of negative patterns (tests to "
  218. "exclude). A test is run if it matches one of the positive "
  219. "patterns and does not match any of the negative patterns.");
  220. GTEST_DEFINE_bool_(
  221. install_failure_signal_handler,
  222. testing::internal::BoolFromGTestEnv("install_failure_signal_handler",
  223. false),
  224. "If true and supported on the current platform, " GTEST_NAME_
  225. " should "
  226. "install a signal handler that dumps debugging information when fatal "
  227. "signals are raised.");
  228. GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them.");
  229. // The net priority order after flag processing is thus:
  230. // --gtest_output command line flag
  231. // GTEST_OUTPUT environment variable
  232. // XML_OUTPUT_FILE environment variable
  233. // ''
  234. GTEST_DEFINE_string_(
  235. output,
  236. testing::internal::StringFromGTestEnv(
  237. "output", testing::internal::OutputFlagAlsoCheckEnvVar().c_str()),
  238. "A format (defaults to \"xml\" but can be specified to be \"json\"), "
  239. "optionally followed by a colon and an output file name or directory. "
  240. "A directory is indicated by a trailing pathname separator. "
  241. "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
  242. "If a directory is specified, output files will be created "
  243. "within that directory, with file-names based on the test "
  244. "executable's name and, if necessary, made unique by adding "
  245. "digits.");
  246. GTEST_DEFINE_bool_(
  247. brief, testing::internal::BoolFromGTestEnv("brief", false),
  248. "True if only test failures should be displayed in text output.");
  249. GTEST_DEFINE_bool_(print_time,
  250. testing::internal::BoolFromGTestEnv("print_time", true),
  251. "True if and only if " GTEST_NAME_
  252. " should display elapsed time in text output.");
  253. GTEST_DEFINE_bool_(print_utf8,
  254. testing::internal::BoolFromGTestEnv("print_utf8", true),
  255. "True if and only if " GTEST_NAME_
  256. " prints UTF8 characters as text.");
  257. GTEST_DEFINE_int32_(
  258. random_seed, testing::internal::Int32FromGTestEnv("random_seed", 0),
  259. "Random number seed to use when shuffling test orders. Must be in range "
  260. "[1, 99999], or 0 to use a seed based on the current time.");
  261. GTEST_DEFINE_int32_(
  262. repeat, testing::internal::Int32FromGTestEnv("repeat", 1),
  263. "How many times to repeat each test. Specify a negative number "
  264. "for repeating forever. Useful for shaking out flaky tests.");
  265. GTEST_DEFINE_bool_(
  266. recreate_environments_when_repeating,
  267. testing::internal::BoolFromGTestEnv("recreate_environments_when_repeating",
  268. false),
  269. "Controls whether global test environments are recreated for each repeat "
  270. "of the tests. If set to false the global test environments are only set "
  271. "up once, for the first iteration, and only torn down once, for the last. "
  272. "Useful for shaking out flaky tests with stable, expensive test "
  273. "environments. If --gtest_repeat is set to a negative number, meaning "
  274. "there is no last run, the environments will always be recreated to avoid "
  275. "leaks.");
  276. GTEST_DEFINE_bool_(show_internal_stack_frames, false,
  277. "True if and only if " GTEST_NAME_
  278. " should include internal stack frames when "
  279. "printing test failure stack traces.");
  280. GTEST_DEFINE_bool_(shuffle,
  281. testing::internal::BoolFromGTestEnv("shuffle", false),
  282. "True if and only if " GTEST_NAME_
  283. " should randomize tests' order on every run.");
  284. GTEST_DEFINE_int32_(
  285. stack_trace_depth,
  286. testing::internal::Int32FromGTestEnv("stack_trace_depth",
  287. testing::kMaxStackTraceDepth),
  288. "The maximum number of stack frames to print when an "
  289. "assertion fails. The valid range is 0 through 100, inclusive.");
  290. GTEST_DEFINE_string_(
  291. stream_result_to,
  292. testing::internal::StringFromGTestEnv("stream_result_to", ""),
  293. "This flag specifies the host name and the port number on which to stream "
  294. "test results. Example: \"localhost:555\". The flag is effective only on "
  295. "Linux.");
  296. GTEST_DEFINE_bool_(
  297. throw_on_failure,
  298. testing::internal::BoolFromGTestEnv("throw_on_failure", false),
  299. "When this flag is specified, a failed assertion will throw an exception "
  300. "if exceptions are enabled or exit the program with a non-zero code "
  301. "otherwise. For use with an external test framework.");
  302. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  303. GTEST_DEFINE_string_(
  304. flagfile, testing::internal::StringFromGTestEnv("flagfile", ""),
  305. "This flag specifies the flagfile to read command-line flags from.");
  306. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  307. namespace testing {
  308. namespace internal {
  309. // Generates a random number from [0, range), using a Linear
  310. // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
  311. // than kMaxRange.
  312. uint32_t Random::Generate(uint32_t range) {
  313. // These constants are the same as are used in glibc's rand(3).
  314. // Use wider types than necessary to prevent unsigned overflow diagnostics.
  315. state_ = static_cast<uint32_t>(1103515245ULL * state_ + 12345U) % kMaxRange;
  316. GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0).";
  317. GTEST_CHECK_(range <= kMaxRange)
  318. << "Generation of a number in [0, " << range << ") was requested, "
  319. << "but this can only generate numbers in [0, " << kMaxRange << ").";
  320. // Converting via modulus introduces a bit of downward bias, but
  321. // it's simple, and a linear congruential generator isn't too good
  322. // to begin with.
  323. return state_ % range;
  324. }
  325. // GTestIsInitialized() returns true if and only if the user has initialized
  326. // Google Test. Useful for catching the user mistake of not initializing
  327. // Google Test before calling RUN_ALL_TESTS().
  328. static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
  329. // Iterates over a vector of TestSuites, keeping a running sum of the
  330. // results of calling a given int-returning method on each.
  331. // Returns the sum.
  332. static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
  333. int (TestSuite::*method)() const) {
  334. int sum = 0;
  335. for (size_t i = 0; i < case_list.size(); i++) {
  336. sum += (case_list[i]->*method)();
  337. }
  338. return sum;
  339. }
  340. // Returns true if and only if the test suite passed.
  341. static bool TestSuitePassed(const TestSuite* test_suite) {
  342. return test_suite->should_run() && test_suite->Passed();
  343. }
  344. // Returns true if and only if the test suite failed.
  345. static bool TestSuiteFailed(const TestSuite* test_suite) {
  346. return test_suite->should_run() && test_suite->Failed();
  347. }
  348. // Returns true if and only if test_suite contains at least one test that
  349. // should run.
  350. static bool ShouldRunTestSuite(const TestSuite* test_suite) {
  351. return test_suite->should_run();
  352. }
  353. // AssertHelper constructor.
  354. AssertHelper::AssertHelper(TestPartResult::Type type, const char* file,
  355. int line, const char* message)
  356. : data_(new AssertHelperData(type, file, line, message)) {}
  357. AssertHelper::~AssertHelper() { delete data_; }
  358. // Message assignment, for assertion streaming support.
  359. void AssertHelper::operator=(const Message& message) const {
  360. UnitTest::GetInstance()->AddTestPartResult(
  361. data_->type, data_->file, data_->line,
  362. AppendUserMessage(data_->message, message),
  363. UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)
  364. // Skips the stack frame for this function itself.
  365. ); // NOLINT
  366. }
  367. namespace {
  368. // When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P
  369. // to creates test cases for it, a synthetic test case is
  370. // inserted to report ether an error or a log message.
  371. //
  372. // This configuration bit will likely be removed at some point.
  373. constexpr bool kErrorOnUninstantiatedParameterizedTest = true;
  374. constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true;
  375. // A test that fails at a given file/line location with a given message.
  376. class FailureTest : public Test {
  377. public:
  378. explicit FailureTest(const CodeLocation& loc, std::string error_message,
  379. bool as_error)
  380. : loc_(loc),
  381. error_message_(std::move(error_message)),
  382. as_error_(as_error) {}
  383. void TestBody() override {
  384. if (as_error_) {
  385. AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),
  386. loc_.line, "") = Message() << error_message_;
  387. } else {
  388. std::cout << error_message_ << std::endl;
  389. }
  390. }
  391. private:
  392. const CodeLocation loc_;
  393. const std::string error_message_;
  394. const bool as_error_;
  395. };
  396. } // namespace
  397. std::set<std::string>* GetIgnoredParameterizedTestSuites() {
  398. return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
  399. }
  400. // Add a given test_suit to the list of them allow to go un-instantiated.
  401. MarkAsIgnored::MarkAsIgnored(const char* test_suite) {
  402. GetIgnoredParameterizedTestSuites()->insert(test_suite);
  403. }
  404. // If this parameterized test suite has no instantiations (and that
  405. // has not been marked as okay), emit a test case reporting that.
  406. void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
  407. bool has_test_p) {
  408. const auto& ignored = *GetIgnoredParameterizedTestSuites();
  409. if (ignored.find(name) != ignored.end()) return;
  410. const char kMissingInstantiation[] = //
  411. " is defined via TEST_P, but never instantiated. None of the test cases "
  412. "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
  413. "ones provided expand to nothing."
  414. "\n\n"
  415. "Ideally, TEST_P definitions should only ever be included as part of "
  416. "binaries that intend to use them. (As opposed to, for example, being "
  417. "placed in a library that may be linked in to get other utilities.)";
  418. const char kMissingTestCase[] = //
  419. " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
  420. "defined via TEST_P . No test cases will run."
  421. "\n\n"
  422. "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
  423. "code that always depend on code that provides TEST_P. Failing to do "
  424. "so is often an indication of dead code, e.g. the last TEST_P was "
  425. "removed but the rest got left behind.";
  426. std::string message =
  427. "Parameterized test suite " + name +
  428. (has_test_p ? kMissingInstantiation : kMissingTestCase) +
  429. "\n\n"
  430. "To suppress this error for this test suite, insert the following line "
  431. "(in a non-header) in the namespace it is defined in:"
  432. "\n\n"
  433. "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
  434. name + ");";
  435. std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
  436. RegisterTest( //
  437. "GoogleTestVerification", full_name.c_str(),
  438. nullptr, // No type parameter.
  439. nullptr, // No value parameter.
  440. location.file.c_str(), location.line, [message, location] {
  441. return new FailureTest(location, message,
  442. kErrorOnUninstantiatedParameterizedTest);
  443. });
  444. }
  445. void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
  446. CodeLocation code_location) {
  447. GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(
  448. test_suite_name, code_location);
  449. }
  450. void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) {
  451. GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation(
  452. case_name);
  453. }
  454. void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
  455. const char* test_suite_name, CodeLocation code_location) {
  456. suites_.emplace(std::string(test_suite_name),
  457. TypeParameterizedTestSuiteInfo(code_location));
  458. }
  459. void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
  460. const char* test_suite_name) {
  461. auto it = suites_.find(std::string(test_suite_name));
  462. if (it != suites_.end()) {
  463. it->second.instantiated = true;
  464. } else {
  465. GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '"
  466. << test_suite_name << "'";
  467. }
  468. }
  469. void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
  470. const auto& ignored = *GetIgnoredParameterizedTestSuites();
  471. for (const auto& testcase : suites_) {
  472. if (testcase.second.instantiated) continue;
  473. if (ignored.find(testcase.first) != ignored.end()) continue;
  474. std::string message =
  475. "Type parameterized test suite " + testcase.first +
  476. " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
  477. "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
  478. "\n\n"
  479. "Ideally, TYPED_TEST_P definitions should only ever be included as "
  480. "part of binaries that intend to use them. (As opposed to, for "
  481. "example, being placed in a library that may be linked in to get other "
  482. "utilities.)"
  483. "\n\n"
  484. "To suppress this error for this test suite, insert the following line "
  485. "(in a non-header) in the namespace it is defined in:"
  486. "\n\n"
  487. "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
  488. testcase.first + ");";
  489. std::string full_name =
  490. "UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">";
  491. RegisterTest( //
  492. "GoogleTestVerification", full_name.c_str(),
  493. nullptr, // No type parameter.
  494. nullptr, // No value parameter.
  495. testcase.second.code_location.file.c_str(),
  496. testcase.second.code_location.line, [message, testcase] {
  497. return new FailureTest(testcase.second.code_location, message,
  498. kErrorOnUninstantiatedTypeParameterizedTest);
  499. });
  500. }
  501. }
  502. // A copy of all command line arguments. Set by InitGoogleTest().
  503. static ::std::vector<std::string> g_argvs;
  504. ::std::vector<std::string> GetArgvs() {
  505. #if defined(GTEST_CUSTOM_GET_ARGVS_)
  506. // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
  507. // ::string. This code converts it to the appropriate type.
  508. const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
  509. return ::std::vector<std::string>(custom.begin(), custom.end());
  510. #else // defined(GTEST_CUSTOM_GET_ARGVS_)
  511. return g_argvs;
  512. #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
  513. }
  514. // Returns the current application's name, removing directory path if that
  515. // is present.
  516. FilePath GetCurrentExecutableName() {
  517. FilePath result;
  518. #if GTEST_OS_WINDOWS || GTEST_OS_OS2
  519. result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
  520. #else
  521. result.Set(FilePath(GetArgvs()[0]));
  522. #endif // GTEST_OS_WINDOWS
  523. return result.RemoveDirectoryName();
  524. }
  525. // Functions for processing the gtest_output flag.
  526. // Returns the output format, or "" for normal printed output.
  527. std::string UnitTestOptions::GetOutputFormat() {
  528. std::string s = GTEST_FLAG_GET(output);
  529. const char* const gtest_output_flag = s.c_str();
  530. const char* const colon = strchr(gtest_output_flag, ':');
  531. return (colon == nullptr)
  532. ? std::string(gtest_output_flag)
  533. : std::string(gtest_output_flag,
  534. static_cast<size_t>(colon - gtest_output_flag));
  535. }
  536. // Returns the name of the requested output file, or the default if none
  537. // was explicitly specified.
  538. std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
  539. std::string s = GTEST_FLAG_GET(output);
  540. const char* const gtest_output_flag = s.c_str();
  541. std::string format = GetOutputFormat();
  542. if (format.empty()) format = std::string(kDefaultOutputFormat);
  543. const char* const colon = strchr(gtest_output_flag, ':');
  544. if (colon == nullptr)
  545. return internal::FilePath::MakeFileName(
  546. internal::FilePath(
  547. UnitTest::GetInstance()->original_working_dir()),
  548. internal::FilePath(kDefaultOutputFile), 0, format.c_str())
  549. .string();
  550. internal::FilePath output_name(colon + 1);
  551. if (!output_name.IsAbsolutePath())
  552. output_name = internal::FilePath::ConcatPaths(
  553. internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
  554. internal::FilePath(colon + 1));
  555. if (!output_name.IsDirectory()) return output_name.string();
  556. internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
  557. output_name, internal::GetCurrentExecutableName(),
  558. GetOutputFormat().c_str()));
  559. return result.string();
  560. }
  561. // Returns true if and only if the wildcard pattern matches the string. Each
  562. // pattern consists of regular characters, single-character wildcards (?), and
  563. // multi-character wildcards (*).
  564. //
  565. // This function implements a linear-time string globbing algorithm based on
  566. // https://research.swtch.com/glob.
  567. static bool PatternMatchesString(const std::string& name_str,
  568. const char* pattern, const char* pattern_end) {
  569. const char* name = name_str.c_str();
  570. const char* const name_begin = name;
  571. const char* const name_end = name + name_str.size();
  572. const char* pattern_next = pattern;
  573. const char* name_next = name;
  574. while (pattern < pattern_end || name < name_end) {
  575. if (pattern < pattern_end) {
  576. switch (*pattern) {
  577. default: // Match an ordinary character.
  578. if (name < name_end && *name == *pattern) {
  579. ++pattern;
  580. ++name;
  581. continue;
  582. }
  583. break;
  584. case '?': // Match any single character.
  585. if (name < name_end) {
  586. ++pattern;
  587. ++name;
  588. continue;
  589. }
  590. break;
  591. case '*':
  592. // Match zero or more characters. Start by skipping over the wildcard
  593. // and matching zero characters from name. If that fails, restart and
  594. // match one more character than the last attempt.
  595. pattern_next = pattern;
  596. name_next = name + 1;
  597. ++pattern;
  598. continue;
  599. }
  600. }
  601. // Failed to match a character. Restart if possible.
  602. if (name_begin < name_next && name_next <= name_end) {
  603. pattern = pattern_next;
  604. name = name_next;
  605. continue;
  606. }
  607. return false;
  608. }
  609. return true;
  610. }
  611. namespace {
  612. bool IsGlobPattern(const std::string& pattern) {
  613. return std::any_of(pattern.begin(), pattern.end(),
  614. [](const char c) { return c == '?' || c == '*'; });
  615. }
  616. class UnitTestFilter {
  617. public:
  618. UnitTestFilter() = default;
  619. // Constructs a filter from a string of patterns separated by `:`.
  620. explicit UnitTestFilter(const std::string& filter) {
  621. // By design "" filter matches "" string.
  622. std::vector<std::string> all_patterns;
  623. SplitString(filter, ':', &all_patterns);
  624. const auto exact_match_patterns_begin = std::partition(
  625. all_patterns.begin(), all_patterns.end(), &IsGlobPattern);
  626. glob_patterns_.reserve(static_cast<size_t>(
  627. std::distance(all_patterns.begin(), exact_match_patterns_begin)));
  628. std::move(all_patterns.begin(), exact_match_patterns_begin,
  629. std::inserter(glob_patterns_, glob_patterns_.begin()));
  630. std::move(
  631. exact_match_patterns_begin, all_patterns.end(),
  632. std::inserter(exact_match_patterns_, exact_match_patterns_.begin()));
  633. }
  634. // Returns true if and only if name matches at least one of the patterns in
  635. // the filter.
  636. bool MatchesName(const std::string& name) const {
  637. return exact_match_patterns_.count(name) > 0 ||
  638. std::any_of(glob_patterns_.begin(), glob_patterns_.end(),
  639. [&name](const std::string& pattern) {
  640. return PatternMatchesString(
  641. name, pattern.c_str(),
  642. pattern.c_str() + pattern.size());
  643. });
  644. }
  645. private:
  646. std::vector<std::string> glob_patterns_;
  647. std::unordered_set<std::string> exact_match_patterns_;
  648. };
  649. class PositiveAndNegativeUnitTestFilter {
  650. public:
  651. // Constructs a positive and a negative filter from a string. The string
  652. // contains a positive filter optionally followed by a '-' character and a
  653. // negative filter. In case only a negative filter is provided the positive
  654. // filter will be assumed "*".
  655. // A filter is a list of patterns separated by ':'.
  656. explicit PositiveAndNegativeUnitTestFilter(const std::string& filter) {
  657. std::vector<std::string> positive_and_negative_filters;
  658. // NOTE: `SplitString` always returns a non-empty container.
  659. SplitString(filter, '-', &positive_and_negative_filters);
  660. const auto& positive_filter = positive_and_negative_filters.front();
  661. if (positive_and_negative_filters.size() > 1) {
  662. positive_filter_ = UnitTestFilter(
  663. positive_filter.empty() ? kUniversalFilter : positive_filter);
  664. // TODO(b/214626361): Fail on multiple '-' characters
  665. // For the moment to preserve old behavior we concatenate the rest of the
  666. // string parts with `-` as separator to generate the negative filter.
  667. auto negative_filter_string = positive_and_negative_filters[1];
  668. for (std::size_t i = 2; i < positive_and_negative_filters.size(); i++)
  669. negative_filter_string =
  670. negative_filter_string + '-' + positive_and_negative_filters[i];
  671. negative_filter_ = UnitTestFilter(negative_filter_string);
  672. } else {
  673. // In case we don't have a negative filter and positive filter is ""
  674. // we do not use kUniversalFilter by design as opposed to when we have a
  675. // negative filter.
  676. positive_filter_ = UnitTestFilter(positive_filter);
  677. }
  678. }
  679. // Returns true if and only if test name (this is generated by appending test
  680. // suit name and test name via a '.' character) matches the positive filter
  681. // and does not match the negative filter.
  682. bool MatchesTest(const std::string& test_suite_name,
  683. const std::string& test_name) const {
  684. return MatchesName(test_suite_name + "." + test_name);
  685. }
  686. // Returns true if and only if name matches the positive filter and does not
  687. // match the negative filter.
  688. bool MatchesName(const std::string& name) const {
  689. return positive_filter_.MatchesName(name) &&
  690. !negative_filter_.MatchesName(name);
  691. }
  692. private:
  693. UnitTestFilter positive_filter_;
  694. UnitTestFilter negative_filter_;
  695. };
  696. } // namespace
  697. bool UnitTestOptions::MatchesFilter(const std::string& name_str,
  698. const char* filter) {
  699. return UnitTestFilter(filter).MatchesName(name_str);
  700. }
  701. // Returns true if and only if the user-specified filter matches the test
  702. // suite name and the test name.
  703. bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
  704. const std::string& test_name) {
  705. // Split --gtest_filter at '-', if there is one, to separate into
  706. // positive filter and negative filter portions
  707. return PositiveAndNegativeUnitTestFilter(GTEST_FLAG_GET(filter))
  708. .MatchesTest(test_suite_name, test_name);
  709. }
  710. #if GTEST_HAS_SEH
  711. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  712. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  713. // This function is useful as an __except condition.
  714. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
  715. // Google Test should handle a SEH exception if:
  716. // 1. the user wants it to, AND
  717. // 2. this is not a breakpoint exception, AND
  718. // 3. this is not a C++ exception (VC++ implements them via SEH,
  719. // apparently).
  720. //
  721. // SEH exception code for C++ exceptions.
  722. // (see http://support.microsoft.com/kb/185294 for more information).
  723. const DWORD kCxxExceptionCode = 0xe06d7363;
  724. bool should_handle = true;
  725. if (!GTEST_FLAG_GET(catch_exceptions))
  726. should_handle = false;
  727. else if (exception_code == EXCEPTION_BREAKPOINT)
  728. should_handle = false;
  729. else if (exception_code == kCxxExceptionCode)
  730. should_handle = false;
  731. return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
  732. }
  733. #endif // GTEST_HAS_SEH
  734. } // namespace internal
  735. // The c'tor sets this object as the test part result reporter used by
  736. // Google Test. The 'result' parameter specifies where to report the
  737. // results. Intercepts only failures from the current thread.
  738. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  739. TestPartResultArray* result)
  740. : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
  741. Init();
  742. }
  743. // The c'tor sets this object as the test part result reporter used by
  744. // Google Test. The 'result' parameter specifies where to report the
  745. // results.
  746. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  747. InterceptMode intercept_mode, TestPartResultArray* result)
  748. : intercept_mode_(intercept_mode), result_(result) {
  749. Init();
  750. }
  751. void ScopedFakeTestPartResultReporter::Init() {
  752. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  753. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  754. old_reporter_ = impl->GetGlobalTestPartResultReporter();
  755. impl->SetGlobalTestPartResultReporter(this);
  756. } else {
  757. old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
  758. impl->SetTestPartResultReporterForCurrentThread(this);
  759. }
  760. }
  761. // The d'tor restores the test part result reporter used by Google Test
  762. // before.
  763. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
  764. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  765. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  766. impl->SetGlobalTestPartResultReporter(old_reporter_);
  767. } else {
  768. impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
  769. }
  770. }
  771. // Increments the test part result count and remembers the result.
  772. // This method is from the TestPartResultReporterInterface interface.
  773. void ScopedFakeTestPartResultReporter::ReportTestPartResult(
  774. const TestPartResult& result) {
  775. result_->Append(result);
  776. }
  777. namespace internal {
  778. // Returns the type ID of ::testing::Test. We should always call this
  779. // instead of GetTypeId< ::testing::Test>() to get the type ID of
  780. // testing::Test. This is to work around a suspected linker bug when
  781. // using Google Test as a framework on Mac OS X. The bug causes
  782. // GetTypeId< ::testing::Test>() to return different values depending
  783. // on whether the call is from the Google Test framework itself or
  784. // from user test code. GetTestTypeId() is guaranteed to always
  785. // return the same value, as it always calls GetTypeId<>() from the
  786. // gtest.cc, which is within the Google Test framework.
  787. TypeId GetTestTypeId() { return GetTypeId<Test>(); }
  788. // The value of GetTestTypeId() as seen from within the Google Test
  789. // library. This is solely for testing GetTestTypeId().
  790. extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
  791. // This predicate-formatter checks that 'results' contains a test part
  792. // failure of the given type and that the failure message contains the
  793. // given substring.
  794. static AssertionResult HasOneFailure(const char* /* results_expr */,
  795. const char* /* type_expr */,
  796. const char* /* substr_expr */,
  797. const TestPartResultArray& results,
  798. TestPartResult::Type type,
  799. const std::string& substr) {
  800. const std::string expected(type == TestPartResult::kFatalFailure
  801. ? "1 fatal failure"
  802. : "1 non-fatal failure");
  803. Message msg;
  804. if (results.size() != 1) {
  805. msg << "Expected: " << expected << "\n"
  806. << " Actual: " << results.size() << " failures";
  807. for (int i = 0; i < results.size(); i++) {
  808. msg << "\n" << results.GetTestPartResult(i);
  809. }
  810. return AssertionFailure() << msg;
  811. }
  812. const TestPartResult& r = results.GetTestPartResult(0);
  813. if (r.type() != type) {
  814. return AssertionFailure() << "Expected: " << expected << "\n"
  815. << " Actual:\n"
  816. << r;
  817. }
  818. if (strstr(r.message(), substr.c_str()) == nullptr) {
  819. return AssertionFailure()
  820. << "Expected: " << expected << " containing \"" << substr << "\"\n"
  821. << " Actual:\n"
  822. << r;
  823. }
  824. return AssertionSuccess();
  825. }
  826. // The constructor of SingleFailureChecker remembers where to look up
  827. // test part results, what type of failure we expect, and what
  828. // substring the failure message should contain.
  829. SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
  830. TestPartResult::Type type,
  831. const std::string& substr)
  832. : results_(results), type_(type), substr_(substr) {}
  833. // The destructor of SingleFailureChecker verifies that the given
  834. // TestPartResultArray contains exactly one failure that has the given
  835. // type and contains the given substring. If that's not the case, a
  836. // non-fatal failure will be generated.
  837. SingleFailureChecker::~SingleFailureChecker() {
  838. EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
  839. }
  840. DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
  841. UnitTestImpl* unit_test)
  842. : unit_test_(unit_test) {}
  843. void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
  844. const TestPartResult& result) {
  845. unit_test_->current_test_result()->AddTestPartResult(result);
  846. unit_test_->listeners()->repeater()->OnTestPartResult(result);
  847. }
  848. DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
  849. UnitTestImpl* unit_test)
  850. : unit_test_(unit_test) {}
  851. void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
  852. const TestPartResult& result) {
  853. unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
  854. }
  855. // Returns the global test part result reporter.
  856. TestPartResultReporterInterface*
  857. UnitTestImpl::GetGlobalTestPartResultReporter() {
  858. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  859. return global_test_part_result_repoter_;
  860. }
  861. // Sets the global test part result reporter.
  862. void UnitTestImpl::SetGlobalTestPartResultReporter(
  863. TestPartResultReporterInterface* reporter) {
  864. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  865. global_test_part_result_repoter_ = reporter;
  866. }
  867. // Returns the test part result reporter for the current thread.
  868. TestPartResultReporterInterface*
  869. UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
  870. return per_thread_test_part_result_reporter_.get();
  871. }
  872. // Sets the test part result reporter for the current thread.
  873. void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
  874. TestPartResultReporterInterface* reporter) {
  875. per_thread_test_part_result_reporter_.set(reporter);
  876. }
  877. // Gets the number of successful test suites.
  878. int UnitTestImpl::successful_test_suite_count() const {
  879. return CountIf(test_suites_, TestSuitePassed);
  880. }
  881. // Gets the number of failed test suites.
  882. int UnitTestImpl::failed_test_suite_count() const {
  883. return CountIf(test_suites_, TestSuiteFailed);
  884. }
  885. // Gets the number of all test suites.
  886. int UnitTestImpl::total_test_suite_count() const {
  887. return static_cast<int>(test_suites_.size());
  888. }
  889. // Gets the number of all test suites that contain at least one test
  890. // that should run.
  891. int UnitTestImpl::test_suite_to_run_count() const {
  892. return CountIf(test_suites_, ShouldRunTestSuite);
  893. }
  894. // Gets the number of successful tests.
  895. int UnitTestImpl::successful_test_count() const {
  896. return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
  897. }
  898. // Gets the number of skipped tests.
  899. int UnitTestImpl::skipped_test_count() const {
  900. return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
  901. }
  902. // Gets the number of failed tests.
  903. int UnitTestImpl::failed_test_count() const {
  904. return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
  905. }
  906. // Gets the number of disabled tests that will be reported in the XML report.
  907. int UnitTestImpl::reportable_disabled_test_count() const {
  908. return SumOverTestSuiteList(test_suites_,
  909. &TestSuite::reportable_disabled_test_count);
  910. }
  911. // Gets the number of disabled tests.
  912. int UnitTestImpl::disabled_test_count() const {
  913. return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
  914. }
  915. // Gets the number of tests to be printed in the XML report.
  916. int UnitTestImpl::reportable_test_count() const {
  917. return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
  918. }
  919. // Gets the number of all tests.
  920. int UnitTestImpl::total_test_count() const {
  921. return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
  922. }
  923. // Gets the number of tests that should run.
  924. int UnitTestImpl::test_to_run_count() const {
  925. return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
  926. }
  927. // Returns the current OS stack trace as an std::string.
  928. //
  929. // The maximum number of stack frames to be included is specified by
  930. // the gtest_stack_trace_depth flag. The skip_count parameter
  931. // specifies the number of top frames to be skipped, which doesn't
  932. // count against the number of frames to be included.
  933. //
  934. // For example, if Foo() calls Bar(), which in turn calls
  935. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  936. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  937. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
  938. return os_stack_trace_getter()->CurrentStackTrace(
  939. static_cast<int>(GTEST_FLAG_GET(stack_trace_depth)), skip_count + 1
  940. // Skips the user-specified number of frames plus this function
  941. // itself.
  942. ); // NOLINT
  943. }
  944. // A helper class for measuring elapsed times.
  945. class Timer {
  946. public:
  947. Timer() : start_(std::chrono::steady_clock::now()) {}
  948. // Return time elapsed in milliseconds since the timer was created.
  949. TimeInMillis Elapsed() {
  950. return std::chrono::duration_cast<std::chrono::milliseconds>(
  951. std::chrono::steady_clock::now() - start_)
  952. .count();
  953. }
  954. private:
  955. std::chrono::steady_clock::time_point start_;
  956. };
  957. // Returns a timestamp as milliseconds since the epoch. Note this time may jump
  958. // around subject to adjustments by the system, to measure elapsed time use
  959. // Timer instead.
  960. TimeInMillis GetTimeInMillis() {
  961. return std::chrono::duration_cast<std::chrono::milliseconds>(
  962. std::chrono::system_clock::now() -
  963. std::chrono::system_clock::from_time_t(0))
  964. .count();
  965. }
  966. // Utilities
  967. // class String.
  968. #if GTEST_OS_WINDOWS_MOBILE
  969. // Creates a UTF-16 wide string from the given ANSI string, allocating
  970. // memory using new. The caller is responsible for deleting the return
  971. // value using delete[]. Returns the wide string, or NULL if the
  972. // input is NULL.
  973. LPCWSTR String::AnsiToUtf16(const char* ansi) {
  974. if (!ansi) return nullptr;
  975. const int length = strlen(ansi);
  976. const int unicode_length =
  977. MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
  978. WCHAR* unicode = new WCHAR[unicode_length + 1];
  979. MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);
  980. unicode[unicode_length] = 0;
  981. return unicode;
  982. }
  983. // Creates an ANSI string from the given wide string, allocating
  984. // memory using new. The caller is responsible for deleting the return
  985. // value using delete[]. Returns the ANSI string, or NULL if the
  986. // input is NULL.
  987. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
  988. if (!utf16_str) return nullptr;
  989. const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
  990. 0, nullptr, nullptr);
  991. char* ansi = new char[ansi_length + 1];
  992. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
  993. nullptr);
  994. ansi[ansi_length] = 0;
  995. return ansi;
  996. }
  997. #endif // GTEST_OS_WINDOWS_MOBILE
  998. // Compares two C strings. Returns true if and only if they have the same
  999. // content.
  1000. //
  1001. // Unlike strcmp(), this function can handle NULL argument(s). A NULL
  1002. // C string is considered different to any non-NULL C string,
  1003. // including the empty string.
  1004. bool String::CStringEquals(const char* lhs, const char* rhs) {
  1005. if (lhs == nullptr) return rhs == nullptr;
  1006. if (rhs == nullptr) return false;
  1007. return strcmp(lhs, rhs) == 0;
  1008. }
  1009. #if GTEST_HAS_STD_WSTRING
  1010. // Converts an array of wide chars to a narrow string using the UTF-8
  1011. // encoding, and streams the result to the given Message object.
  1012. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
  1013. Message* msg) {
  1014. for (size_t i = 0; i != length;) { // NOLINT
  1015. if (wstr[i] != L'\0') {
  1016. *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
  1017. while (i != length && wstr[i] != L'\0') i++;
  1018. } else {
  1019. *msg << '\0';
  1020. i++;
  1021. }
  1022. }
  1023. }
  1024. #endif // GTEST_HAS_STD_WSTRING
  1025. void SplitString(const ::std::string& str, char delimiter,
  1026. ::std::vector< ::std::string>* dest) {
  1027. ::std::vector< ::std::string> parsed;
  1028. ::std::string::size_type pos = 0;
  1029. while (::testing::internal::AlwaysTrue()) {
  1030. const ::std::string::size_type colon = str.find(delimiter, pos);
  1031. if (colon == ::std::string::npos) {
  1032. parsed.push_back(str.substr(pos));
  1033. break;
  1034. } else {
  1035. parsed.push_back(str.substr(pos, colon - pos));
  1036. pos = colon + 1;
  1037. }
  1038. }
  1039. dest->swap(parsed);
  1040. }
  1041. } // namespace internal
  1042. // Constructs an empty Message.
  1043. // We allocate the stringstream separately because otherwise each use of
  1044. // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
  1045. // stack frame leading to huge stack frames in some cases; gcc does not reuse
  1046. // the stack space.
  1047. Message::Message() : ss_(new ::std::stringstream) {
  1048. // By default, we want there to be enough precision when printing
  1049. // a double to a Message.
  1050. *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
  1051. }
  1052. // These two overloads allow streaming a wide C string to a Message
  1053. // using the UTF-8 encoding.
  1054. Message& Message::operator<<(const wchar_t* wide_c_str) {
  1055. return *this << internal::String::ShowWideCString(wide_c_str);
  1056. }
  1057. Message& Message::operator<<(wchar_t* wide_c_str) {
  1058. return *this << internal::String::ShowWideCString(wide_c_str);
  1059. }
  1060. #if GTEST_HAS_STD_WSTRING
  1061. // Converts the given wide string to a narrow string using the UTF-8
  1062. // encoding, and streams the result to this Message object.
  1063. Message& Message::operator<<(const ::std::wstring& wstr) {
  1064. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  1065. return *this;
  1066. }
  1067. #endif // GTEST_HAS_STD_WSTRING
  1068. // Gets the text streamed to this object so far as an std::string.
  1069. // Each '\0' character in the buffer is replaced with "\\0".
  1070. std::string Message::GetString() const {
  1071. return internal::StringStreamToString(ss_.get());
  1072. }
  1073. namespace internal {
  1074. namespace edit_distance {
  1075. std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
  1076. const std::vector<size_t>& right) {
  1077. std::vector<std::vector<double> > costs(
  1078. left.size() + 1, std::vector<double>(right.size() + 1));
  1079. std::vector<std::vector<EditType> > best_move(
  1080. left.size() + 1, std::vector<EditType>(right.size() + 1));
  1081. // Populate for empty right.
  1082. for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
  1083. costs[l_i][0] = static_cast<double>(l_i);
  1084. best_move[l_i][0] = kRemove;
  1085. }
  1086. // Populate for empty left.
  1087. for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
  1088. costs[0][r_i] = static_cast<double>(r_i);
  1089. best_move[0][r_i] = kAdd;
  1090. }
  1091. for (size_t l_i = 0; l_i < left.size(); ++l_i) {
  1092. for (size_t r_i = 0; r_i < right.size(); ++r_i) {
  1093. if (left[l_i] == right[r_i]) {
  1094. // Found a match. Consume it.
  1095. costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
  1096. best_move[l_i + 1][r_i + 1] = kMatch;
  1097. continue;
  1098. }
  1099. const double add = costs[l_i + 1][r_i];
  1100. const double remove = costs[l_i][r_i + 1];
  1101. const double replace = costs[l_i][r_i];
  1102. if (add < remove && add < replace) {
  1103. costs[l_i + 1][r_i + 1] = add + 1;
  1104. best_move[l_i + 1][r_i + 1] = kAdd;
  1105. } else if (remove < add && remove < replace) {
  1106. costs[l_i + 1][r_i + 1] = remove + 1;
  1107. best_move[l_i + 1][r_i + 1] = kRemove;
  1108. } else {
  1109. // We make replace a little more expensive than add/remove to lower
  1110. // their priority.
  1111. costs[l_i + 1][r_i + 1] = replace + 1.00001;
  1112. best_move[l_i + 1][r_i + 1] = kReplace;
  1113. }
  1114. }
  1115. }
  1116. // Reconstruct the best path. We do it in reverse order.
  1117. std::vector<EditType> best_path;
  1118. for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
  1119. EditType move = best_move[l_i][r_i];
  1120. best_path.push_back(move);
  1121. l_i -= move != kAdd;
  1122. r_i -= move != kRemove;
  1123. }
  1124. std::reverse(best_path.begin(), best_path.end());
  1125. return best_path;
  1126. }
  1127. namespace {
  1128. // Helper class to convert string into ids with deduplication.
  1129. class InternalStrings {
  1130. public:
  1131. size_t GetId(const std::string& str) {
  1132. IdMap::iterator it = ids_.find(str);
  1133. if (it != ids_.end()) return it->second;
  1134. size_t id = ids_.size();
  1135. return ids_[str] = id;
  1136. }
  1137. private:
  1138. typedef std::map<std::string, size_t> IdMap;
  1139. IdMap ids_;
  1140. };
  1141. } // namespace
  1142. std::vector<EditType> CalculateOptimalEdits(
  1143. const std::vector<std::string>& left,
  1144. const std::vector<std::string>& right) {
  1145. std::vector<size_t> left_ids, right_ids;
  1146. {
  1147. InternalStrings intern_table;
  1148. for (size_t i = 0; i < left.size(); ++i) {
  1149. left_ids.push_back(intern_table.GetId(left[i]));
  1150. }
  1151. for (size_t i = 0; i < right.size(); ++i) {
  1152. right_ids.push_back(intern_table.GetId(right[i]));
  1153. }
  1154. }
  1155. return CalculateOptimalEdits(left_ids, right_ids);
  1156. }
  1157. namespace {
  1158. // Helper class that holds the state for one hunk and prints it out to the
  1159. // stream.
  1160. // It reorders adds/removes when possible to group all removes before all
  1161. // adds. It also adds the hunk header before printint into the stream.
  1162. class Hunk {
  1163. public:
  1164. Hunk(size_t left_start, size_t right_start)
  1165. : left_start_(left_start),
  1166. right_start_(right_start),
  1167. adds_(),
  1168. removes_(),
  1169. common_() {}
  1170. void PushLine(char edit, const char* line) {
  1171. switch (edit) {
  1172. case ' ':
  1173. ++common_;
  1174. FlushEdits();
  1175. hunk_.push_back(std::make_pair(' ', line));
  1176. break;
  1177. case '-':
  1178. ++removes_;
  1179. hunk_removes_.push_back(std::make_pair('-', line));
  1180. break;
  1181. case '+':
  1182. ++adds_;
  1183. hunk_adds_.push_back(std::make_pair('+', line));
  1184. break;
  1185. }
  1186. }
  1187. void PrintTo(std::ostream* os) {
  1188. PrintHeader(os);
  1189. FlushEdits();
  1190. for (std::list<std::pair<char, const char*> >::const_iterator it =
  1191. hunk_.begin();
  1192. it != hunk_.end(); ++it) {
  1193. *os << it->first << it->second << "\n";
  1194. }
  1195. }
  1196. bool has_edits() const { return adds_ || removes_; }
  1197. private:
  1198. void FlushEdits() {
  1199. hunk_.splice(hunk_.end(), hunk_removes_);
  1200. hunk_.splice(hunk_.end(), hunk_adds_);
  1201. }
  1202. // Print a unified diff header for one hunk.
  1203. // The format is
  1204. // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
  1205. // where the left/right parts are omitted if unnecessary.
  1206. void PrintHeader(std::ostream* ss) const {
  1207. *ss << "@@ ";
  1208. if (removes_) {
  1209. *ss << "-" << left_start_ << "," << (removes_ + common_);
  1210. }
  1211. if (removes_ && adds_) {
  1212. *ss << " ";
  1213. }
  1214. if (adds_) {
  1215. *ss << "+" << right_start_ << "," << (adds_ + common_);
  1216. }
  1217. *ss << " @@\n";
  1218. }
  1219. size_t left_start_, right_start_;
  1220. size_t adds_, removes_, common_;
  1221. std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
  1222. };
  1223. } // namespace
  1224. // Create a list of diff hunks in Unified diff format.
  1225. // Each hunk has a header generated by PrintHeader above plus a body with
  1226. // lines prefixed with ' ' for no change, '-' for deletion and '+' for
  1227. // addition.
  1228. // 'context' represents the desired unchanged prefix/suffix around the diff.
  1229. // If two hunks are close enough that their contexts overlap, then they are
  1230. // joined into one hunk.
  1231. std::string CreateUnifiedDiff(const std::vector<std::string>& left,
  1232. const std::vector<std::string>& right,
  1233. size_t context) {
  1234. const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
  1235. size_t l_i = 0, r_i = 0, edit_i = 0;
  1236. std::stringstream ss;
  1237. while (edit_i < edits.size()) {
  1238. // Find first edit.
  1239. while (edit_i < edits.size() && edits[edit_i] == kMatch) {
  1240. ++l_i;
  1241. ++r_i;
  1242. ++edit_i;
  1243. }
  1244. // Find the first line to include in the hunk.
  1245. const size_t prefix_context = std::min(l_i, context);
  1246. Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
  1247. for (size_t i = prefix_context; i > 0; --i) {
  1248. hunk.PushLine(' ', left[l_i - i].c_str());
  1249. }
  1250. // Iterate the edits until we found enough suffix for the hunk or the input
  1251. // is over.
  1252. size_t n_suffix = 0;
  1253. for (; edit_i < edits.size(); ++edit_i) {
  1254. if (n_suffix >= context) {
  1255. // Continue only if the next hunk is very close.
  1256. auto it = edits.begin() + static_cast<int>(edit_i);
  1257. while (it != edits.end() && *it == kMatch) ++it;
  1258. if (it == edits.end() ||
  1259. static_cast<size_t>(it - edits.begin()) - edit_i >= context) {
  1260. // There is no next edit or it is too far away.
  1261. break;
  1262. }
  1263. }
  1264. EditType edit = edits[edit_i];
  1265. // Reset count when a non match is found.
  1266. n_suffix = edit == kMatch ? n_suffix + 1 : 0;
  1267. if (edit == kMatch || edit == kRemove || edit == kReplace) {
  1268. hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
  1269. }
  1270. if (edit == kAdd || edit == kReplace) {
  1271. hunk.PushLine('+', right[r_i].c_str());
  1272. }
  1273. // Advance indices, depending on edit type.
  1274. l_i += edit != kAdd;
  1275. r_i += edit != kRemove;
  1276. }
  1277. if (!hunk.has_edits()) {
  1278. // We are done. We don't want this hunk.
  1279. break;
  1280. }
  1281. hunk.PrintTo(&ss);
  1282. }
  1283. return ss.str();
  1284. }
  1285. } // namespace edit_distance
  1286. namespace {
  1287. // The string representation of the values received in EqFailure() are already
  1288. // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
  1289. // characters the same.
  1290. std::vector<std::string> SplitEscapedString(const std::string& str) {
  1291. std::vector<std::string> lines;
  1292. size_t start = 0, end = str.size();
  1293. if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
  1294. ++start;
  1295. --end;
  1296. }
  1297. bool escaped = false;
  1298. for (size_t i = start; i + 1 < end; ++i) {
  1299. if (escaped) {
  1300. escaped = false;
  1301. if (str[i] == 'n') {
  1302. lines.push_back(str.substr(start, i - start - 1));
  1303. start = i + 1;
  1304. }
  1305. } else {
  1306. escaped = str[i] == '\\';
  1307. }
  1308. }
  1309. lines.push_back(str.substr(start, end - start));
  1310. return lines;
  1311. }
  1312. } // namespace
  1313. // Constructs and returns the message for an equality assertion
  1314. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  1315. //
  1316. // The first four parameters are the expressions used in the assertion
  1317. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  1318. // where foo is 5 and bar is 6, we have:
  1319. //
  1320. // lhs_expression: "foo"
  1321. // rhs_expression: "bar"
  1322. // lhs_value: "5"
  1323. // rhs_value: "6"
  1324. //
  1325. // The ignoring_case parameter is true if and only if the assertion is a
  1326. // *_STRCASEEQ*. When it's true, the string "Ignoring case" will
  1327. // be inserted into the message.
  1328. AssertionResult EqFailure(const char* lhs_expression,
  1329. const char* rhs_expression,
  1330. const std::string& lhs_value,
  1331. const std::string& rhs_value, bool ignoring_case) {
  1332. Message msg;
  1333. msg << "Expected equality of these values:";
  1334. msg << "\n " << lhs_expression;
  1335. if (lhs_value != lhs_expression) {
  1336. msg << "\n Which is: " << lhs_value;
  1337. }
  1338. msg << "\n " << rhs_expression;
  1339. if (rhs_value != rhs_expression) {
  1340. msg << "\n Which is: " << rhs_value;
  1341. }
  1342. if (ignoring_case) {
  1343. msg << "\nIgnoring case";
  1344. }
  1345. if (!lhs_value.empty() && !rhs_value.empty()) {
  1346. const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value);
  1347. const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value);
  1348. if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
  1349. msg << "\nWith diff:\n"
  1350. << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
  1351. }
  1352. }
  1353. return AssertionFailure() << msg;
  1354. }
  1355. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  1356. std::string GetBoolAssertionFailureMessage(
  1357. const AssertionResult& assertion_result, const char* expression_text,
  1358. const char* actual_predicate_value, const char* expected_predicate_value) {
  1359. const char* actual_message = assertion_result.message();
  1360. Message msg;
  1361. msg << "Value of: " << expression_text
  1362. << "\n Actual: " << actual_predicate_value;
  1363. if (actual_message[0] != '\0') msg << " (" << actual_message << ")";
  1364. msg << "\nExpected: " << expected_predicate_value;
  1365. return msg.GetString();
  1366. }
  1367. // Helper function for implementing ASSERT_NEAR.
  1368. AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2,
  1369. const char* abs_error_expr, double val1,
  1370. double val2, double abs_error) {
  1371. const double diff = fabs(val1 - val2);
  1372. if (diff <= abs_error) return AssertionSuccess();
  1373. // Find the value which is closest to zero.
  1374. const double min_abs = std::min(fabs(val1), fabs(val2));
  1375. // Find the distance to the next double from that value.
  1376. const double epsilon =
  1377. nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
  1378. // Detect the case where abs_error is so small that EXPECT_NEAR is
  1379. // effectively the same as EXPECT_EQUAL, and give an informative error
  1380. // message so that the situation can be more easily understood without
  1381. // requiring exotic floating-point knowledge.
  1382. // Don't do an epsilon check if abs_error is zero because that implies
  1383. // that an equality check was actually intended.
  1384. if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
  1385. abs_error < epsilon) {
  1386. return AssertionFailure()
  1387. << "The difference between " << expr1 << " and " << expr2 << " is "
  1388. << diff << ", where\n"
  1389. << expr1 << " evaluates to " << val1 << ",\n"
  1390. << expr2 << " evaluates to " << val2 << ".\nThe abs_error parameter "
  1391. << abs_error_expr << " evaluates to " << abs_error
  1392. << " which is smaller than the minimum distance between doubles for "
  1393. "numbers of this magnitude which is "
  1394. << epsilon
  1395. << ", thus making this EXPECT_NEAR check equivalent to "
  1396. "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
  1397. }
  1398. return AssertionFailure()
  1399. << "The difference between " << expr1 << " and " << expr2 << " is "
  1400. << diff << ", which exceeds " << abs_error_expr << ", where\n"
  1401. << expr1 << " evaluates to " << val1 << ",\n"
  1402. << expr2 << " evaluates to " << val2 << ", and\n"
  1403. << abs_error_expr << " evaluates to " << abs_error << ".";
  1404. }
  1405. // Helper template for implementing FloatLE() and DoubleLE().
  1406. template <typename RawType>
  1407. AssertionResult FloatingPointLE(const char* expr1, const char* expr2,
  1408. RawType val1, RawType val2) {
  1409. // Returns success if val1 is less than val2,
  1410. if (val1 < val2) {
  1411. return AssertionSuccess();
  1412. }
  1413. // or if val1 is almost equal to val2.
  1414. const FloatingPoint<RawType> lhs(val1), rhs(val2);
  1415. if (lhs.AlmostEquals(rhs)) {
  1416. return AssertionSuccess();
  1417. }
  1418. // Note that the above two checks will both fail if either val1 or
  1419. // val2 is NaN, as the IEEE floating-point standard requires that
  1420. // any predicate involving a NaN must return false.
  1421. ::std::stringstream val1_ss;
  1422. val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  1423. << val1;
  1424. ::std::stringstream val2_ss;
  1425. val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  1426. << val2;
  1427. return AssertionFailure()
  1428. << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
  1429. << " Actual: " << StringStreamToString(&val1_ss) << " vs "
  1430. << StringStreamToString(&val2_ss);
  1431. }
  1432. } // namespace internal
  1433. // Asserts that val1 is less than, or almost equal to, val2. Fails
  1434. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  1435. AssertionResult FloatLE(const char* expr1, const char* expr2, float val1,
  1436. float val2) {
  1437. return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
  1438. }
  1439. // Asserts that val1 is less than, or almost equal to, val2. Fails
  1440. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  1441. AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1,
  1442. double val2) {
  1443. return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
  1444. }
  1445. namespace internal {
  1446. // The helper function for {ASSERT|EXPECT}_STREQ.
  1447. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  1448. const char* rhs_expression, const char* lhs,
  1449. const char* rhs) {
  1450. if (String::CStringEquals(lhs, rhs)) {
  1451. return AssertionSuccess();
  1452. }
  1453. return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
  1454. PrintToString(rhs), false);
  1455. }
  1456. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  1457. AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
  1458. const char* rhs_expression, const char* lhs,
  1459. const char* rhs) {
  1460. if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
  1461. return AssertionSuccess();
  1462. }
  1463. return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
  1464. PrintToString(rhs), true);
  1465. }
  1466. // The helper function for {ASSERT|EXPECT}_STRNE.
  1467. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  1468. const char* s2_expression, const char* s1,
  1469. const char* s2) {
  1470. if (!String::CStringEquals(s1, s2)) {
  1471. return AssertionSuccess();
  1472. } else {
  1473. return AssertionFailure()
  1474. << "Expected: (" << s1_expression << ") != (" << s2_expression
  1475. << "), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
  1476. }
  1477. }
  1478. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  1479. AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  1480. const char* s2_expression, const char* s1,
  1481. const char* s2) {
  1482. if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
  1483. return AssertionSuccess();
  1484. } else {
  1485. return AssertionFailure()
  1486. << "Expected: (" << s1_expression << ") != (" << s2_expression
  1487. << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
  1488. }
  1489. }
  1490. } // namespace internal
  1491. namespace {
  1492. // Helper functions for implementing IsSubString() and IsNotSubstring().
  1493. // This group of overloaded functions return true if and only if needle
  1494. // is a substring of haystack. NULL is considered a substring of
  1495. // itself only.
  1496. bool IsSubstringPred(const char* needle, const char* haystack) {
  1497. if (needle == nullptr || haystack == nullptr) return needle == haystack;
  1498. return strstr(haystack, needle) != nullptr;
  1499. }
  1500. bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
  1501. if (needle == nullptr || haystack == nullptr) return needle == haystack;
  1502. return wcsstr(haystack, needle) != nullptr;
  1503. }
  1504. // StringType here can be either ::std::string or ::std::wstring.
  1505. template <typename StringType>
  1506. bool IsSubstringPred(const StringType& needle, const StringType& haystack) {
  1507. return haystack.find(needle) != StringType::npos;
  1508. }
  1509. // This function implements either IsSubstring() or IsNotSubstring(),
  1510. // depending on the value of the expected_to_be_substring parameter.
  1511. // StringType here can be const char*, const wchar_t*, ::std::string,
  1512. // or ::std::wstring.
  1513. template <typename StringType>
  1514. AssertionResult IsSubstringImpl(bool expected_to_be_substring,
  1515. const char* needle_expr,
  1516. const char* haystack_expr,
  1517. const StringType& needle,
  1518. const StringType& haystack) {
  1519. if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
  1520. return AssertionSuccess();
  1521. const bool is_wide_string = sizeof(needle[0]) > 1;
  1522. const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
  1523. return AssertionFailure()
  1524. << "Value of: " << needle_expr << "\n"
  1525. << " Actual: " << begin_string_quote << needle << "\"\n"
  1526. << "Expected: " << (expected_to_be_substring ? "" : "not ")
  1527. << "a substring of " << haystack_expr << "\n"
  1528. << "Which is: " << begin_string_quote << haystack << "\"";
  1529. }
  1530. } // namespace
  1531. // IsSubstring() and IsNotSubstring() check whether needle is a
  1532. // substring of haystack (NULL is considered a substring of itself
  1533. // only), and return an appropriate error message when they fail.
  1534. AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
  1535. const char* needle, const char* haystack) {
  1536. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1537. }
  1538. AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
  1539. const wchar_t* needle, const wchar_t* haystack) {
  1540. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1541. }
  1542. AssertionResult IsNotSubstring(const char* needle_expr,
  1543. const char* haystack_expr, const char* needle,
  1544. const char* haystack) {
  1545. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1546. }
  1547. AssertionResult IsNotSubstring(const char* needle_expr,
  1548. const char* haystack_expr, const wchar_t* needle,
  1549. const wchar_t* haystack) {
  1550. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1551. }
  1552. AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
  1553. const ::std::string& needle,
  1554. const ::std::string& haystack) {
  1555. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1556. }
  1557. AssertionResult IsNotSubstring(const char* needle_expr,
  1558. const char* haystack_expr,
  1559. const ::std::string& needle,
  1560. const ::std::string& haystack) {
  1561. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1562. }
  1563. #if GTEST_HAS_STD_WSTRING
  1564. AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
  1565. const ::std::wstring& needle,
  1566. const ::std::wstring& haystack) {
  1567. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1568. }
  1569. AssertionResult IsNotSubstring(const char* needle_expr,
  1570. const char* haystack_expr,
  1571. const ::std::wstring& needle,
  1572. const ::std::wstring& haystack) {
  1573. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1574. }
  1575. #endif // GTEST_HAS_STD_WSTRING
  1576. namespace internal {
  1577. #if GTEST_OS_WINDOWS
  1578. namespace {
  1579. // Helper function for IsHRESULT{SuccessFailure} predicates
  1580. AssertionResult HRESULTFailureHelper(const char* expr, const char* expected,
  1581. long hr) { // NOLINT
  1582. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
  1583. // Windows CE doesn't support FormatMessage.
  1584. const char error_text[] = "";
  1585. #else
  1586. // Looks up the human-readable system message for the HRESULT code
  1587. // and since we're not passing any params to FormatMessage, we don't
  1588. // want inserts expanded.
  1589. const DWORD kFlags =
  1590. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
  1591. const DWORD kBufSize = 4096;
  1592. // Gets the system's human readable message string for this HRESULT.
  1593. char error_text[kBufSize] = {'\0'};
  1594. DWORD message_length = ::FormatMessageA(kFlags,
  1595. 0, // no source, we're asking system
  1596. static_cast<DWORD>(hr), // the error
  1597. 0, // no line width restrictions
  1598. error_text, // output buffer
  1599. kBufSize, // buf size
  1600. nullptr); // no arguments for inserts
  1601. // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
  1602. for (; message_length && IsSpace(error_text[message_length - 1]);
  1603. --message_length) {
  1604. error_text[message_length - 1] = '\0';
  1605. }
  1606. #endif // GTEST_OS_WINDOWS_MOBILE
  1607. const std::string error_hex("0x" + String::FormatHexInt(hr));
  1608. return ::testing::AssertionFailure()
  1609. << "Expected: " << expr << " " << expected << ".\n"
  1610. << " Actual: " << error_hex << " " << error_text << "\n";
  1611. }
  1612. } // namespace
  1613. AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
  1614. if (SUCCEEDED(hr)) {
  1615. return AssertionSuccess();
  1616. }
  1617. return HRESULTFailureHelper(expr, "succeeds", hr);
  1618. }
  1619. AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
  1620. if (FAILED(hr)) {
  1621. return AssertionSuccess();
  1622. }
  1623. return HRESULTFailureHelper(expr, "fails", hr);
  1624. }
  1625. #endif // GTEST_OS_WINDOWS
  1626. // Utility functions for encoding Unicode text (wide strings) in
  1627. // UTF-8.
  1628. // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
  1629. // like this:
  1630. //
  1631. // Code-point length Encoding
  1632. // 0 - 7 bits 0xxxxxxx
  1633. // 8 - 11 bits 110xxxxx 10xxxxxx
  1634. // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
  1635. // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  1636. // The maximum code-point a one-byte UTF-8 sequence can represent.
  1637. constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1;
  1638. // The maximum code-point a two-byte UTF-8 sequence can represent.
  1639. constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1;
  1640. // The maximum code-point a three-byte UTF-8 sequence can represent.
  1641. constexpr uint32_t kMaxCodePoint3 =
  1642. (static_cast<uint32_t>(1) << (4 + 2 * 6)) - 1;
  1643. // The maximum code-point a four-byte UTF-8 sequence can represent.
  1644. constexpr uint32_t kMaxCodePoint4 =
  1645. (static_cast<uint32_t>(1) << (3 + 3 * 6)) - 1;
  1646. // Chops off the n lowest bits from a bit pattern. Returns the n
  1647. // lowest bits. As a side effect, the original bit pattern will be
  1648. // shifted to the right by n bits.
  1649. inline uint32_t ChopLowBits(uint32_t* bits, int n) {
  1650. const uint32_t low_bits = *bits & ((static_cast<uint32_t>(1) << n) - 1);
  1651. *bits >>= n;
  1652. return low_bits;
  1653. }
  1654. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  1655. // code_point parameter is of type uint32_t because wchar_t may not be
  1656. // wide enough to contain a code point.
  1657. // If the code_point is not a valid Unicode code point
  1658. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  1659. // to "(Invalid Unicode 0xXXXXXXXX)".
  1660. std::string CodePointToUtf8(uint32_t code_point) {
  1661. if (code_point > kMaxCodePoint4) {
  1662. return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")";
  1663. }
  1664. char str[5]; // Big enough for the largest valid code point.
  1665. if (code_point <= kMaxCodePoint1) {
  1666. str[1] = '\0';
  1667. str[0] = static_cast<char>(code_point); // 0xxxxxxx
  1668. } else if (code_point <= kMaxCodePoint2) {
  1669. str[2] = '\0';
  1670. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1671. str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
  1672. } else if (code_point <= kMaxCodePoint3) {
  1673. str[3] = '\0';
  1674. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1675. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1676. str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
  1677. } else { // code_point <= kMaxCodePoint4
  1678. str[4] = '\0';
  1679. str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1680. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1681. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  1682. str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
  1683. }
  1684. return str;
  1685. }
  1686. // The following two functions only make sense if the system
  1687. // uses UTF-16 for wide string encoding. All supported systems
  1688. // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
  1689. // Determines if the arguments constitute UTF-16 surrogate pair
  1690. // and thus should be combined into a single Unicode code point
  1691. // using CreateCodePointFromUtf16SurrogatePair.
  1692. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
  1693. return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&
  1694. (second & 0xFC00) == 0xDC00;
  1695. }
  1696. // Creates a Unicode code point from UTF16 surrogate pair.
  1697. inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first,
  1698. wchar_t second) {
  1699. const auto first_u = static_cast<uint32_t>(first);
  1700. const auto second_u = static_cast<uint32_t>(second);
  1701. const uint32_t mask = (1 << 10) - 1;
  1702. return (sizeof(wchar_t) == 2)
  1703. ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
  1704. :
  1705. // This function should not be called when the condition is
  1706. // false, but we provide a sensible default in case it is.
  1707. first_u;
  1708. }
  1709. // Converts a wide string to a narrow string in UTF-8 encoding.
  1710. // The wide string is assumed to have the following encoding:
  1711. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
  1712. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  1713. // Parameter str points to a null-terminated wide string.
  1714. // Parameter num_chars may additionally limit the number
  1715. // of wchar_t characters processed. -1 is used when the entire string
  1716. // should be processed.
  1717. // If the string contains code points that are not valid Unicode code points
  1718. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  1719. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  1720. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  1721. // will be encoded as individual Unicode characters from Basic Normal Plane.
  1722. std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
  1723. if (num_chars == -1) num_chars = static_cast<int>(wcslen(str));
  1724. ::std::stringstream stream;
  1725. for (int i = 0; i < num_chars; ++i) {
  1726. uint32_t unicode_code_point;
  1727. if (str[i] == L'\0') {
  1728. break;
  1729. } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
  1730. unicode_code_point =
  1731. CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]);
  1732. i++;
  1733. } else {
  1734. unicode_code_point = static_cast<uint32_t>(str[i]);
  1735. }
  1736. stream << CodePointToUtf8(unicode_code_point);
  1737. }
  1738. return StringStreamToString(&stream);
  1739. }
  1740. // Converts a wide C string to an std::string using the UTF-8 encoding.
  1741. // NULL will be converted to "(null)".
  1742. std::string String::ShowWideCString(const wchar_t* wide_c_str) {
  1743. if (wide_c_str == nullptr) return "(null)";
  1744. return internal::WideStringToUtf8(wide_c_str, -1);
  1745. }
  1746. // Compares two wide C strings. Returns true if and only if they have the
  1747. // same content.
  1748. //
  1749. // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
  1750. // C string is considered different to any non-NULL C string,
  1751. // including the empty string.
  1752. bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) {
  1753. if (lhs == nullptr) return rhs == nullptr;
  1754. if (rhs == nullptr) return false;
  1755. return wcscmp(lhs, rhs) == 0;
  1756. }
  1757. // Helper function for *_STREQ on wide strings.
  1758. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  1759. const char* rhs_expression, const wchar_t* lhs,
  1760. const wchar_t* rhs) {
  1761. if (String::WideCStringEquals(lhs, rhs)) {
  1762. return AssertionSuccess();
  1763. }
  1764. return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
  1765. PrintToString(rhs), false);
  1766. }
  1767. // Helper function for *_STRNE on wide strings.
  1768. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  1769. const char* s2_expression, const wchar_t* s1,
  1770. const wchar_t* s2) {
  1771. if (!String::WideCStringEquals(s1, s2)) {
  1772. return AssertionSuccess();
  1773. }
  1774. return AssertionFailure()
  1775. << "Expected: (" << s1_expression << ") != (" << s2_expression
  1776. << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2);
  1777. }
  1778. // Compares two C strings, ignoring case. Returns true if and only if they have
  1779. // the same content.
  1780. //
  1781. // Unlike strcasecmp(), this function can handle NULL argument(s). A
  1782. // NULL C string is considered different to any non-NULL C string,
  1783. // including the empty string.
  1784. bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
  1785. if (lhs == nullptr) return rhs == nullptr;
  1786. if (rhs == nullptr) return false;
  1787. return posix::StrCaseCmp(lhs, rhs) == 0;
  1788. }
  1789. // Compares two wide C strings, ignoring case. Returns true if and only if they
  1790. // have the same content.
  1791. //
  1792. // Unlike wcscasecmp(), this function can handle NULL argument(s).
  1793. // A NULL C string is considered different to any non-NULL wide C string,
  1794. // including the empty string.
  1795. // NB: The implementations on different platforms slightly differ.
  1796. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  1797. // environment variable. On GNU platform this method uses wcscasecmp
  1798. // which compares according to LC_CTYPE category of the current locale.
  1799. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  1800. // current locale.
  1801. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  1802. const wchar_t* rhs) {
  1803. if (lhs == nullptr) return rhs == nullptr;
  1804. if (rhs == nullptr) return false;
  1805. #if GTEST_OS_WINDOWS
  1806. return _wcsicmp(lhs, rhs) == 0;
  1807. #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
  1808. return wcscasecmp(lhs, rhs) == 0;
  1809. #else
  1810. // Android, Mac OS X and Cygwin don't define wcscasecmp.
  1811. // Other unknown OSes may not define it either.
  1812. wint_t left, right;
  1813. do {
  1814. left = towlower(static_cast<wint_t>(*lhs++));
  1815. right = towlower(static_cast<wint_t>(*rhs++));
  1816. } while (left && left == right);
  1817. return left == right;
  1818. #endif // OS selector
  1819. }
  1820. // Returns true if and only if str ends with the given suffix, ignoring case.
  1821. // Any string is considered to end with an empty suffix.
  1822. bool String::EndsWithCaseInsensitive(const std::string& str,
  1823. const std::string& suffix) {
  1824. const size_t str_len = str.length();
  1825. const size_t suffix_len = suffix.length();
  1826. return (str_len >= suffix_len) &&
  1827. CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
  1828. suffix.c_str());
  1829. }
  1830. // Formats an int value as "%02d".
  1831. std::string String::FormatIntWidth2(int value) {
  1832. return FormatIntWidthN(value, 2);
  1833. }
  1834. // Formats an int value to given width with leading zeros.
  1835. std::string String::FormatIntWidthN(int value, int width) {
  1836. std::stringstream ss;
  1837. ss << std::setfill('0') << std::setw(width) << value;
  1838. return ss.str();
  1839. }
  1840. // Formats an int value as "%X".
  1841. std::string String::FormatHexUInt32(uint32_t value) {
  1842. std::stringstream ss;
  1843. ss << std::hex << std::uppercase << value;
  1844. return ss.str();
  1845. }
  1846. // Formats an int value as "%X".
  1847. std::string String::FormatHexInt(int value) {
  1848. return FormatHexUInt32(static_cast<uint32_t>(value));
  1849. }
  1850. // Formats a byte as "%02X".
  1851. std::string String::FormatByte(unsigned char value) {
  1852. std::stringstream ss;
  1853. ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
  1854. << static_cast<unsigned int>(value);
  1855. return ss.str();
  1856. }
  1857. // Converts the buffer in a stringstream to an std::string, converting NUL
  1858. // bytes to "\\0" along the way.
  1859. std::string StringStreamToString(::std::stringstream* ss) {
  1860. const ::std::string& str = ss->str();
  1861. const char* const start = str.c_str();
  1862. const char* const end = start + str.length();
  1863. std::string result;
  1864. result.reserve(static_cast<size_t>(2 * (end - start)));
  1865. for (const char* ch = start; ch != end; ++ch) {
  1866. if (*ch == '\0') {
  1867. result += "\\0"; // Replaces NUL with "\\0";
  1868. } else {
  1869. result += *ch;
  1870. }
  1871. }
  1872. return result;
  1873. }
  1874. // Appends the user-supplied message to the Google-Test-generated message.
  1875. std::string AppendUserMessage(const std::string& gtest_msg,
  1876. const Message& user_msg) {
  1877. // Appends the user message if it's non-empty.
  1878. const std::string user_msg_string = user_msg.GetString();
  1879. if (user_msg_string.empty()) {
  1880. return gtest_msg;
  1881. }
  1882. if (gtest_msg.empty()) {
  1883. return user_msg_string;
  1884. }
  1885. return gtest_msg + "\n" + user_msg_string;
  1886. }
  1887. } // namespace internal
  1888. // class TestResult
  1889. // Creates an empty TestResult.
  1890. TestResult::TestResult()
  1891. : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
  1892. // D'tor.
  1893. TestResult::~TestResult() {}
  1894. // Returns the i-th test part result among all the results. i can
  1895. // range from 0 to total_part_count() - 1. If i is not in that range,
  1896. // aborts the program.
  1897. const TestPartResult& TestResult::GetTestPartResult(int i) const {
  1898. if (i < 0 || i >= total_part_count()) internal::posix::Abort();
  1899. return test_part_results_.at(static_cast<size_t>(i));
  1900. }
  1901. // Returns the i-th test property. i can range from 0 to
  1902. // test_property_count() - 1. If i is not in that range, aborts the
  1903. // program.
  1904. const TestProperty& TestResult::GetTestProperty(int i) const {
  1905. if (i < 0 || i >= test_property_count()) internal::posix::Abort();
  1906. return test_properties_.at(static_cast<size_t>(i));
  1907. }
  1908. // Clears the test part results.
  1909. void TestResult::ClearTestPartResults() { test_part_results_.clear(); }
  1910. // Adds a test part result to the list.
  1911. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
  1912. test_part_results_.push_back(test_part_result);
  1913. }
  1914. // Adds a test property to the list. If a property with the same key as the
  1915. // supplied property is already represented, the value of this test_property
  1916. // replaces the old value for that key.
  1917. void TestResult::RecordProperty(const std::string& xml_element,
  1918. const TestProperty& test_property) {
  1919. if (!ValidateTestProperty(xml_element, test_property)) {
  1920. return;
  1921. }
  1922. internal::MutexLock lock(&test_properties_mutex_);
  1923. const std::vector<TestProperty>::iterator property_with_matching_key =
  1924. std::find_if(test_properties_.begin(), test_properties_.end(),
  1925. internal::TestPropertyKeyIs(test_property.key()));
  1926. if (property_with_matching_key == test_properties_.end()) {
  1927. test_properties_.push_back(test_property);
  1928. return;
  1929. }
  1930. property_with_matching_key->SetValue(test_property.value());
  1931. }
  1932. // The list of reserved attributes used in the <testsuites> element of XML
  1933. // output.
  1934. static const char* const kReservedTestSuitesAttributes[] = {
  1935. "disabled", "errors", "failures", "name",
  1936. "random_seed", "tests", "time", "timestamp"};
  1937. // The list of reserved attributes used in the <testsuite> element of XML
  1938. // output.
  1939. static const char* const kReservedTestSuiteAttributes[] = {
  1940. "disabled", "errors", "failures", "name",
  1941. "tests", "time", "timestamp", "skipped"};
  1942. // The list of reserved attributes used in the <testcase> element of XML output.
  1943. static const char* const kReservedTestCaseAttributes[] = {
  1944. "classname", "name", "status", "time",
  1945. "type_param", "value_param", "file", "line"};
  1946. // Use a slightly different set for allowed output to ensure existing tests can
  1947. // still RecordProperty("result") or "RecordProperty(timestamp")
  1948. static const char* const kReservedOutputTestCaseAttributes[] = {
  1949. "classname", "name", "status", "time", "type_param",
  1950. "value_param", "file", "line", "result", "timestamp"};
  1951. template <size_t kSize>
  1952. std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
  1953. return std::vector<std::string>(array, array + kSize);
  1954. }
  1955. static std::vector<std::string> GetReservedAttributesForElement(
  1956. const std::string& xml_element) {
  1957. if (xml_element == "testsuites") {
  1958. return ArrayAsVector(kReservedTestSuitesAttributes);
  1959. } else if (xml_element == "testsuite") {
  1960. return ArrayAsVector(kReservedTestSuiteAttributes);
  1961. } else if (xml_element == "testcase") {
  1962. return ArrayAsVector(kReservedTestCaseAttributes);
  1963. } else {
  1964. GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
  1965. }
  1966. // This code is unreachable but some compilers may not realizes that.
  1967. return std::vector<std::string>();
  1968. }
  1969. // TODO(jdesprez): Merge the two getReserved attributes once skip is improved
  1970. static std::vector<std::string> GetReservedOutputAttributesForElement(
  1971. const std::string& xml_element) {
  1972. if (xml_element == "testsuites") {
  1973. return ArrayAsVector(kReservedTestSuitesAttributes);
  1974. } else if (xml_element == "testsuite") {
  1975. return ArrayAsVector(kReservedTestSuiteAttributes);
  1976. } else if (xml_element == "testcase") {
  1977. return ArrayAsVector(kReservedOutputTestCaseAttributes);
  1978. } else {
  1979. GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
  1980. }
  1981. // This code is unreachable but some compilers may not realizes that.
  1982. return std::vector<std::string>();
  1983. }
  1984. static std::string FormatWordList(const std::vector<std::string>& words) {
  1985. Message word_list;
  1986. for (size_t i = 0; i < words.size(); ++i) {
  1987. if (i > 0 && words.size() > 2) {
  1988. word_list << ", ";
  1989. }
  1990. if (i == words.size() - 1) {
  1991. word_list << "and ";
  1992. }
  1993. word_list << "'" << words[i] << "'";
  1994. }
  1995. return word_list.GetString();
  1996. }
  1997. static bool ValidateTestPropertyName(
  1998. const std::string& property_name,
  1999. const std::vector<std::string>& reserved_names) {
  2000. if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
  2001. reserved_names.end()) {
  2002. ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
  2003. << " (" << FormatWordList(reserved_names)
  2004. << " are reserved by " << GTEST_NAME_ << ")";
  2005. return false;
  2006. }
  2007. return true;
  2008. }
  2009. // Adds a failure if the key is a reserved attribute of the element named
  2010. // xml_element. Returns true if the property is valid.
  2011. bool TestResult::ValidateTestProperty(const std::string& xml_element,
  2012. const TestProperty& test_property) {
  2013. return ValidateTestPropertyName(test_property.key(),
  2014. GetReservedAttributesForElement(xml_element));
  2015. }
  2016. // Clears the object.
  2017. void TestResult::Clear() {
  2018. test_part_results_.clear();
  2019. test_properties_.clear();
  2020. death_test_count_ = 0;
  2021. elapsed_time_ = 0;
  2022. }
  2023. // Returns true off the test part was skipped.
  2024. static bool TestPartSkipped(const TestPartResult& result) {
  2025. return result.skipped();
  2026. }
  2027. // Returns true if and only if the test was skipped.
  2028. bool TestResult::Skipped() const {
  2029. return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
  2030. }
  2031. // Returns true if and only if the test failed.
  2032. bool TestResult::Failed() const {
  2033. for (int i = 0; i < total_part_count(); ++i) {
  2034. if (GetTestPartResult(i).failed()) return true;
  2035. }
  2036. return false;
  2037. }
  2038. // Returns true if and only if the test part fatally failed.
  2039. static bool TestPartFatallyFailed(const TestPartResult& result) {
  2040. return result.fatally_failed();
  2041. }
  2042. // Returns true if and only if the test fatally failed.
  2043. bool TestResult::HasFatalFailure() const {
  2044. return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
  2045. }
  2046. // Returns true if and only if the test part non-fatally failed.
  2047. static bool TestPartNonfatallyFailed(const TestPartResult& result) {
  2048. return result.nonfatally_failed();
  2049. }
  2050. // Returns true if and only if the test has a non-fatal failure.
  2051. bool TestResult::HasNonfatalFailure() const {
  2052. return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
  2053. }
  2054. // Gets the number of all test parts. This is the sum of the number
  2055. // of successful test parts and the number of failed test parts.
  2056. int TestResult::total_part_count() const {
  2057. return static_cast<int>(test_part_results_.size());
  2058. }
  2059. // Returns the number of the test properties.
  2060. int TestResult::test_property_count() const {
  2061. return static_cast<int>(test_properties_.size());
  2062. }
  2063. // class Test
  2064. // Creates a Test object.
  2065. // The c'tor saves the states of all flags.
  2066. Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {}
  2067. // The d'tor restores the states of all flags. The actual work is
  2068. // done by the d'tor of the gtest_flag_saver_ field, and thus not
  2069. // visible here.
  2070. Test::~Test() {}
  2071. // Sets up the test fixture.
  2072. //
  2073. // A sub-class may override this.
  2074. void Test::SetUp() {}
  2075. // Tears down the test fixture.
  2076. //
  2077. // A sub-class may override this.
  2078. void Test::TearDown() {}
  2079. // Allows user supplied key value pairs to be recorded for later output.
  2080. void Test::RecordProperty(const std::string& key, const std::string& value) {
  2081. UnitTest::GetInstance()->RecordProperty(key, value);
  2082. }
  2083. // Allows user supplied key value pairs to be recorded for later output.
  2084. void Test::RecordProperty(const std::string& key, int value) {
  2085. Message value_message;
  2086. value_message << value;
  2087. RecordProperty(key, value_message.GetString().c_str());
  2088. }
  2089. namespace internal {
  2090. void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  2091. const std::string& message) {
  2092. // This function is a friend of UnitTest and as such has access to
  2093. // AddTestPartResult.
  2094. UnitTest::GetInstance()->AddTestPartResult(
  2095. result_type,
  2096. nullptr, // No info about the source file where the exception occurred.
  2097. -1, // We have no info on which line caused the exception.
  2098. message,
  2099. ""); // No stack trace, either.
  2100. }
  2101. } // namespace internal
  2102. // Google Test requires all tests in the same test suite to use the same test
  2103. // fixture class. This function checks if the current test has the
  2104. // same fixture class as the first test in the current test suite. If
  2105. // yes, it returns true; otherwise it generates a Google Test failure and
  2106. // returns false.
  2107. bool Test::HasSameFixtureClass() {
  2108. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2109. const TestSuite* const test_suite = impl->current_test_suite();
  2110. // Info about the first test in the current test suite.
  2111. const TestInfo* const first_test_info = test_suite->test_info_list()[0];
  2112. const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
  2113. const char* const first_test_name = first_test_info->name();
  2114. // Info about the current test.
  2115. const TestInfo* const this_test_info = impl->current_test_info();
  2116. const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
  2117. const char* const this_test_name = this_test_info->name();
  2118. if (this_fixture_id != first_fixture_id) {
  2119. // Is the first test defined using TEST?
  2120. const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
  2121. // Is this test defined using TEST?
  2122. const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
  2123. if (first_is_TEST || this_is_TEST) {
  2124. // Both TEST and TEST_F appear in same test suite, which is incorrect.
  2125. // Tell the user how to fix this.
  2126. // Gets the name of the TEST and the name of the TEST_F. Note
  2127. // that first_is_TEST and this_is_TEST cannot both be true, as
  2128. // the fixture IDs are different for the two tests.
  2129. const char* const TEST_name =
  2130. first_is_TEST ? first_test_name : this_test_name;
  2131. const char* const TEST_F_name =
  2132. first_is_TEST ? this_test_name : first_test_name;
  2133. ADD_FAILURE()
  2134. << "All tests in the same test suite must use the same test fixture\n"
  2135. << "class, so mixing TEST_F and TEST in the same test suite is\n"
  2136. << "illegal. In test suite " << this_test_info->test_suite_name()
  2137. << ",\n"
  2138. << "test " << TEST_F_name << " is defined using TEST_F but\n"
  2139. << "test " << TEST_name << " is defined using TEST. You probably\n"
  2140. << "want to change the TEST to TEST_F or move it to another test\n"
  2141. << "case.";
  2142. } else {
  2143. // Two fixture classes with the same name appear in two different
  2144. // namespaces, which is not allowed. Tell the user how to fix this.
  2145. ADD_FAILURE()
  2146. << "All tests in the same test suite must use the same test fixture\n"
  2147. << "class. However, in test suite "
  2148. << this_test_info->test_suite_name() << ",\n"
  2149. << "you defined test " << first_test_name << " and test "
  2150. << this_test_name << "\n"
  2151. << "using two different test fixture classes. This can happen if\n"
  2152. << "the two classes are from different namespaces or translation\n"
  2153. << "units and have the same name. You should probably rename one\n"
  2154. << "of the classes to put the tests into different test suites.";
  2155. }
  2156. return false;
  2157. }
  2158. return true;
  2159. }
  2160. #if GTEST_HAS_SEH
  2161. // Adds an "exception thrown" fatal failure to the current test. This
  2162. // function returns its result via an output parameter pointer because VC++
  2163. // prohibits creation of objects with destructors on stack in functions
  2164. // using __try (see error C2712).
  2165. static std::string* FormatSehExceptionMessage(DWORD exception_code,
  2166. const char* location) {
  2167. Message message;
  2168. message << "SEH exception with code 0x" << std::setbase(16) << exception_code
  2169. << std::setbase(10) << " thrown in " << location << ".";
  2170. return new std::string(message.GetString());
  2171. }
  2172. #endif // GTEST_HAS_SEH
  2173. namespace internal {
  2174. #if GTEST_HAS_EXCEPTIONS
  2175. // Adds an "exception thrown" fatal failure to the current test.
  2176. static std::string FormatCxxExceptionMessage(const char* description,
  2177. const char* location) {
  2178. Message message;
  2179. if (description != nullptr) {
  2180. message << "C++ exception with description \"" << description << "\"";
  2181. } else {
  2182. message << "Unknown C++ exception";
  2183. }
  2184. message << " thrown in " << location << ".";
  2185. return message.GetString();
  2186. }
  2187. static std::string PrintTestPartResultToString(
  2188. const TestPartResult& test_part_result);
  2189. GoogleTestFailureException::GoogleTestFailureException(
  2190. const TestPartResult& failure)
  2191. : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
  2192. #endif // GTEST_HAS_EXCEPTIONS
  2193. // We put these helper functions in the internal namespace as IBM's xlC
  2194. // compiler rejects the code if they were declared static.
  2195. // Runs the given method and handles SEH exceptions it throws, when
  2196. // SEH is supported; returns the 0-value for type Result in case of an
  2197. // SEH exception. (Microsoft compilers cannot handle SEH and C++
  2198. // exceptions in the same function. Therefore, we provide a separate
  2199. // wrapper function for handling SEH exceptions.)
  2200. template <class T, typename Result>
  2201. Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
  2202. const char* location) {
  2203. #if GTEST_HAS_SEH
  2204. __try {
  2205. return (object->*method)();
  2206. } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
  2207. GetExceptionCode())) {
  2208. // We create the exception message on the heap because VC++ prohibits
  2209. // creation of objects with destructors on stack in functions using __try
  2210. // (see error C2712).
  2211. std::string* exception_message =
  2212. FormatSehExceptionMessage(GetExceptionCode(), location);
  2213. internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
  2214. *exception_message);
  2215. delete exception_message;
  2216. return static_cast<Result>(0);
  2217. }
  2218. #else
  2219. (void)location;
  2220. return (object->*method)();
  2221. #endif // GTEST_HAS_SEH
  2222. }
  2223. // Runs the given method and catches and reports C++ and/or SEH-style
  2224. // exceptions, if they are supported; returns the 0-value for type
  2225. // Result in case of an SEH exception.
  2226. template <class T, typename Result>
  2227. Result HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
  2228. const char* location) {
  2229. // NOTE: The user code can affect the way in which Google Test handles
  2230. // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
  2231. // RUN_ALL_TESTS() starts. It is technically possible to check the flag
  2232. // after the exception is caught and either report or re-throw the
  2233. // exception based on the flag's value:
  2234. //
  2235. // try {
  2236. // // Perform the test method.
  2237. // } catch (...) {
  2238. // if (GTEST_FLAG_GET(catch_exceptions))
  2239. // // Report the exception as failure.
  2240. // else
  2241. // throw; // Re-throws the original exception.
  2242. // }
  2243. //
  2244. // However, the purpose of this flag is to allow the program to drop into
  2245. // the debugger when the exception is thrown. On most platforms, once the
  2246. // control enters the catch block, the exception origin information is
  2247. // lost and the debugger will stop the program at the point of the
  2248. // re-throw in this function -- instead of at the point of the original
  2249. // throw statement in the code under test. For this reason, we perform
  2250. // the check early, sacrificing the ability to affect Google Test's
  2251. // exception handling in the method where the exception is thrown.
  2252. if (internal::GetUnitTestImpl()->catch_exceptions()) {
  2253. #if GTEST_HAS_EXCEPTIONS
  2254. try {
  2255. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  2256. } catch (const AssertionException&) { // NOLINT
  2257. // This failure was reported already.
  2258. } catch (const internal::GoogleTestFailureException&) { // NOLINT
  2259. // This exception type can only be thrown by a failed Google
  2260. // Test assertion with the intention of letting another testing
  2261. // framework catch it. Therefore we just re-throw it.
  2262. throw;
  2263. } catch (const std::exception& e) { // NOLINT
  2264. internal::ReportFailureInUnknownLocation(
  2265. TestPartResult::kFatalFailure,
  2266. FormatCxxExceptionMessage(e.what(), location));
  2267. } catch (...) { // NOLINT
  2268. internal::ReportFailureInUnknownLocation(
  2269. TestPartResult::kFatalFailure,
  2270. FormatCxxExceptionMessage(nullptr, location));
  2271. }
  2272. return static_cast<Result>(0);
  2273. #else
  2274. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  2275. #endif // GTEST_HAS_EXCEPTIONS
  2276. } else {
  2277. return (object->*method)();
  2278. }
  2279. }
  2280. } // namespace internal
  2281. // Runs the test and updates the test result.
  2282. void Test::Run() {
  2283. if (!HasSameFixtureClass()) return;
  2284. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2285. impl->os_stack_trace_getter()->UponLeavingGTest();
  2286. internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
  2287. // We will run the test only if SetUp() was successful and didn't call
  2288. // GTEST_SKIP().
  2289. if (!HasFatalFailure() && !IsSkipped()) {
  2290. impl->os_stack_trace_getter()->UponLeavingGTest();
  2291. internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody,
  2292. "the test body");
  2293. }
  2294. // However, we want to clean up as much as possible. Hence we will
  2295. // always call TearDown(), even if SetUp() or the test body has
  2296. // failed.
  2297. impl->os_stack_trace_getter()->UponLeavingGTest();
  2298. internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown,
  2299. "TearDown()");
  2300. }
  2301. // Returns true if and only if the current test has a fatal failure.
  2302. bool Test::HasFatalFailure() {
  2303. return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
  2304. }
  2305. // Returns true if and only if the current test has a non-fatal failure.
  2306. bool Test::HasNonfatalFailure() {
  2307. return internal::GetUnitTestImpl()
  2308. ->current_test_result()
  2309. ->HasNonfatalFailure();
  2310. }
  2311. // Returns true if and only if the current test was skipped.
  2312. bool Test::IsSkipped() {
  2313. return internal::GetUnitTestImpl()->current_test_result()->Skipped();
  2314. }
  2315. // class TestInfo
  2316. // Constructs a TestInfo object. It assumes ownership of the test factory
  2317. // object.
  2318. TestInfo::TestInfo(const std::string& a_test_suite_name,
  2319. const std::string& a_name, const char* a_type_param,
  2320. const char* a_value_param,
  2321. internal::CodeLocation a_code_location,
  2322. internal::TypeId fixture_class_id,
  2323. internal::TestFactoryBase* factory)
  2324. : test_suite_name_(a_test_suite_name),
  2325. name_(a_name),
  2326. type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
  2327. value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
  2328. location_(a_code_location),
  2329. fixture_class_id_(fixture_class_id),
  2330. should_run_(false),
  2331. is_disabled_(false),
  2332. matches_filter_(false),
  2333. is_in_another_shard_(false),
  2334. factory_(factory),
  2335. result_() {}
  2336. // Destructs a TestInfo object.
  2337. TestInfo::~TestInfo() { delete factory_; }
  2338. namespace internal {
  2339. // Creates a new TestInfo object and registers it with Google Test;
  2340. // returns the created object.
  2341. //
  2342. // Arguments:
  2343. //
  2344. // test_suite_name: name of the test suite
  2345. // name: name of the test
  2346. // type_param: the name of the test's type parameter, or NULL if
  2347. // this is not a typed or a type-parameterized test.
  2348. // value_param: text representation of the test's value parameter,
  2349. // or NULL if this is not a value-parameterized test.
  2350. // code_location: code location where the test is defined
  2351. // fixture_class_id: ID of the test fixture class
  2352. // set_up_tc: pointer to the function that sets up the test suite
  2353. // tear_down_tc: pointer to the function that tears down the test suite
  2354. // factory: pointer to the factory that creates a test object.
  2355. // The newly created TestInfo instance will assume
  2356. // ownership of the factory object.
  2357. TestInfo* MakeAndRegisterTestInfo(
  2358. const char* test_suite_name, const char* name, const char* type_param,
  2359. const char* value_param, CodeLocation code_location,
  2360. TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
  2361. TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
  2362. TestInfo* const test_info =
  2363. new TestInfo(test_suite_name, name, type_param, value_param,
  2364. code_location, fixture_class_id, factory);
  2365. GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
  2366. return test_info;
  2367. }
  2368. void ReportInvalidTestSuiteType(const char* test_suite_name,
  2369. CodeLocation code_location) {
  2370. Message errors;
  2371. errors
  2372. << "Attempted redefinition of test suite " << test_suite_name << ".\n"
  2373. << "All tests in the same test suite must use the same test fixture\n"
  2374. << "class. However, in test suite " << test_suite_name << ", you tried\n"
  2375. << "to define a test using a fixture class different from the one\n"
  2376. << "used earlier. This can happen if the two fixture classes are\n"
  2377. << "from different namespaces and have the same name. You should\n"
  2378. << "probably rename one of the classes to put the tests into different\n"
  2379. << "test suites.";
  2380. GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
  2381. code_location.line)
  2382. << " " << errors.GetString();
  2383. }
  2384. } // namespace internal
  2385. namespace {
  2386. // A predicate that checks the test name of a TestInfo against a known
  2387. // value.
  2388. //
  2389. // This is used for implementation of the TestSuite class only. We put
  2390. // it in the anonymous namespace to prevent polluting the outer
  2391. // namespace.
  2392. //
  2393. // TestNameIs is copyable.
  2394. class TestNameIs {
  2395. public:
  2396. // Constructor.
  2397. //
  2398. // TestNameIs has NO default constructor.
  2399. explicit TestNameIs(const char* name) : name_(name) {}
  2400. // Returns true if and only if the test name of test_info matches name_.
  2401. bool operator()(const TestInfo* test_info) const {
  2402. return test_info && test_info->name() == name_;
  2403. }
  2404. private:
  2405. std::string name_;
  2406. };
  2407. } // namespace
  2408. namespace internal {
  2409. // This method expands all parameterized tests registered with macros TEST_P
  2410. // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
  2411. // This will be done just once during the program runtime.
  2412. void UnitTestImpl::RegisterParameterizedTests() {
  2413. if (!parameterized_tests_registered_) {
  2414. parameterized_test_registry_.RegisterTests();
  2415. type_parameterized_test_registry_.CheckForInstantiations();
  2416. parameterized_tests_registered_ = true;
  2417. }
  2418. }
  2419. } // namespace internal
  2420. // Creates the test object, runs it, records its result, and then
  2421. // deletes it.
  2422. void TestInfo::Run() {
  2423. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  2424. if (!should_run_) {
  2425. if (is_disabled_ && matches_filter_) repeater->OnTestDisabled(*this);
  2426. return;
  2427. }
  2428. // Tells UnitTest where to store test result.
  2429. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2430. impl->set_current_test_info(this);
  2431. // Notifies the unit test event listeners that a test is about to start.
  2432. repeater->OnTestStart(*this);
  2433. result_.set_start_timestamp(internal::GetTimeInMillis());
  2434. internal::Timer timer;
  2435. impl->os_stack_trace_getter()->UponLeavingGTest();
  2436. // Creates the test object.
  2437. Test* const test = internal::HandleExceptionsInMethodIfSupported(
  2438. factory_, &internal::TestFactoryBase::CreateTest,
  2439. "the test fixture's constructor");
  2440. // Runs the test if the constructor didn't generate a fatal failure or invoke
  2441. // GTEST_SKIP().
  2442. // Note that the object will not be null
  2443. if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
  2444. // This doesn't throw as all user code that can throw are wrapped into
  2445. // exception handling code.
  2446. test->Run();
  2447. }
  2448. if (test != nullptr) {
  2449. // Deletes the test object.
  2450. impl->os_stack_trace_getter()->UponLeavingGTest();
  2451. internal::HandleExceptionsInMethodIfSupported(
  2452. test, &Test::DeleteSelf_, "the test fixture's destructor");
  2453. }
  2454. result_.set_elapsed_time(timer.Elapsed());
  2455. // Notifies the unit test event listener that a test has just finished.
  2456. repeater->OnTestEnd(*this);
  2457. // Tells UnitTest to stop associating assertion results to this
  2458. // test.
  2459. impl->set_current_test_info(nullptr);
  2460. }
  2461. // Skip and records a skipped test result for this object.
  2462. void TestInfo::Skip() {
  2463. if (!should_run_) return;
  2464. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2465. impl->set_current_test_info(this);
  2466. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  2467. // Notifies the unit test event listeners that a test is about to start.
  2468. repeater->OnTestStart(*this);
  2469. const TestPartResult test_part_result =
  2470. TestPartResult(TestPartResult::kSkip, this->file(), this->line(), "");
  2471. impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
  2472. test_part_result);
  2473. // Notifies the unit test event listener that a test has just finished.
  2474. repeater->OnTestEnd(*this);
  2475. impl->set_current_test_info(nullptr);
  2476. }
  2477. // class TestSuite
  2478. // Gets the number of successful tests in this test suite.
  2479. int TestSuite::successful_test_count() const {
  2480. return CountIf(test_info_list_, TestPassed);
  2481. }
  2482. // Gets the number of successful tests in this test suite.
  2483. int TestSuite::skipped_test_count() const {
  2484. return CountIf(test_info_list_, TestSkipped);
  2485. }
  2486. // Gets the number of failed tests in this test suite.
  2487. int TestSuite::failed_test_count() const {
  2488. return CountIf(test_info_list_, TestFailed);
  2489. }
  2490. // Gets the number of disabled tests that will be reported in the XML report.
  2491. int TestSuite::reportable_disabled_test_count() const {
  2492. return CountIf(test_info_list_, TestReportableDisabled);
  2493. }
  2494. // Gets the number of disabled tests in this test suite.
  2495. int TestSuite::disabled_test_count() const {
  2496. return CountIf(test_info_list_, TestDisabled);
  2497. }
  2498. // Gets the number of tests to be printed in the XML report.
  2499. int TestSuite::reportable_test_count() const {
  2500. return CountIf(test_info_list_, TestReportable);
  2501. }
  2502. // Get the number of tests in this test suite that should run.
  2503. int TestSuite::test_to_run_count() const {
  2504. return CountIf(test_info_list_, ShouldRunTest);
  2505. }
  2506. // Gets the number of all tests.
  2507. int TestSuite::total_test_count() const {
  2508. return static_cast<int>(test_info_list_.size());
  2509. }
  2510. // Creates a TestSuite with the given name.
  2511. //
  2512. // Arguments:
  2513. //
  2514. // a_name: name of the test suite
  2515. // a_type_param: the name of the test suite's type parameter, or NULL if
  2516. // this is not a typed or a type-parameterized test suite.
  2517. // set_up_tc: pointer to the function that sets up the test suite
  2518. // tear_down_tc: pointer to the function that tears down the test suite
  2519. TestSuite::TestSuite(const char* a_name, const char* a_type_param,
  2520. internal::SetUpTestSuiteFunc set_up_tc,
  2521. internal::TearDownTestSuiteFunc tear_down_tc)
  2522. : name_(a_name),
  2523. type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
  2524. set_up_tc_(set_up_tc),
  2525. tear_down_tc_(tear_down_tc),
  2526. should_run_(false),
  2527. start_timestamp_(0),
  2528. elapsed_time_(0) {}
  2529. // Destructor of TestSuite.
  2530. TestSuite::~TestSuite() {
  2531. // Deletes every Test in the collection.
  2532. ForEach(test_info_list_, internal::Delete<TestInfo>);
  2533. }
  2534. // Returns the i-th test among all the tests. i can range from 0 to
  2535. // total_test_count() - 1. If i is not in that range, returns NULL.
  2536. const TestInfo* TestSuite::GetTestInfo(int i) const {
  2537. const int index = GetElementOr(test_indices_, i, -1);
  2538. return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
  2539. }
  2540. // Returns the i-th test among all the tests. i can range from 0 to
  2541. // total_test_count() - 1. If i is not in that range, returns NULL.
  2542. TestInfo* TestSuite::GetMutableTestInfo(int i) {
  2543. const int index = GetElementOr(test_indices_, i, -1);
  2544. return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
  2545. }
  2546. // Adds a test to this test suite. Will delete the test upon
  2547. // destruction of the TestSuite object.
  2548. void TestSuite::AddTestInfo(TestInfo* test_info) {
  2549. test_info_list_.push_back(test_info);
  2550. test_indices_.push_back(static_cast<int>(test_indices_.size()));
  2551. }
  2552. // Runs every test in this TestSuite.
  2553. void TestSuite::Run() {
  2554. if (!should_run_) return;
  2555. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2556. impl->set_current_test_suite(this);
  2557. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  2558. // Call both legacy and the new API
  2559. repeater->OnTestSuiteStart(*this);
  2560. // Legacy API is deprecated but still available
  2561. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  2562. repeater->OnTestCaseStart(*this);
  2563. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  2564. impl->os_stack_trace_getter()->UponLeavingGTest();
  2565. internal::HandleExceptionsInMethodIfSupported(
  2566. this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
  2567. const bool skip_all = ad_hoc_test_result().Failed();
  2568. start_timestamp_ = internal::GetTimeInMillis();
  2569. internal::Timer timer;
  2570. for (int i = 0; i < total_test_count(); i++) {
  2571. if (skip_all) {
  2572. GetMutableTestInfo(i)->Skip();
  2573. } else {
  2574. GetMutableTestInfo(i)->Run();
  2575. }
  2576. if (GTEST_FLAG_GET(fail_fast) &&
  2577. GetMutableTestInfo(i)->result()->Failed()) {
  2578. for (int j = i + 1; j < total_test_count(); j++) {
  2579. GetMutableTestInfo(j)->Skip();
  2580. }
  2581. break;
  2582. }
  2583. }
  2584. elapsed_time_ = timer.Elapsed();
  2585. impl->os_stack_trace_getter()->UponLeavingGTest();
  2586. internal::HandleExceptionsInMethodIfSupported(
  2587. this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()");
  2588. // Call both legacy and the new API
  2589. repeater->OnTestSuiteEnd(*this);
  2590. // Legacy API is deprecated but still available
  2591. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  2592. repeater->OnTestCaseEnd(*this);
  2593. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  2594. impl->set_current_test_suite(nullptr);
  2595. }
  2596. // Skips all tests under this TestSuite.
  2597. void TestSuite::Skip() {
  2598. if (!should_run_) return;
  2599. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2600. impl->set_current_test_suite(this);
  2601. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  2602. // Call both legacy and the new API
  2603. repeater->OnTestSuiteStart(*this);
  2604. // Legacy API is deprecated but still available
  2605. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  2606. repeater->OnTestCaseStart(*this);
  2607. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  2608. for (int i = 0; i < total_test_count(); i++) {
  2609. GetMutableTestInfo(i)->Skip();
  2610. }
  2611. // Call both legacy and the new API
  2612. repeater->OnTestSuiteEnd(*this);
  2613. // Legacy API is deprecated but still available
  2614. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  2615. repeater->OnTestCaseEnd(*this);
  2616. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  2617. impl->set_current_test_suite(nullptr);
  2618. }
  2619. // Clears the results of all tests in this test suite.
  2620. void TestSuite::ClearResult() {
  2621. ad_hoc_test_result_.Clear();
  2622. ForEach(test_info_list_, TestInfo::ClearTestResult);
  2623. }
  2624. // Shuffles the tests in this test suite.
  2625. void TestSuite::ShuffleTests(internal::Random* random) {
  2626. Shuffle(random, &test_indices_);
  2627. }
  2628. // Restores the test order to before the first shuffle.
  2629. void TestSuite::UnshuffleTests() {
  2630. for (size_t i = 0; i < test_indices_.size(); i++) {
  2631. test_indices_[i] = static_cast<int>(i);
  2632. }
  2633. }
  2634. // Formats a countable noun. Depending on its quantity, either the
  2635. // singular form or the plural form is used. e.g.
  2636. //
  2637. // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
  2638. // FormatCountableNoun(5, "book", "books") returns "5 books".
  2639. static std::string FormatCountableNoun(int count, const char* singular_form,
  2640. const char* plural_form) {
  2641. return internal::StreamableToString(count) + " " +
  2642. (count == 1 ? singular_form : plural_form);
  2643. }
  2644. // Formats the count of tests.
  2645. static std::string FormatTestCount(int test_count) {
  2646. return FormatCountableNoun(test_count, "test", "tests");
  2647. }
  2648. // Formats the count of test suites.
  2649. static std::string FormatTestSuiteCount(int test_suite_count) {
  2650. return FormatCountableNoun(test_suite_count, "test suite", "test suites");
  2651. }
  2652. // Converts a TestPartResult::Type enum to human-friendly string
  2653. // representation. Both kNonFatalFailure and kFatalFailure are translated
  2654. // to "Failure", as the user usually doesn't care about the difference
  2655. // between the two when viewing the test result.
  2656. static const char* TestPartResultTypeToString(TestPartResult::Type type) {
  2657. switch (type) {
  2658. case TestPartResult::kSkip:
  2659. return "Skipped\n";
  2660. case TestPartResult::kSuccess:
  2661. return "Success";
  2662. case TestPartResult::kNonFatalFailure:
  2663. case TestPartResult::kFatalFailure:
  2664. #ifdef _MSC_VER
  2665. return "error: ";
  2666. #else
  2667. return "Failure\n";
  2668. #endif
  2669. default:
  2670. return "Unknown result type";
  2671. }
  2672. }
  2673. namespace internal {
  2674. namespace {
  2675. enum class GTestColor { kDefault, kRed, kGreen, kYellow };
  2676. } // namespace
  2677. // Prints a TestPartResult to an std::string.
  2678. static std::string PrintTestPartResultToString(
  2679. const TestPartResult& test_part_result) {
  2680. return (Message() << internal::FormatFileLocation(
  2681. test_part_result.file_name(),
  2682. test_part_result.line_number())
  2683. << " "
  2684. << TestPartResultTypeToString(test_part_result.type())
  2685. << test_part_result.message())
  2686. .GetString();
  2687. }
  2688. // Prints a TestPartResult.
  2689. static void PrintTestPartResult(const TestPartResult& test_part_result) {
  2690. const std::string& result = PrintTestPartResultToString(test_part_result);
  2691. printf("%s\n", result.c_str());
  2692. fflush(stdout);
  2693. // If the test program runs in Visual Studio or a debugger, the
  2694. // following statements add the test part result message to the Output
  2695. // window such that the user can double-click on it to jump to the
  2696. // corresponding source code location; otherwise they do nothing.
  2697. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  2698. // We don't call OutputDebugString*() on Windows Mobile, as printing
  2699. // to stdout is done by OutputDebugString() there already - we don't
  2700. // want the same message printed twice.
  2701. ::OutputDebugStringA(result.c_str());
  2702. ::OutputDebugStringA("\n");
  2703. #endif
  2704. }
  2705. // class PrettyUnitTestResultPrinter
  2706. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
  2707. !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  2708. // Returns the character attribute for the given color.
  2709. static WORD GetColorAttribute(GTestColor color) {
  2710. switch (color) {
  2711. case GTestColor::kRed:
  2712. return FOREGROUND_RED;
  2713. case GTestColor::kGreen:
  2714. return FOREGROUND_GREEN;
  2715. case GTestColor::kYellow:
  2716. return FOREGROUND_RED | FOREGROUND_GREEN;
  2717. default:
  2718. return 0;
  2719. }
  2720. }
  2721. static int GetBitOffset(WORD color_mask) {
  2722. if (color_mask == 0) return 0;
  2723. int bitOffset = 0;
  2724. while ((color_mask & 1) == 0) {
  2725. color_mask >>= 1;
  2726. ++bitOffset;
  2727. }
  2728. return bitOffset;
  2729. }
  2730. static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
  2731. // Let's reuse the BG
  2732. static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
  2733. BACKGROUND_RED | BACKGROUND_INTENSITY;
  2734. static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
  2735. FOREGROUND_RED | FOREGROUND_INTENSITY;
  2736. const WORD existing_bg = old_color_attrs & background_mask;
  2737. WORD new_color =
  2738. GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
  2739. static const int bg_bitOffset = GetBitOffset(background_mask);
  2740. static const int fg_bitOffset = GetBitOffset(foreground_mask);
  2741. if (((new_color & background_mask) >> bg_bitOffset) ==
  2742. ((new_color & foreground_mask) >> fg_bitOffset)) {
  2743. new_color ^= FOREGROUND_INTENSITY; // invert intensity
  2744. }
  2745. return new_color;
  2746. }
  2747. #else
  2748. // Returns the ANSI color code for the given color. GTestColor::kDefault is
  2749. // an invalid input.
  2750. static const char* GetAnsiColorCode(GTestColor color) {
  2751. switch (color) {
  2752. case GTestColor::kRed:
  2753. return "1";
  2754. case GTestColor::kGreen:
  2755. return "2";
  2756. case GTestColor::kYellow:
  2757. return "3";
  2758. default:
  2759. return nullptr;
  2760. }
  2761. }
  2762. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  2763. // Returns true if and only if Google Test should use colors in the output.
  2764. bool ShouldUseColor(bool stdout_is_tty) {
  2765. std::string c = GTEST_FLAG_GET(color);
  2766. const char* const gtest_color = c.c_str();
  2767. if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
  2768. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
  2769. // On Windows the TERM variable is usually not set, but the
  2770. // console there does support colors.
  2771. return stdout_is_tty;
  2772. #else
  2773. // On non-Windows platforms, we rely on the TERM variable.
  2774. const char* const term = posix::GetEnv("TERM");
  2775. const bool term_supports_color =
  2776. String::CStringEquals(term, "xterm") ||
  2777. String::CStringEquals(term, "xterm-color") ||
  2778. String::CStringEquals(term, "xterm-256color") ||
  2779. String::CStringEquals(term, "screen") ||
  2780. String::CStringEquals(term, "screen-256color") ||
  2781. String::CStringEquals(term, "tmux") ||
  2782. String::CStringEquals(term, "tmux-256color") ||
  2783. String::CStringEquals(term, "rxvt-unicode") ||
  2784. String::CStringEquals(term, "rxvt-unicode-256color") ||
  2785. String::CStringEquals(term, "linux") ||
  2786. String::CStringEquals(term, "cygwin");
  2787. return stdout_is_tty && term_supports_color;
  2788. #endif // GTEST_OS_WINDOWS
  2789. }
  2790. return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
  2791. String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
  2792. String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
  2793. String::CStringEquals(gtest_color, "1");
  2794. // We take "yes", "true", "t", and "1" as meaning "yes". If the
  2795. // value is neither one of these nor "auto", we treat it as "no" to
  2796. // be conservative.
  2797. }
  2798. // Helpers for printing colored strings to stdout. Note that on Windows, we
  2799. // cannot simply emit special characters and have the terminal change colors.
  2800. // This routine must actually emit the characters rather than return a string
  2801. // that would be colored when printed, as can be done on Linux.
  2802. GTEST_ATTRIBUTE_PRINTF_(2, 3)
  2803. static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
  2804. va_list args;
  2805. va_start(args, fmt);
  2806. static const bool in_color_mode =
  2807. ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
  2808. const bool use_color = in_color_mode && (color != GTestColor::kDefault);
  2809. if (!use_color) {
  2810. vprintf(fmt, args);
  2811. va_end(args);
  2812. return;
  2813. }
  2814. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
  2815. !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  2816. const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  2817. // Gets the current text color.
  2818. CONSOLE_SCREEN_BUFFER_INFO buffer_info;
  2819. GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
  2820. const WORD old_color_attrs = buffer_info.wAttributes;
  2821. const WORD new_color = GetNewColor(color, old_color_attrs);
  2822. // We need to flush the stream buffers into the console before each
  2823. // SetConsoleTextAttribute call lest it affect the text that is already
  2824. // printed but has not yet reached the console.
  2825. fflush(stdout);
  2826. SetConsoleTextAttribute(stdout_handle, new_color);
  2827. vprintf(fmt, args);
  2828. fflush(stdout);
  2829. // Restores the text color.
  2830. SetConsoleTextAttribute(stdout_handle, old_color_attrs);
  2831. #else
  2832. printf("\033[0;3%sm", GetAnsiColorCode(color));
  2833. vprintf(fmt, args);
  2834. printf("\033[m"); // Resets the terminal to default.
  2835. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  2836. va_end(args);
  2837. }
  2838. // Text printed in Google Test's text output and --gtest_list_tests
  2839. // output to label the type parameter and value parameter for a test.
  2840. static const char kTypeParamLabel[] = "TypeParam";
  2841. static const char kValueParamLabel[] = "GetParam()";
  2842. static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
  2843. const char* const type_param = test_info.type_param();
  2844. const char* const value_param = test_info.value_param();
  2845. if (type_param != nullptr || value_param != nullptr) {
  2846. printf(", where ");
  2847. if (type_param != nullptr) {
  2848. printf("%s = %s", kTypeParamLabel, type_param);
  2849. if (value_param != nullptr) printf(" and ");
  2850. }
  2851. if (value_param != nullptr) {
  2852. printf("%s = %s", kValueParamLabel, value_param);
  2853. }
  2854. }
  2855. }
  2856. // This class implements the TestEventListener interface.
  2857. //
  2858. // Class PrettyUnitTestResultPrinter is copyable.
  2859. class PrettyUnitTestResultPrinter : public TestEventListener {
  2860. public:
  2861. PrettyUnitTestResultPrinter() {}
  2862. static void PrintTestName(const char* test_suite, const char* test) {
  2863. printf("%s.%s", test_suite, test);
  2864. }
  2865. // The following methods override what's in the TestEventListener class.
  2866. void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
  2867. void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
  2868. void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
  2869. void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
  2870. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  2871. void OnTestCaseStart(const TestCase& test_case) override;
  2872. #else
  2873. void OnTestSuiteStart(const TestSuite& test_suite) override;
  2874. #endif // OnTestCaseStart
  2875. void OnTestStart(const TestInfo& test_info) override;
  2876. void OnTestDisabled(const TestInfo& test_info) override;
  2877. void OnTestPartResult(const TestPartResult& result) override;
  2878. void OnTestEnd(const TestInfo& test_info) override;
  2879. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  2880. void OnTestCaseEnd(const TestCase& test_case) override;
  2881. #else
  2882. void OnTestSuiteEnd(const TestSuite& test_suite) override;
  2883. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  2884. void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
  2885. void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
  2886. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  2887. void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
  2888. private:
  2889. static void PrintFailedTests(const UnitTest& unit_test);
  2890. static void PrintFailedTestSuites(const UnitTest& unit_test);
  2891. static void PrintSkippedTests(const UnitTest& unit_test);
  2892. };
  2893. // Fired before each iteration of tests starts.
  2894. void PrettyUnitTestResultPrinter::OnTestIterationStart(
  2895. const UnitTest& unit_test, int iteration) {
  2896. if (GTEST_FLAG_GET(repeat) != 1)
  2897. printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
  2898. std::string f = GTEST_FLAG_GET(filter);
  2899. const char* const filter = f.c_str();
  2900. // Prints the filter if it's not *. This reminds the user that some
  2901. // tests may be skipped.
  2902. if (!String::CStringEquals(filter, kUniversalFilter)) {
  2903. ColoredPrintf(GTestColor::kYellow, "Note: %s filter = %s\n", GTEST_NAME_,
  2904. filter);
  2905. }
  2906. if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
  2907. const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
  2908. ColoredPrintf(GTestColor::kYellow, "Note: This is test shard %d of %s.\n",
  2909. static_cast<int>(shard_index) + 1,
  2910. internal::posix::GetEnv(kTestTotalShards));
  2911. }
  2912. if (GTEST_FLAG_GET(shuffle)) {
  2913. ColoredPrintf(GTestColor::kYellow,
  2914. "Note: Randomizing tests' orders with a seed of %d .\n",
  2915. unit_test.random_seed());
  2916. }
  2917. ColoredPrintf(GTestColor::kGreen, "[==========] ");
  2918. printf("Running %s from %s.\n",
  2919. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  2920. FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
  2921. fflush(stdout);
  2922. }
  2923. void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
  2924. const UnitTest& /*unit_test*/) {
  2925. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  2926. printf("Global test environment set-up.\n");
  2927. fflush(stdout);
  2928. }
  2929. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  2930. void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
  2931. const std::string counts =
  2932. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  2933. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  2934. printf("%s from %s", counts.c_str(), test_case.name());
  2935. if (test_case.type_param() == nullptr) {
  2936. printf("\n");
  2937. } else {
  2938. printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
  2939. }
  2940. fflush(stdout);
  2941. }
  2942. #else
  2943. void PrettyUnitTestResultPrinter::OnTestSuiteStart(
  2944. const TestSuite& test_suite) {
  2945. const std::string counts =
  2946. FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
  2947. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  2948. printf("%s from %s", counts.c_str(), test_suite.name());
  2949. if (test_suite.type_param() == nullptr) {
  2950. printf("\n");
  2951. } else {
  2952. printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
  2953. }
  2954. fflush(stdout);
  2955. }
  2956. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  2957. void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
  2958. ColoredPrintf(GTestColor::kGreen, "[ RUN ] ");
  2959. PrintTestName(test_info.test_suite_name(), test_info.name());
  2960. printf("\n");
  2961. fflush(stdout);
  2962. }
  2963. void PrettyUnitTestResultPrinter::OnTestDisabled(const TestInfo& test_info) {
  2964. ColoredPrintf(GTestColor::kYellow, "[ DISABLED ] ");
  2965. PrintTestName(test_info.test_suite_name(), test_info.name());
  2966. printf("\n");
  2967. fflush(stdout);
  2968. }
  2969. // Called after an assertion failure.
  2970. void PrettyUnitTestResultPrinter::OnTestPartResult(
  2971. const TestPartResult& result) {
  2972. switch (result.type()) {
  2973. // If the test part succeeded, we don't need to do anything.
  2974. case TestPartResult::kSuccess:
  2975. return;
  2976. default:
  2977. // Print failure message from the assertion
  2978. // (e.g. expected this and got that).
  2979. PrintTestPartResult(result);
  2980. fflush(stdout);
  2981. }
  2982. }
  2983. void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  2984. if (test_info.result()->Passed()) {
  2985. ColoredPrintf(GTestColor::kGreen, "[ OK ] ");
  2986. } else if (test_info.result()->Skipped()) {
  2987. ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
  2988. } else {
  2989. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  2990. }
  2991. PrintTestName(test_info.test_suite_name(), test_info.name());
  2992. if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info);
  2993. if (GTEST_FLAG_GET(print_time)) {
  2994. printf(" (%s ms)\n",
  2995. internal::StreamableToString(test_info.result()->elapsed_time())
  2996. .c_str());
  2997. } else {
  2998. printf("\n");
  2999. }
  3000. fflush(stdout);
  3001. }
  3002. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3003. void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
  3004. if (!GTEST_FLAG_GET(print_time)) return;
  3005. const std::string counts =
  3006. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  3007. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  3008. printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
  3009. internal::StreamableToString(test_case.elapsed_time()).c_str());
  3010. fflush(stdout);
  3011. }
  3012. #else
  3013. void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
  3014. if (!GTEST_FLAG_GET(print_time)) return;
  3015. const std::string counts =
  3016. FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
  3017. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  3018. printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
  3019. internal::StreamableToString(test_suite.elapsed_time()).c_str());
  3020. fflush(stdout);
  3021. }
  3022. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3023. void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
  3024. const UnitTest& /*unit_test*/) {
  3025. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  3026. printf("Global test environment tear-down\n");
  3027. fflush(stdout);
  3028. }
  3029. // Internal helper for printing the list of failed tests.
  3030. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
  3031. const int failed_test_count = unit_test.failed_test_count();
  3032. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  3033. printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
  3034. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  3035. const TestSuite& test_suite = *unit_test.GetTestSuite(i);
  3036. if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
  3037. continue;
  3038. }
  3039. for (int j = 0; j < test_suite.total_test_count(); ++j) {
  3040. const TestInfo& test_info = *test_suite.GetTestInfo(j);
  3041. if (!test_info.should_run() || !test_info.result()->Failed()) {
  3042. continue;
  3043. }
  3044. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  3045. printf("%s.%s", test_suite.name(), test_info.name());
  3046. PrintFullTestCommentIfPresent(test_info);
  3047. printf("\n");
  3048. }
  3049. }
  3050. printf("\n%2d FAILED %s\n", failed_test_count,
  3051. failed_test_count == 1 ? "TEST" : "TESTS");
  3052. }
  3053. // Internal helper for printing the list of test suite failures not covered by
  3054. // PrintFailedTests.
  3055. void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
  3056. const UnitTest& unit_test) {
  3057. int suite_failure_count = 0;
  3058. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  3059. const TestSuite& test_suite = *unit_test.GetTestSuite(i);
  3060. if (!test_suite.should_run()) {
  3061. continue;
  3062. }
  3063. if (test_suite.ad_hoc_test_result().Failed()) {
  3064. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  3065. printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
  3066. ++suite_failure_count;
  3067. }
  3068. }
  3069. if (suite_failure_count > 0) {
  3070. printf("\n%2d FAILED TEST %s\n", suite_failure_count,
  3071. suite_failure_count == 1 ? "SUITE" : "SUITES");
  3072. }
  3073. }
  3074. // Internal helper for printing the list of skipped tests.
  3075. void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
  3076. const int skipped_test_count = unit_test.skipped_test_count();
  3077. if (skipped_test_count == 0) {
  3078. return;
  3079. }
  3080. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  3081. const TestSuite& test_suite = *unit_test.GetTestSuite(i);
  3082. if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
  3083. continue;
  3084. }
  3085. for (int j = 0; j < test_suite.total_test_count(); ++j) {
  3086. const TestInfo& test_info = *test_suite.GetTestInfo(j);
  3087. if (!test_info.should_run() || !test_info.result()->Skipped()) {
  3088. continue;
  3089. }
  3090. ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
  3091. printf("%s.%s", test_suite.name(), test_info.name());
  3092. printf("\n");
  3093. }
  3094. }
  3095. }
  3096. void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  3097. int /*iteration*/) {
  3098. ColoredPrintf(GTestColor::kGreen, "[==========] ");
  3099. printf("%s from %s ran.",
  3100. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  3101. FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
  3102. if (GTEST_FLAG_GET(print_time)) {
  3103. printf(" (%s ms total)",
  3104. internal::StreamableToString(unit_test.elapsed_time()).c_str());
  3105. }
  3106. printf("\n");
  3107. ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
  3108. printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  3109. const int skipped_test_count = unit_test.skipped_test_count();
  3110. if (skipped_test_count > 0) {
  3111. ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
  3112. printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
  3113. PrintSkippedTests(unit_test);
  3114. }
  3115. if (!unit_test.Passed()) {
  3116. PrintFailedTests(unit_test);
  3117. PrintFailedTestSuites(unit_test);
  3118. }
  3119. int num_disabled = unit_test.reportable_disabled_test_count();
  3120. if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {
  3121. if (unit_test.Passed()) {
  3122. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
  3123. }
  3124. ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
  3125. num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
  3126. }
  3127. // Ensure that Google Test output is printed before, e.g., heapchecker output.
  3128. fflush(stdout);
  3129. }
  3130. // End PrettyUnitTestResultPrinter
  3131. // This class implements the TestEventListener interface.
  3132. //
  3133. // Class BriefUnitTestResultPrinter is copyable.
  3134. class BriefUnitTestResultPrinter : public TestEventListener {
  3135. public:
  3136. BriefUnitTestResultPrinter() {}
  3137. static void PrintTestName(const char* test_suite, const char* test) {
  3138. printf("%s.%s", test_suite, test);
  3139. }
  3140. // The following methods override what's in the TestEventListener class.
  3141. void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
  3142. void OnTestIterationStart(const UnitTest& /*unit_test*/,
  3143. int /*iteration*/) override {}
  3144. void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
  3145. void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
  3146. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3147. void OnTestCaseStart(const TestCase& /*test_case*/) override {}
  3148. #else
  3149. void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
  3150. #endif // OnTestCaseStart
  3151. void OnTestStart(const TestInfo& /*test_info*/) override {}
  3152. void OnTestDisabled(const TestInfo& /*test_info*/) override {}
  3153. void OnTestPartResult(const TestPartResult& result) override;
  3154. void OnTestEnd(const TestInfo& test_info) override;
  3155. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3156. void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
  3157. #else
  3158. void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
  3159. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3160. void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
  3161. void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
  3162. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  3163. void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
  3164. };
  3165. // Called after an assertion failure.
  3166. void BriefUnitTestResultPrinter::OnTestPartResult(
  3167. const TestPartResult& result) {
  3168. switch (result.type()) {
  3169. // If the test part succeeded, we don't need to do anything.
  3170. case TestPartResult::kSuccess:
  3171. return;
  3172. default:
  3173. // Print failure message from the assertion
  3174. // (e.g. expected this and got that).
  3175. PrintTestPartResult(result);
  3176. fflush(stdout);
  3177. }
  3178. }
  3179. void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  3180. if (test_info.result()->Failed()) {
  3181. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  3182. PrintTestName(test_info.test_suite_name(), test_info.name());
  3183. PrintFullTestCommentIfPresent(test_info);
  3184. if (GTEST_FLAG_GET(print_time)) {
  3185. printf(" (%s ms)\n",
  3186. internal::StreamableToString(test_info.result()->elapsed_time())
  3187. .c_str());
  3188. } else {
  3189. printf("\n");
  3190. }
  3191. fflush(stdout);
  3192. }
  3193. }
  3194. void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  3195. int /*iteration*/) {
  3196. ColoredPrintf(GTestColor::kGreen, "[==========] ");
  3197. printf("%s from %s ran.",
  3198. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  3199. FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
  3200. if (GTEST_FLAG_GET(print_time)) {
  3201. printf(" (%s ms total)",
  3202. internal::StreamableToString(unit_test.elapsed_time()).c_str());
  3203. }
  3204. printf("\n");
  3205. ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
  3206. printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  3207. const int skipped_test_count = unit_test.skipped_test_count();
  3208. if (skipped_test_count > 0) {
  3209. ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
  3210. printf("%s.\n", FormatTestCount(skipped_test_count).c_str());
  3211. }
  3212. int num_disabled = unit_test.reportable_disabled_test_count();
  3213. if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {
  3214. if (unit_test.Passed()) {
  3215. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
  3216. }
  3217. ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
  3218. num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
  3219. }
  3220. // Ensure that Google Test output is printed before, e.g., heapchecker output.
  3221. fflush(stdout);
  3222. }
  3223. // End BriefUnitTestResultPrinter
  3224. // class TestEventRepeater
  3225. //
  3226. // This class forwards events to other event listeners.
  3227. class TestEventRepeater : public TestEventListener {
  3228. public:
  3229. TestEventRepeater() : forwarding_enabled_(true) {}
  3230. ~TestEventRepeater() override;
  3231. void Append(TestEventListener* listener);
  3232. TestEventListener* Release(TestEventListener* listener);
  3233. // Controls whether events will be forwarded to listeners_. Set to false
  3234. // in death test child processes.
  3235. bool forwarding_enabled() const { return forwarding_enabled_; }
  3236. void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
  3237. void OnTestProgramStart(const UnitTest& unit_test) override;
  3238. void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
  3239. void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
  3240. void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
  3241. // Legacy API is deprecated but still available
  3242. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3243. void OnTestCaseStart(const TestSuite& parameter) override;
  3244. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3245. void OnTestSuiteStart(const TestSuite& parameter) override;
  3246. void OnTestStart(const TestInfo& test_info) override;
  3247. void OnTestDisabled(const TestInfo& test_info) override;
  3248. void OnTestPartResult(const TestPartResult& result) override;
  3249. void OnTestEnd(const TestInfo& test_info) override;
  3250. // Legacy API is deprecated but still available
  3251. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3252. void OnTestCaseEnd(const TestCase& parameter) override;
  3253. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3254. void OnTestSuiteEnd(const TestSuite& parameter) override;
  3255. void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
  3256. void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
  3257. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  3258. void OnTestProgramEnd(const UnitTest& unit_test) override;
  3259. private:
  3260. // Controls whether events will be forwarded to listeners_. Set to false
  3261. // in death test child processes.
  3262. bool forwarding_enabled_;
  3263. // The list of listeners that receive events.
  3264. std::vector<TestEventListener*> listeners_;
  3265. TestEventRepeater(const TestEventRepeater&) = delete;
  3266. TestEventRepeater& operator=(const TestEventRepeater&) = delete;
  3267. };
  3268. TestEventRepeater::~TestEventRepeater() {
  3269. ForEach(listeners_, Delete<TestEventListener>);
  3270. }
  3271. void TestEventRepeater::Append(TestEventListener* listener) {
  3272. listeners_.push_back(listener);
  3273. }
  3274. TestEventListener* TestEventRepeater::Release(TestEventListener* listener) {
  3275. for (size_t i = 0; i < listeners_.size(); ++i) {
  3276. if (listeners_[i] == listener) {
  3277. listeners_.erase(listeners_.begin() + static_cast<int>(i));
  3278. return listener;
  3279. }
  3280. }
  3281. return nullptr;
  3282. }
  3283. // Since most methods are very similar, use macros to reduce boilerplate.
  3284. // This defines a member that forwards the call to all listeners.
  3285. #define GTEST_REPEATER_METHOD_(Name, Type) \
  3286. void TestEventRepeater::Name(const Type& parameter) { \
  3287. if (forwarding_enabled_) { \
  3288. for (size_t i = 0; i < listeners_.size(); i++) { \
  3289. listeners_[i]->Name(parameter); \
  3290. } \
  3291. } \
  3292. }
  3293. // This defines a member that forwards the call to all listeners in reverse
  3294. // order.
  3295. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
  3296. void TestEventRepeater::Name(const Type& parameter) { \
  3297. if (forwarding_enabled_) { \
  3298. for (size_t i = listeners_.size(); i != 0; i--) { \
  3299. listeners_[i - 1]->Name(parameter); \
  3300. } \
  3301. } \
  3302. }
  3303. GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
  3304. GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
  3305. // Legacy API is deprecated but still available
  3306. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3307. GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
  3308. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3309. GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
  3310. GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
  3311. GTEST_REPEATER_METHOD_(OnTestDisabled, TestInfo)
  3312. GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
  3313. GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
  3314. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
  3315. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
  3316. GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
  3317. // Legacy API is deprecated but still available
  3318. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3319. GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
  3320. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3321. GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
  3322. GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
  3323. #undef GTEST_REPEATER_METHOD_
  3324. #undef GTEST_REVERSE_REPEATER_METHOD_
  3325. void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
  3326. int iteration) {
  3327. if (forwarding_enabled_) {
  3328. for (size_t i = 0; i < listeners_.size(); i++) {
  3329. listeners_[i]->OnTestIterationStart(unit_test, iteration);
  3330. }
  3331. }
  3332. }
  3333. void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
  3334. int iteration) {
  3335. if (forwarding_enabled_) {
  3336. for (size_t i = listeners_.size(); i > 0; i--) {
  3337. listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration);
  3338. }
  3339. }
  3340. }
  3341. // End TestEventRepeater
  3342. // This class generates an XML output file.
  3343. class XmlUnitTestResultPrinter : public EmptyTestEventListener {
  3344. public:
  3345. explicit XmlUnitTestResultPrinter(const char* output_file);
  3346. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  3347. void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);
  3348. // Prints an XML summary of all unit tests.
  3349. static void PrintXmlTestsList(std::ostream* stream,
  3350. const std::vector<TestSuite*>& test_suites);
  3351. private:
  3352. // Is c a whitespace character that is normalized to a space character
  3353. // when it appears in an XML attribute value?
  3354. static bool IsNormalizableWhitespace(unsigned char c) {
  3355. return c == '\t' || c == '\n' || c == '\r';
  3356. }
  3357. // May c appear in a well-formed XML document?
  3358. // https://www.w3.org/TR/REC-xml/#charsets
  3359. static bool IsValidXmlCharacter(unsigned char c) {
  3360. return IsNormalizableWhitespace(c) || c >= 0x20;
  3361. }
  3362. // Returns an XML-escaped copy of the input string str. If
  3363. // is_attribute is true, the text is meant to appear as an attribute
  3364. // value, and normalizable whitespace is preserved by replacing it
  3365. // with character references.
  3366. static std::string EscapeXml(const std::string& str, bool is_attribute);
  3367. // Returns the given string with all characters invalid in XML removed.
  3368. static std::string RemoveInvalidXmlCharacters(const std::string& str);
  3369. // Convenience wrapper around EscapeXml when str is an attribute value.
  3370. static std::string EscapeXmlAttribute(const std::string& str) {
  3371. return EscapeXml(str, true);
  3372. }
  3373. // Convenience wrapper around EscapeXml when str is not an attribute value.
  3374. static std::string EscapeXmlText(const char* str) {
  3375. return EscapeXml(str, false);
  3376. }
  3377. // Verifies that the given attribute belongs to the given element and
  3378. // streams the attribute as XML.
  3379. static void OutputXmlAttribute(std::ostream* stream,
  3380. const std::string& element_name,
  3381. const std::string& name,
  3382. const std::string& value);
  3383. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  3384. static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
  3385. // Streams a test suite XML stanza containing the given test result.
  3386. //
  3387. // Requires: result.Failed()
  3388. static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
  3389. const TestResult& result);
  3390. // Streams an XML representation of a TestResult object.
  3391. static void OutputXmlTestResult(::std::ostream* stream,
  3392. const TestResult& result);
  3393. // Streams an XML representation of a TestInfo object.
  3394. static void OutputXmlTestInfo(::std::ostream* stream,
  3395. const char* test_suite_name,
  3396. const TestInfo& test_info);
  3397. // Prints an XML representation of a TestSuite object
  3398. static void PrintXmlTestSuite(::std::ostream* stream,
  3399. const TestSuite& test_suite);
  3400. // Prints an XML summary of unit_test to output stream out.
  3401. static void PrintXmlUnitTest(::std::ostream* stream,
  3402. const UnitTest& unit_test);
  3403. // Produces a string representing the test properties in a result as space
  3404. // delimited XML attributes based on the property key="value" pairs.
  3405. // When the std::string is not empty, it includes a space at the beginning,
  3406. // to delimit this attribute from prior attributes.
  3407. static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
  3408. // Streams an XML representation of the test properties of a TestResult
  3409. // object.
  3410. static void OutputXmlTestProperties(std::ostream* stream,
  3411. const TestResult& result);
  3412. // The output file.
  3413. const std::string output_file_;
  3414. XmlUnitTestResultPrinter(const XmlUnitTestResultPrinter&) = delete;
  3415. XmlUnitTestResultPrinter& operator=(const XmlUnitTestResultPrinter&) = delete;
  3416. };
  3417. // Creates a new XmlUnitTestResultPrinter.
  3418. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
  3419. : output_file_(output_file) {
  3420. if (output_file_.empty()) {
  3421. GTEST_LOG_(FATAL) << "XML output file may not be null";
  3422. }
  3423. }
  3424. // Called after the unit test ends.
  3425. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  3426. int /*iteration*/) {
  3427. FILE* xmlout = OpenFileForWriting(output_file_);
  3428. std::stringstream stream;
  3429. PrintXmlUnitTest(&stream, unit_test);
  3430. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  3431. fclose(xmlout);
  3432. }
  3433. void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
  3434. const std::vector<TestSuite*>& test_suites) {
  3435. FILE* xmlout = OpenFileForWriting(output_file_);
  3436. std::stringstream stream;
  3437. PrintXmlTestsList(&stream, test_suites);
  3438. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  3439. fclose(xmlout);
  3440. }
  3441. // Returns an XML-escaped copy of the input string str. If is_attribute
  3442. // is true, the text is meant to appear as an attribute value, and
  3443. // normalizable whitespace is preserved by replacing it with character
  3444. // references.
  3445. //
  3446. // Invalid XML characters in str, if any, are stripped from the output.
  3447. // It is expected that most, if not all, of the text processed by this
  3448. // module will consist of ordinary English text.
  3449. // If this module is ever modified to produce version 1.1 XML output,
  3450. // most invalid characters can be retained using character references.
  3451. std::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str,
  3452. bool is_attribute) {
  3453. Message m;
  3454. for (size_t i = 0; i < str.size(); ++i) {
  3455. const char ch = str[i];
  3456. switch (ch) {
  3457. case '<':
  3458. m << "&lt;";
  3459. break;
  3460. case '>':
  3461. m << "&gt;";
  3462. break;
  3463. case '&':
  3464. m << "&amp;";
  3465. break;
  3466. case '\'':
  3467. if (is_attribute)
  3468. m << "&apos;";
  3469. else
  3470. m << '\'';
  3471. break;
  3472. case '"':
  3473. if (is_attribute)
  3474. m << "&quot;";
  3475. else
  3476. m << '"';
  3477. break;
  3478. default:
  3479. if (IsValidXmlCharacter(static_cast<unsigned char>(ch))) {
  3480. if (is_attribute &&
  3481. IsNormalizableWhitespace(static_cast<unsigned char>(ch)))
  3482. m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
  3483. << ";";
  3484. else
  3485. m << ch;
  3486. }
  3487. break;
  3488. }
  3489. }
  3490. return m.GetString();
  3491. }
  3492. // Returns the given string with all characters invalid in XML removed.
  3493. // Currently invalid characters are dropped from the string. An
  3494. // alternative is to replace them with certain characters such as . or ?.
  3495. std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
  3496. const std::string& str) {
  3497. std::string output;
  3498. output.reserve(str.size());
  3499. for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
  3500. if (IsValidXmlCharacter(static_cast<unsigned char>(*it)))
  3501. output.push_back(*it);
  3502. return output;
  3503. }
  3504. // The following routines generate an XML representation of a UnitTest
  3505. // object.
  3506. //
  3507. // This is how Google Test concepts map to the DTD:
  3508. //
  3509. // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
  3510. // <testsuite name="testcase-name"> <-- corresponds to a TestSuite object
  3511. // <testcase name="test-name"> <-- corresponds to a TestInfo object
  3512. // <failure message="...">...</failure>
  3513. // <failure message="...">...</failure>
  3514. // <failure message="...">...</failure>
  3515. // <-- individual assertion failures
  3516. // </testcase>
  3517. // </testsuite>
  3518. // </testsuites>
  3519. // Formats the given time in milliseconds as seconds.
  3520. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
  3521. ::std::stringstream ss;
  3522. ss << (static_cast<double>(ms) * 1e-3);
  3523. return ss.str();
  3524. }
  3525. static bool PortableLocaltime(time_t seconds, struct tm* out) {
  3526. #if defined(_MSC_VER)
  3527. return localtime_s(out, &seconds) == 0;
  3528. #elif defined(__MINGW32__) || defined(__MINGW64__)
  3529. // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
  3530. // Windows' localtime(), which has a thread-local tm buffer.
  3531. struct tm* tm_ptr = localtime(&seconds); // NOLINT
  3532. if (tm_ptr == nullptr) return false;
  3533. *out = *tm_ptr;
  3534. return true;
  3535. #elif defined(__STDC_LIB_EXT1__)
  3536. // Uses localtime_s when available as localtime_r is only available from
  3537. // C23 standard.
  3538. return localtime_s(&seconds, out) != nullptr;
  3539. #else
  3540. return localtime_r(&seconds, out) != nullptr;
  3541. #endif
  3542. }
  3543. // Converts the given epoch time in milliseconds to a date string in the ISO
  3544. // 8601 format, without the timezone information.
  3545. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
  3546. struct tm time_struct;
  3547. if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  3548. return "";
  3549. // YYYY-MM-DDThh:mm:ss.sss
  3550. return StreamableToString(time_struct.tm_year + 1900) + "-" +
  3551. String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  3552. String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  3553. String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  3554. String::FormatIntWidth2(time_struct.tm_min) + ":" +
  3555. String::FormatIntWidth2(time_struct.tm_sec) + "." +
  3556. String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);
  3557. }
  3558. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  3559. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
  3560. const char* data) {
  3561. const char* segment = data;
  3562. *stream << "<![CDATA[";
  3563. for (;;) {
  3564. const char* const next_segment = strstr(segment, "]]>");
  3565. if (next_segment != nullptr) {
  3566. stream->write(segment,
  3567. static_cast<std::streamsize>(next_segment - segment));
  3568. *stream << "]]>]]&gt;<![CDATA[";
  3569. segment = next_segment + strlen("]]>");
  3570. } else {
  3571. *stream << segment;
  3572. break;
  3573. }
  3574. }
  3575. *stream << "]]>";
  3576. }
  3577. void XmlUnitTestResultPrinter::OutputXmlAttribute(
  3578. std::ostream* stream, const std::string& element_name,
  3579. const std::string& name, const std::string& value) {
  3580. const std::vector<std::string>& allowed_names =
  3581. GetReservedOutputAttributesForElement(element_name);
  3582. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  3583. allowed_names.end())
  3584. << "Attribute " << name << " is not allowed for element <" << element_name
  3585. << ">.";
  3586. *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
  3587. }
  3588. // Streams a test suite XML stanza containing the given test result.
  3589. void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
  3590. ::std::ostream* stream, const TestResult& result) {
  3591. // Output the boilerplate for a minimal test suite with one test.
  3592. *stream << " <testsuite";
  3593. OutputXmlAttribute(stream, "testsuite", "name", "NonTestSuiteFailure");
  3594. OutputXmlAttribute(stream, "testsuite", "tests", "1");
  3595. OutputXmlAttribute(stream, "testsuite", "failures", "1");
  3596. OutputXmlAttribute(stream, "testsuite", "disabled", "0");
  3597. OutputXmlAttribute(stream, "testsuite", "skipped", "0");
  3598. OutputXmlAttribute(stream, "testsuite", "errors", "0");
  3599. OutputXmlAttribute(stream, "testsuite", "time",
  3600. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  3601. OutputXmlAttribute(
  3602. stream, "testsuite", "timestamp",
  3603. FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
  3604. *stream << ">";
  3605. // Output the boilerplate for a minimal test case with a single test.
  3606. *stream << " <testcase";
  3607. OutputXmlAttribute(stream, "testcase", "name", "");
  3608. OutputXmlAttribute(stream, "testcase", "status", "run");
  3609. OutputXmlAttribute(stream, "testcase", "result", "completed");
  3610. OutputXmlAttribute(stream, "testcase", "classname", "");
  3611. OutputXmlAttribute(stream, "testcase", "time",
  3612. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  3613. OutputXmlAttribute(
  3614. stream, "testcase", "timestamp",
  3615. FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
  3616. // Output the actual test result.
  3617. OutputXmlTestResult(stream, result);
  3618. // Complete the test suite.
  3619. *stream << " </testsuite>\n";
  3620. }
  3621. // Prints an XML representation of a TestInfo object.
  3622. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
  3623. const char* test_suite_name,
  3624. const TestInfo& test_info) {
  3625. const TestResult& result = *test_info.result();
  3626. const std::string kTestsuite = "testcase";
  3627. if (test_info.is_in_another_shard()) {
  3628. return;
  3629. }
  3630. *stream << " <testcase";
  3631. OutputXmlAttribute(stream, kTestsuite, "name", test_info.name());
  3632. if (test_info.value_param() != nullptr) {
  3633. OutputXmlAttribute(stream, kTestsuite, "value_param",
  3634. test_info.value_param());
  3635. }
  3636. if (test_info.type_param() != nullptr) {
  3637. OutputXmlAttribute(stream, kTestsuite, "type_param",
  3638. test_info.type_param());
  3639. }
  3640. OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
  3641. OutputXmlAttribute(stream, kTestsuite, "line",
  3642. StreamableToString(test_info.line()));
  3643. if (GTEST_FLAG_GET(list_tests)) {
  3644. *stream << " />\n";
  3645. return;
  3646. }
  3647. OutputXmlAttribute(stream, kTestsuite, "status",
  3648. test_info.should_run() ? "run" : "notrun");
  3649. OutputXmlAttribute(stream, kTestsuite, "result",
  3650. test_info.should_run()
  3651. ? (result.Skipped() ? "skipped" : "completed")
  3652. : "suppressed");
  3653. OutputXmlAttribute(stream, kTestsuite, "time",
  3654. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  3655. OutputXmlAttribute(
  3656. stream, kTestsuite, "timestamp",
  3657. FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
  3658. OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
  3659. OutputXmlTestResult(stream, result);
  3660. }
  3661. void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
  3662. const TestResult& result) {
  3663. int failures = 0;
  3664. int skips = 0;
  3665. for (int i = 0; i < result.total_part_count(); ++i) {
  3666. const TestPartResult& part = result.GetTestPartResult(i);
  3667. if (part.failed()) {
  3668. if (++failures == 1 && skips == 0) {
  3669. *stream << ">\n";
  3670. }
  3671. const std::string location =
  3672. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  3673. part.line_number());
  3674. const std::string summary = location + "\n" + part.summary();
  3675. *stream << " <failure message=\"" << EscapeXmlAttribute(summary)
  3676. << "\" type=\"\">";
  3677. const std::string detail = location + "\n" + part.message();
  3678. OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
  3679. *stream << "</failure>\n";
  3680. } else if (part.skipped()) {
  3681. if (++skips == 1 && failures == 0) {
  3682. *stream << ">\n";
  3683. }
  3684. const std::string location =
  3685. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  3686. part.line_number());
  3687. const std::string summary = location + "\n" + part.summary();
  3688. *stream << " <skipped message=\""
  3689. << EscapeXmlAttribute(summary.c_str()) << "\">";
  3690. const std::string detail = location + "\n" + part.message();
  3691. OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
  3692. *stream << "</skipped>\n";
  3693. }
  3694. }
  3695. if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
  3696. *stream << " />\n";
  3697. } else {
  3698. if (failures == 0 && skips == 0) {
  3699. *stream << ">\n";
  3700. }
  3701. OutputXmlTestProperties(stream, result);
  3702. *stream << " </testcase>\n";
  3703. }
  3704. }
  3705. // Prints an XML representation of a TestSuite object
  3706. void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
  3707. const TestSuite& test_suite) {
  3708. const std::string kTestsuite = "testsuite";
  3709. *stream << " <" << kTestsuite;
  3710. OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
  3711. OutputXmlAttribute(stream, kTestsuite, "tests",
  3712. StreamableToString(test_suite.reportable_test_count()));
  3713. if (!GTEST_FLAG_GET(list_tests)) {
  3714. OutputXmlAttribute(stream, kTestsuite, "failures",
  3715. StreamableToString(test_suite.failed_test_count()));
  3716. OutputXmlAttribute(
  3717. stream, kTestsuite, "disabled",
  3718. StreamableToString(test_suite.reportable_disabled_test_count()));
  3719. OutputXmlAttribute(stream, kTestsuite, "skipped",
  3720. StreamableToString(test_suite.skipped_test_count()));
  3721. OutputXmlAttribute(stream, kTestsuite, "errors", "0");
  3722. OutputXmlAttribute(stream, kTestsuite, "time",
  3723. FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
  3724. OutputXmlAttribute(
  3725. stream, kTestsuite, "timestamp",
  3726. FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp()));
  3727. *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
  3728. }
  3729. *stream << ">\n";
  3730. for (int i = 0; i < test_suite.total_test_count(); ++i) {
  3731. if (test_suite.GetTestInfo(i)->is_reportable())
  3732. OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
  3733. }
  3734. *stream << " </" << kTestsuite << ">\n";
  3735. }
  3736. // Prints an XML summary of unit_test to output stream out.
  3737. void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
  3738. const UnitTest& unit_test) {
  3739. const std::string kTestsuites = "testsuites";
  3740. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  3741. *stream << "<" << kTestsuites;
  3742. OutputXmlAttribute(stream, kTestsuites, "tests",
  3743. StreamableToString(unit_test.reportable_test_count()));
  3744. OutputXmlAttribute(stream, kTestsuites, "failures",
  3745. StreamableToString(unit_test.failed_test_count()));
  3746. OutputXmlAttribute(
  3747. stream, kTestsuites, "disabled",
  3748. StreamableToString(unit_test.reportable_disabled_test_count()));
  3749. OutputXmlAttribute(stream, kTestsuites, "errors", "0");
  3750. OutputXmlAttribute(stream, kTestsuites, "time",
  3751. FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
  3752. OutputXmlAttribute(
  3753. stream, kTestsuites, "timestamp",
  3754. FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
  3755. if (GTEST_FLAG_GET(shuffle)) {
  3756. OutputXmlAttribute(stream, kTestsuites, "random_seed",
  3757. StreamableToString(unit_test.random_seed()));
  3758. }
  3759. *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
  3760. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  3761. *stream << ">\n";
  3762. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  3763. if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
  3764. PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
  3765. }
  3766. // If there was a test failure outside of one of the test suites (like in a
  3767. // test environment) include that in the output.
  3768. if (unit_test.ad_hoc_test_result().Failed()) {
  3769. OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
  3770. }
  3771. *stream << "</" << kTestsuites << ">\n";
  3772. }
  3773. void XmlUnitTestResultPrinter::PrintXmlTestsList(
  3774. std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
  3775. const std::string kTestsuites = "testsuites";
  3776. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  3777. *stream << "<" << kTestsuites;
  3778. int total_tests = 0;
  3779. for (auto test_suite : test_suites) {
  3780. total_tests += test_suite->total_test_count();
  3781. }
  3782. OutputXmlAttribute(stream, kTestsuites, "tests",
  3783. StreamableToString(total_tests));
  3784. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  3785. *stream << ">\n";
  3786. for (auto test_suite : test_suites) {
  3787. PrintXmlTestSuite(stream, *test_suite);
  3788. }
  3789. *stream << "</" << kTestsuites << ">\n";
  3790. }
  3791. // Produces a string representing the test properties in a result as space
  3792. // delimited XML attributes based on the property key="value" pairs.
  3793. std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
  3794. const TestResult& result) {
  3795. Message attributes;
  3796. for (int i = 0; i < result.test_property_count(); ++i) {
  3797. const TestProperty& property = result.GetTestProperty(i);
  3798. attributes << " " << property.key() << "="
  3799. << "\"" << EscapeXmlAttribute(property.value()) << "\"";
  3800. }
  3801. return attributes.GetString();
  3802. }
  3803. void XmlUnitTestResultPrinter::OutputXmlTestProperties(
  3804. std::ostream* stream, const TestResult& result) {
  3805. const std::string kProperties = "properties";
  3806. const std::string kProperty = "property";
  3807. if (result.test_property_count() <= 0) {
  3808. return;
  3809. }
  3810. *stream << " <" << kProperties << ">\n";
  3811. for (int i = 0; i < result.test_property_count(); ++i) {
  3812. const TestProperty& property = result.GetTestProperty(i);
  3813. *stream << " <" << kProperty;
  3814. *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
  3815. *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
  3816. *stream << "/>\n";
  3817. }
  3818. *stream << " </" << kProperties << ">\n";
  3819. }
  3820. // End XmlUnitTestResultPrinter
  3821. // This class generates an JSON output file.
  3822. class JsonUnitTestResultPrinter : public EmptyTestEventListener {
  3823. public:
  3824. explicit JsonUnitTestResultPrinter(const char* output_file);
  3825. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  3826. // Prints an JSON summary of all unit tests.
  3827. static void PrintJsonTestList(::std::ostream* stream,
  3828. const std::vector<TestSuite*>& test_suites);
  3829. private:
  3830. // Returns an JSON-escaped copy of the input string str.
  3831. static std::string EscapeJson(const std::string& str);
  3832. //// Verifies that the given attribute belongs to the given element and
  3833. //// streams the attribute as JSON.
  3834. static void OutputJsonKey(std::ostream* stream,
  3835. const std::string& element_name,
  3836. const std::string& name, const std::string& value,
  3837. const std::string& indent, bool comma = true);
  3838. static void OutputJsonKey(std::ostream* stream,
  3839. const std::string& element_name,
  3840. const std::string& name, int value,
  3841. const std::string& indent, bool comma = true);
  3842. // Streams a test suite JSON stanza containing the given test result.
  3843. //
  3844. // Requires: result.Failed()
  3845. static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
  3846. const TestResult& result);
  3847. // Streams a JSON representation of a TestResult object.
  3848. static void OutputJsonTestResult(::std::ostream* stream,
  3849. const TestResult& result);
  3850. // Streams a JSON representation of a TestInfo object.
  3851. static void OutputJsonTestInfo(::std::ostream* stream,
  3852. const char* test_suite_name,
  3853. const TestInfo& test_info);
  3854. // Prints a JSON representation of a TestSuite object
  3855. static void PrintJsonTestSuite(::std::ostream* stream,
  3856. const TestSuite& test_suite);
  3857. // Prints a JSON summary of unit_test to output stream out.
  3858. static void PrintJsonUnitTest(::std::ostream* stream,
  3859. const UnitTest& unit_test);
  3860. // Produces a string representing the test properties in a result as
  3861. // a JSON dictionary.
  3862. static std::string TestPropertiesAsJson(const TestResult& result,
  3863. const std::string& indent);
  3864. // The output file.
  3865. const std::string output_file_;
  3866. JsonUnitTestResultPrinter(const JsonUnitTestResultPrinter&) = delete;
  3867. JsonUnitTestResultPrinter& operator=(const JsonUnitTestResultPrinter&) =
  3868. delete;
  3869. };
  3870. // Creates a new JsonUnitTestResultPrinter.
  3871. JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
  3872. : output_file_(output_file) {
  3873. if (output_file_.empty()) {
  3874. GTEST_LOG_(FATAL) << "JSON output file may not be null";
  3875. }
  3876. }
  3877. void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  3878. int /*iteration*/) {
  3879. FILE* jsonout = OpenFileForWriting(output_file_);
  3880. std::stringstream stream;
  3881. PrintJsonUnitTest(&stream, unit_test);
  3882. fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
  3883. fclose(jsonout);
  3884. }
  3885. // Returns an JSON-escaped copy of the input string str.
  3886. std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
  3887. Message m;
  3888. for (size_t i = 0; i < str.size(); ++i) {
  3889. const char ch = str[i];
  3890. switch (ch) {
  3891. case '\\':
  3892. case '"':
  3893. case '/':
  3894. m << '\\' << ch;
  3895. break;
  3896. case '\b':
  3897. m << "\\b";
  3898. break;
  3899. case '\t':
  3900. m << "\\t";
  3901. break;
  3902. case '\n':
  3903. m << "\\n";
  3904. break;
  3905. case '\f':
  3906. m << "\\f";
  3907. break;
  3908. case '\r':
  3909. m << "\\r";
  3910. break;
  3911. default:
  3912. if (ch < ' ') {
  3913. m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
  3914. } else {
  3915. m << ch;
  3916. }
  3917. break;
  3918. }
  3919. }
  3920. return m.GetString();
  3921. }
  3922. // The following routines generate an JSON representation of a UnitTest
  3923. // object.
  3924. // Formats the given time in milliseconds as seconds.
  3925. static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
  3926. ::std::stringstream ss;
  3927. ss << (static_cast<double>(ms) * 1e-3) << "s";
  3928. return ss.str();
  3929. }
  3930. // Converts the given epoch time in milliseconds to a date string in the
  3931. // RFC3339 format, without the timezone information.
  3932. static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
  3933. struct tm time_struct;
  3934. if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  3935. return "";
  3936. // YYYY-MM-DDThh:mm:ss
  3937. return StreamableToString(time_struct.tm_year + 1900) + "-" +
  3938. String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  3939. String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  3940. String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  3941. String::FormatIntWidth2(time_struct.tm_min) + ":" +
  3942. String::FormatIntWidth2(time_struct.tm_sec) + "Z";
  3943. }
  3944. static inline std::string Indent(size_t width) {
  3945. return std::string(width, ' ');
  3946. }
  3947. void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream,
  3948. const std::string& element_name,
  3949. const std::string& name,
  3950. const std::string& value,
  3951. const std::string& indent,
  3952. bool comma) {
  3953. const std::vector<std::string>& allowed_names =
  3954. GetReservedOutputAttributesForElement(element_name);
  3955. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  3956. allowed_names.end())
  3957. << "Key \"" << name << "\" is not allowed for value \"" << element_name
  3958. << "\".";
  3959. *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
  3960. if (comma) *stream << ",\n";
  3961. }
  3962. void JsonUnitTestResultPrinter::OutputJsonKey(
  3963. std::ostream* stream, const std::string& element_name,
  3964. const std::string& name, int value, const std::string& indent, bool comma) {
  3965. const std::vector<std::string>& allowed_names =
  3966. GetReservedOutputAttributesForElement(element_name);
  3967. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  3968. allowed_names.end())
  3969. << "Key \"" << name << "\" is not allowed for value \"" << element_name
  3970. << "\".";
  3971. *stream << indent << "\"" << name << "\": " << StreamableToString(value);
  3972. if (comma) *stream << ",\n";
  3973. }
  3974. // Streams a test suite JSON stanza containing the given test result.
  3975. void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
  3976. ::std::ostream* stream, const TestResult& result) {
  3977. // Output the boilerplate for a new test suite.
  3978. *stream << Indent(4) << "{\n";
  3979. OutputJsonKey(stream, "testsuite", "name", "NonTestSuiteFailure", Indent(6));
  3980. OutputJsonKey(stream, "testsuite", "tests", 1, Indent(6));
  3981. if (!GTEST_FLAG_GET(list_tests)) {
  3982. OutputJsonKey(stream, "testsuite", "failures", 1, Indent(6));
  3983. OutputJsonKey(stream, "testsuite", "disabled", 0, Indent(6));
  3984. OutputJsonKey(stream, "testsuite", "skipped", 0, Indent(6));
  3985. OutputJsonKey(stream, "testsuite", "errors", 0, Indent(6));
  3986. OutputJsonKey(stream, "testsuite", "time",
  3987. FormatTimeInMillisAsDuration(result.elapsed_time()),
  3988. Indent(6));
  3989. OutputJsonKey(stream, "testsuite", "timestamp",
  3990. FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
  3991. Indent(6));
  3992. }
  3993. *stream << Indent(6) << "\"testsuite\": [\n";
  3994. // Output the boilerplate for a new test case.
  3995. *stream << Indent(8) << "{\n";
  3996. OutputJsonKey(stream, "testcase", "name", "", Indent(10));
  3997. OutputJsonKey(stream, "testcase", "status", "RUN", Indent(10));
  3998. OutputJsonKey(stream, "testcase", "result", "COMPLETED", Indent(10));
  3999. OutputJsonKey(stream, "testcase", "timestamp",
  4000. FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
  4001. Indent(10));
  4002. OutputJsonKey(stream, "testcase", "time",
  4003. FormatTimeInMillisAsDuration(result.elapsed_time()),
  4004. Indent(10));
  4005. OutputJsonKey(stream, "testcase", "classname", "", Indent(10), false);
  4006. *stream << TestPropertiesAsJson(result, Indent(10));
  4007. // Output the actual test result.
  4008. OutputJsonTestResult(stream, result);
  4009. // Finish the test suite.
  4010. *stream << "\n" << Indent(6) << "]\n" << Indent(4) << "}";
  4011. }
  4012. // Prints a JSON representation of a TestInfo object.
  4013. void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
  4014. const char* test_suite_name,
  4015. const TestInfo& test_info) {
  4016. const TestResult& result = *test_info.result();
  4017. const std::string kTestsuite = "testcase";
  4018. const std::string kIndent = Indent(10);
  4019. *stream << Indent(8) << "{\n";
  4020. OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent);
  4021. if (test_info.value_param() != nullptr) {
  4022. OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(),
  4023. kIndent);
  4024. }
  4025. if (test_info.type_param() != nullptr) {
  4026. OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
  4027. kIndent);
  4028. }
  4029. OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
  4030. OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
  4031. if (GTEST_FLAG_GET(list_tests)) {
  4032. *stream << "\n" << Indent(8) << "}";
  4033. return;
  4034. } else {
  4035. *stream << ",\n";
  4036. }
  4037. OutputJsonKey(stream, kTestsuite, "status",
  4038. test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
  4039. OutputJsonKey(stream, kTestsuite, "result",
  4040. test_info.should_run()
  4041. ? (result.Skipped() ? "SKIPPED" : "COMPLETED")
  4042. : "SUPPRESSED",
  4043. kIndent);
  4044. OutputJsonKey(stream, kTestsuite, "timestamp",
  4045. FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
  4046. kIndent);
  4047. OutputJsonKey(stream, kTestsuite, "time",
  4048. FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
  4049. OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent,
  4050. false);
  4051. *stream << TestPropertiesAsJson(result, kIndent);
  4052. OutputJsonTestResult(stream, result);
  4053. }
  4054. void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
  4055. const TestResult& result) {
  4056. const std::string kIndent = Indent(10);
  4057. int failures = 0;
  4058. for (int i = 0; i < result.total_part_count(); ++i) {
  4059. const TestPartResult& part = result.GetTestPartResult(i);
  4060. if (part.failed()) {
  4061. *stream << ",\n";
  4062. if (++failures == 1) {
  4063. *stream << kIndent << "\""
  4064. << "failures"
  4065. << "\": [\n";
  4066. }
  4067. const std::string location =
  4068. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  4069. part.line_number());
  4070. const std::string message = EscapeJson(location + "\n" + part.message());
  4071. *stream << kIndent << " {\n"
  4072. << kIndent << " \"failure\": \"" << message << "\",\n"
  4073. << kIndent << " \"type\": \"\"\n"
  4074. << kIndent << " }";
  4075. }
  4076. }
  4077. if (failures > 0) *stream << "\n" << kIndent << "]";
  4078. *stream << "\n" << Indent(8) << "}";
  4079. }
  4080. // Prints an JSON representation of a TestSuite object
  4081. void JsonUnitTestResultPrinter::PrintJsonTestSuite(
  4082. std::ostream* stream, const TestSuite& test_suite) {
  4083. const std::string kTestsuite = "testsuite";
  4084. const std::string kIndent = Indent(6);
  4085. *stream << Indent(4) << "{\n";
  4086. OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
  4087. OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
  4088. kIndent);
  4089. if (!GTEST_FLAG_GET(list_tests)) {
  4090. OutputJsonKey(stream, kTestsuite, "failures",
  4091. test_suite.failed_test_count(), kIndent);
  4092. OutputJsonKey(stream, kTestsuite, "disabled",
  4093. test_suite.reportable_disabled_test_count(), kIndent);
  4094. OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
  4095. OutputJsonKey(
  4096. stream, kTestsuite, "timestamp",
  4097. FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()),
  4098. kIndent);
  4099. OutputJsonKey(stream, kTestsuite, "time",
  4100. FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
  4101. kIndent, false);
  4102. *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
  4103. << ",\n";
  4104. }
  4105. *stream << kIndent << "\"" << kTestsuite << "\": [\n";
  4106. bool comma = false;
  4107. for (int i = 0; i < test_suite.total_test_count(); ++i) {
  4108. if (test_suite.GetTestInfo(i)->is_reportable()) {
  4109. if (comma) {
  4110. *stream << ",\n";
  4111. } else {
  4112. comma = true;
  4113. }
  4114. OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
  4115. }
  4116. }
  4117. *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
  4118. }
  4119. // Prints a JSON summary of unit_test to output stream out.
  4120. void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
  4121. const UnitTest& unit_test) {
  4122. const std::string kTestsuites = "testsuites";
  4123. const std::string kIndent = Indent(2);
  4124. *stream << "{\n";
  4125. OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
  4126. kIndent);
  4127. OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
  4128. kIndent);
  4129. OutputJsonKey(stream, kTestsuites, "disabled",
  4130. unit_test.reportable_disabled_test_count(), kIndent);
  4131. OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
  4132. if (GTEST_FLAG_GET(shuffle)) {
  4133. OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
  4134. kIndent);
  4135. }
  4136. OutputJsonKey(stream, kTestsuites, "timestamp",
  4137. FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
  4138. kIndent);
  4139. OutputJsonKey(stream, kTestsuites, "time",
  4140. FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
  4141. false);
  4142. *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
  4143. << ",\n";
  4144. OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  4145. *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  4146. bool comma = false;
  4147. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  4148. if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
  4149. if (comma) {
  4150. *stream << ",\n";
  4151. } else {
  4152. comma = true;
  4153. }
  4154. PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
  4155. }
  4156. }
  4157. // If there was a test failure outside of one of the test suites (like in a
  4158. // test environment) include that in the output.
  4159. if (unit_test.ad_hoc_test_result().Failed()) {
  4160. OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
  4161. }
  4162. *stream << "\n"
  4163. << kIndent << "]\n"
  4164. << "}\n";
  4165. }
  4166. void JsonUnitTestResultPrinter::PrintJsonTestList(
  4167. std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
  4168. const std::string kTestsuites = "testsuites";
  4169. const std::string kIndent = Indent(2);
  4170. *stream << "{\n";
  4171. int total_tests = 0;
  4172. for (auto test_suite : test_suites) {
  4173. total_tests += test_suite->total_test_count();
  4174. }
  4175. OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
  4176. OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  4177. *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  4178. for (size_t i = 0; i < test_suites.size(); ++i) {
  4179. if (i != 0) {
  4180. *stream << ",\n";
  4181. }
  4182. PrintJsonTestSuite(stream, *test_suites[i]);
  4183. }
  4184. *stream << "\n"
  4185. << kIndent << "]\n"
  4186. << "}\n";
  4187. }
  4188. // Produces a string representing the test properties in a result as
  4189. // a JSON dictionary.
  4190. std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
  4191. const TestResult& result, const std::string& indent) {
  4192. Message attributes;
  4193. for (int i = 0; i < result.test_property_count(); ++i) {
  4194. const TestProperty& property = result.GetTestProperty(i);
  4195. attributes << ",\n"
  4196. << indent << "\"" << property.key() << "\": "
  4197. << "\"" << EscapeJson(property.value()) << "\"";
  4198. }
  4199. return attributes.GetString();
  4200. }
  4201. // End JsonUnitTestResultPrinter
  4202. #if GTEST_CAN_STREAM_RESULTS_
  4203. // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
  4204. // replaces them by "%xx" where xx is their hexadecimal value. For
  4205. // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
  4206. // in both time and space -- important as the input str may contain an
  4207. // arbitrarily long test failure message and stack trace.
  4208. std::string StreamingListener::UrlEncode(const char* str) {
  4209. std::string result;
  4210. result.reserve(strlen(str) + 1);
  4211. for (char ch = *str; ch != '\0'; ch = *++str) {
  4212. switch (ch) {
  4213. case '%':
  4214. case '=':
  4215. case '&':
  4216. case '\n':
  4217. result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
  4218. break;
  4219. default:
  4220. result.push_back(ch);
  4221. break;
  4222. }
  4223. }
  4224. return result;
  4225. }
  4226. void StreamingListener::SocketWriter::MakeConnection() {
  4227. GTEST_CHECK_(sockfd_ == -1)
  4228. << "MakeConnection() can't be called when there is already a connection.";
  4229. addrinfo hints;
  4230. memset(&hints, 0, sizeof(hints));
  4231. hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
  4232. hints.ai_socktype = SOCK_STREAM;
  4233. addrinfo* servinfo = nullptr;
  4234. // Use the getaddrinfo() to get a linked list of IP addresses for
  4235. // the given host name.
  4236. const int error_num =
  4237. getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
  4238. if (error_num != 0) {
  4239. GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
  4240. << gai_strerror(error_num);
  4241. }
  4242. // Loop through all the results and connect to the first we can.
  4243. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
  4244. cur_addr = cur_addr->ai_next) {
  4245. sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,
  4246. cur_addr->ai_protocol);
  4247. if (sockfd_ != -1) {
  4248. // Connect the client socket to the server socket.
  4249. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
  4250. close(sockfd_);
  4251. sockfd_ = -1;
  4252. }
  4253. }
  4254. }
  4255. freeaddrinfo(servinfo); // all done with this structure
  4256. if (sockfd_ == -1) {
  4257. GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
  4258. << host_name_ << ":" << port_num_;
  4259. }
  4260. }
  4261. // End of class Streaming Listener
  4262. #endif // GTEST_CAN_STREAM_RESULTS__
  4263. // class OsStackTraceGetter
  4264. const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
  4265. "... " GTEST_NAME_ " internal frames ...";
  4266. std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
  4267. GTEST_LOCK_EXCLUDED_(mutex_) {
  4268. #if GTEST_HAS_ABSL
  4269. std::string result;
  4270. if (max_depth <= 0) {
  4271. return result;
  4272. }
  4273. max_depth = std::min(max_depth, kMaxStackTraceDepth);
  4274. std::vector<void*> raw_stack(max_depth);
  4275. // Skips the frames requested by the caller, plus this function.
  4276. const int raw_stack_size =
  4277. absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
  4278. void* caller_frame = nullptr;
  4279. {
  4280. MutexLock lock(&mutex_);
  4281. caller_frame = caller_frame_;
  4282. }
  4283. for (int i = 0; i < raw_stack_size; ++i) {
  4284. if (raw_stack[i] == caller_frame &&
  4285. !GTEST_FLAG_GET(show_internal_stack_frames)) {
  4286. // Add a marker to the trace and stop adding frames.
  4287. absl::StrAppend(&result, kElidedFramesMarker, "\n");
  4288. break;
  4289. }
  4290. char tmp[1024];
  4291. const char* symbol = "(unknown)";
  4292. if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
  4293. symbol = tmp;
  4294. }
  4295. char line[1024];
  4296. snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
  4297. result += line;
  4298. }
  4299. return result;
  4300. #else // !GTEST_HAS_ABSL
  4301. static_cast<void>(max_depth);
  4302. static_cast<void>(skip_count);
  4303. return "";
  4304. #endif // GTEST_HAS_ABSL
  4305. }
  4306. void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
  4307. #if GTEST_HAS_ABSL
  4308. void* caller_frame = nullptr;
  4309. if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
  4310. caller_frame = nullptr;
  4311. }
  4312. MutexLock lock(&mutex_);
  4313. caller_frame_ = caller_frame;
  4314. #endif // GTEST_HAS_ABSL
  4315. }
  4316. // A helper class that creates the premature-exit file in its
  4317. // constructor and deletes the file in its destructor.
  4318. class ScopedPrematureExitFile {
  4319. public:
  4320. explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
  4321. : premature_exit_filepath_(
  4322. premature_exit_filepath ? premature_exit_filepath : "") {
  4323. // If a path to the premature-exit file is specified...
  4324. if (!premature_exit_filepath_.empty()) {
  4325. // create the file with a single "0" character in it. I/O
  4326. // errors are ignored as there's nothing better we can do and we
  4327. // don't want to fail the test because of this.
  4328. FILE* pfile = posix::FOpen(premature_exit_filepath_.c_str(), "w");
  4329. fwrite("0", 1, 1, pfile);
  4330. fclose(pfile);
  4331. }
  4332. }
  4333. ~ScopedPrematureExitFile() {
  4334. #if !defined GTEST_OS_ESP8266
  4335. if (!premature_exit_filepath_.empty()) {
  4336. int retval = remove(premature_exit_filepath_.c_str());
  4337. if (retval) {
  4338. GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
  4339. << premature_exit_filepath_ << "\" with error "
  4340. << retval;
  4341. }
  4342. }
  4343. #endif
  4344. }
  4345. private:
  4346. const std::string premature_exit_filepath_;
  4347. ScopedPrematureExitFile(const ScopedPrematureExitFile&) = delete;
  4348. ScopedPrematureExitFile& operator=(const ScopedPrematureExitFile&) = delete;
  4349. };
  4350. } // namespace internal
  4351. // class TestEventListeners
  4352. TestEventListeners::TestEventListeners()
  4353. : repeater_(new internal::TestEventRepeater()),
  4354. default_result_printer_(nullptr),
  4355. default_xml_generator_(nullptr) {}
  4356. TestEventListeners::~TestEventListeners() { delete repeater_; }
  4357. // Returns the standard listener responsible for the default console
  4358. // output. Can be removed from the listeners list to shut down default
  4359. // console output. Note that removing this object from the listener list
  4360. // with Release transfers its ownership to the user.
  4361. void TestEventListeners::Append(TestEventListener* listener) {
  4362. repeater_->Append(listener);
  4363. }
  4364. // Removes the given event listener from the list and returns it. It then
  4365. // becomes the caller's responsibility to delete the listener. Returns
  4366. // NULL if the listener is not found in the list.
  4367. TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
  4368. if (listener == default_result_printer_)
  4369. default_result_printer_ = nullptr;
  4370. else if (listener == default_xml_generator_)
  4371. default_xml_generator_ = nullptr;
  4372. return repeater_->Release(listener);
  4373. }
  4374. // Returns repeater that broadcasts the TestEventListener events to all
  4375. // subscribers.
  4376. TestEventListener* TestEventListeners::repeater() { return repeater_; }
  4377. // Sets the default_result_printer attribute to the provided listener.
  4378. // The listener is also added to the listener list and previous
  4379. // default_result_printer is removed from it and deleted. The listener can
  4380. // also be NULL in which case it will not be added to the list. Does
  4381. // nothing if the previous and the current listener objects are the same.
  4382. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
  4383. if (default_result_printer_ != listener) {
  4384. // It is an error to pass this method a listener that is already in the
  4385. // list.
  4386. delete Release(default_result_printer_);
  4387. default_result_printer_ = listener;
  4388. if (listener != nullptr) Append(listener);
  4389. }
  4390. }
  4391. // Sets the default_xml_generator attribute to the provided listener. The
  4392. // listener is also added to the listener list and previous
  4393. // default_xml_generator is removed from it and deleted. The listener can
  4394. // also be NULL in which case it will not be added to the list. Does
  4395. // nothing if the previous and the current listener objects are the same.
  4396. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
  4397. if (default_xml_generator_ != listener) {
  4398. // It is an error to pass this method a listener that is already in the
  4399. // list.
  4400. delete Release(default_xml_generator_);
  4401. default_xml_generator_ = listener;
  4402. if (listener != nullptr) Append(listener);
  4403. }
  4404. }
  4405. // Controls whether events will be forwarded by the repeater to the
  4406. // listeners in the list.
  4407. bool TestEventListeners::EventForwardingEnabled() const {
  4408. return repeater_->forwarding_enabled();
  4409. }
  4410. void TestEventListeners::SuppressEventForwarding() {
  4411. repeater_->set_forwarding_enabled(false);
  4412. }
  4413. // class UnitTest
  4414. // Gets the singleton UnitTest object. The first time this method is
  4415. // called, a UnitTest object is constructed and returned. Consecutive
  4416. // calls will return the same object.
  4417. //
  4418. // We don't protect this under mutex_ as a user is not supposed to
  4419. // call this before main() starts, from which point on the return
  4420. // value will never change.
  4421. UnitTest* UnitTest::GetInstance() {
  4422. // CodeGear C++Builder insists on a public destructor for the
  4423. // default implementation. Use this implementation to keep good OO
  4424. // design with private destructor.
  4425. #if defined(__BORLANDC__)
  4426. static UnitTest* const instance = new UnitTest;
  4427. return instance;
  4428. #else
  4429. static UnitTest instance;
  4430. return &instance;
  4431. #endif // defined(__BORLANDC__)
  4432. }
  4433. // Gets the number of successful test suites.
  4434. int UnitTest::successful_test_suite_count() const {
  4435. return impl()->successful_test_suite_count();
  4436. }
  4437. // Gets the number of failed test suites.
  4438. int UnitTest::failed_test_suite_count() const {
  4439. return impl()->failed_test_suite_count();
  4440. }
  4441. // Gets the number of all test suites.
  4442. int UnitTest::total_test_suite_count() const {
  4443. return impl()->total_test_suite_count();
  4444. }
  4445. // Gets the number of all test suites that contain at least one test
  4446. // that should run.
  4447. int UnitTest::test_suite_to_run_count() const {
  4448. return impl()->test_suite_to_run_count();
  4449. }
  4450. // Legacy API is deprecated but still available
  4451. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4452. int UnitTest::successful_test_case_count() const {
  4453. return impl()->successful_test_suite_count();
  4454. }
  4455. int UnitTest::failed_test_case_count() const {
  4456. return impl()->failed_test_suite_count();
  4457. }
  4458. int UnitTest::total_test_case_count() const {
  4459. return impl()->total_test_suite_count();
  4460. }
  4461. int UnitTest::test_case_to_run_count() const {
  4462. return impl()->test_suite_to_run_count();
  4463. }
  4464. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4465. // Gets the number of successful tests.
  4466. int UnitTest::successful_test_count() const {
  4467. return impl()->successful_test_count();
  4468. }
  4469. // Gets the number of skipped tests.
  4470. int UnitTest::skipped_test_count() const {
  4471. return impl()->skipped_test_count();
  4472. }
  4473. // Gets the number of failed tests.
  4474. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
  4475. // Gets the number of disabled tests that will be reported in the XML report.
  4476. int UnitTest::reportable_disabled_test_count() const {
  4477. return impl()->reportable_disabled_test_count();
  4478. }
  4479. // Gets the number of disabled tests.
  4480. int UnitTest::disabled_test_count() const {
  4481. return impl()->disabled_test_count();
  4482. }
  4483. // Gets the number of tests to be printed in the XML report.
  4484. int UnitTest::reportable_test_count() const {
  4485. return impl()->reportable_test_count();
  4486. }
  4487. // Gets the number of all tests.
  4488. int UnitTest::total_test_count() const { return impl()->total_test_count(); }
  4489. // Gets the number of tests that should run.
  4490. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
  4491. // Gets the time of the test program start, in ms from the start of the
  4492. // UNIX epoch.
  4493. internal::TimeInMillis UnitTest::start_timestamp() const {
  4494. return impl()->start_timestamp();
  4495. }
  4496. // Gets the elapsed time, in milliseconds.
  4497. internal::TimeInMillis UnitTest::elapsed_time() const {
  4498. return impl()->elapsed_time();
  4499. }
  4500. // Returns true if and only if the unit test passed (i.e. all test suites
  4501. // passed).
  4502. bool UnitTest::Passed() const { return impl()->Passed(); }
  4503. // Returns true if and only if the unit test failed (i.e. some test suite
  4504. // failed or something outside of all tests failed).
  4505. bool UnitTest::Failed() const { return impl()->Failed(); }
  4506. // Gets the i-th test suite among all the test suites. i can range from 0 to
  4507. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  4508. const TestSuite* UnitTest::GetTestSuite(int i) const {
  4509. return impl()->GetTestSuite(i);
  4510. }
  4511. // Legacy API is deprecated but still available
  4512. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4513. const TestCase* UnitTest::GetTestCase(int i) const {
  4514. return impl()->GetTestCase(i);
  4515. }
  4516. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4517. // Returns the TestResult containing information on test failures and
  4518. // properties logged outside of individual test suites.
  4519. const TestResult& UnitTest::ad_hoc_test_result() const {
  4520. return *impl()->ad_hoc_test_result();
  4521. }
  4522. // Gets the i-th test suite among all the test suites. i can range from 0 to
  4523. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  4524. TestSuite* UnitTest::GetMutableTestSuite(int i) {
  4525. return impl()->GetMutableSuiteCase(i);
  4526. }
  4527. // Returns the list of event listeners that can be used to track events
  4528. // inside Google Test.
  4529. TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); }
  4530. // Registers and returns a global test environment. When a test
  4531. // program is run, all global test environments will be set-up in the
  4532. // order they were registered. After all tests in the program have
  4533. // finished, all global test environments will be torn-down in the
  4534. // *reverse* order they were registered.
  4535. //
  4536. // The UnitTest object takes ownership of the given environment.
  4537. //
  4538. // We don't protect this under mutex_, as we only support calling it
  4539. // from the main thread.
  4540. Environment* UnitTest::AddEnvironment(Environment* env) {
  4541. if (env == nullptr) {
  4542. return nullptr;
  4543. }
  4544. impl_->environments().push_back(env);
  4545. return env;
  4546. }
  4547. // Adds a TestPartResult to the current TestResult object. All Google Test
  4548. // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
  4549. // this to report their results. The user code should use the
  4550. // assertion macros instead of calling this directly.
  4551. void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
  4552. const char* file_name, int line_number,
  4553. const std::string& message,
  4554. const std::string& os_stack_trace)
  4555. GTEST_LOCK_EXCLUDED_(mutex_) {
  4556. Message msg;
  4557. msg << message;
  4558. internal::MutexLock lock(&mutex_);
  4559. if (impl_->gtest_trace_stack().size() > 0) {
  4560. msg << "\n" << GTEST_NAME_ << " trace:";
  4561. for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
  4562. const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
  4563. msg << "\n"
  4564. << internal::FormatFileLocation(trace.file, trace.line) << " "
  4565. << trace.message;
  4566. }
  4567. }
  4568. if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
  4569. msg << internal::kStackTraceMarker << os_stack_trace;
  4570. }
  4571. const TestPartResult result = TestPartResult(
  4572. result_type, file_name, line_number, msg.GetString().c_str());
  4573. impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
  4574. result);
  4575. if (result_type != TestPartResult::kSuccess &&
  4576. result_type != TestPartResult::kSkip) {
  4577. // gtest_break_on_failure takes precedence over
  4578. // gtest_throw_on_failure. This allows a user to set the latter
  4579. // in the code (perhaps in order to use Google Test assertions
  4580. // with another testing framework) and specify the former on the
  4581. // command line for debugging.
  4582. if (GTEST_FLAG_GET(break_on_failure)) {
  4583. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  4584. // Using DebugBreak on Windows allows gtest to still break into a debugger
  4585. // when a failure happens and both the --gtest_break_on_failure and
  4586. // the --gtest_catch_exceptions flags are specified.
  4587. DebugBreak();
  4588. #elif (!defined(__native_client__)) && \
  4589. ((defined(__clang__) || defined(__GNUC__)) && \
  4590. (defined(__x86_64__) || defined(__i386__)))
  4591. // with clang/gcc we can achieve the same effect on x86 by invoking int3
  4592. asm("int3");
  4593. #else
  4594. // Dereference nullptr through a volatile pointer to prevent the compiler
  4595. // from removing. We use this rather than abort() or __builtin_trap() for
  4596. // portability: some debuggers don't correctly trap abort().
  4597. *static_cast<volatile int*>(nullptr) = 1;
  4598. #endif // GTEST_OS_WINDOWS
  4599. } else if (GTEST_FLAG_GET(throw_on_failure)) {
  4600. #if GTEST_HAS_EXCEPTIONS
  4601. throw internal::GoogleTestFailureException(result);
  4602. #else
  4603. // We cannot call abort() as it generates a pop-up in debug mode
  4604. // that cannot be suppressed in VC 7.1 or below.
  4605. exit(1);
  4606. #endif
  4607. }
  4608. }
  4609. }
  4610. // Adds a TestProperty to the current TestResult object when invoked from
  4611. // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
  4612. // from SetUpTestSuite or TearDownTestSuite, or to the global property set
  4613. // when invoked elsewhere. If the result already contains a property with
  4614. // the same key, the value will be updated.
  4615. void UnitTest::RecordProperty(const std::string& key,
  4616. const std::string& value) {
  4617. impl_->RecordProperty(TestProperty(key, value));
  4618. }
  4619. // Runs all tests in this UnitTest object and prints the result.
  4620. // Returns 0 if successful, or 1 otherwise.
  4621. //
  4622. // We don't protect this under mutex_, as we only support calling it
  4623. // from the main thread.
  4624. int UnitTest::Run() {
  4625. const bool in_death_test_child_process =
  4626. GTEST_FLAG_GET(internal_run_death_test).length() > 0;
  4627. // Google Test implements this protocol for catching that a test
  4628. // program exits before returning control to Google Test:
  4629. //
  4630. // 1. Upon start, Google Test creates a file whose absolute path
  4631. // is specified by the environment variable
  4632. // TEST_PREMATURE_EXIT_FILE.
  4633. // 2. When Google Test has finished its work, it deletes the file.
  4634. //
  4635. // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
  4636. // running a Google-Test-based test program and check the existence
  4637. // of the file at the end of the test execution to see if it has
  4638. // exited prematurely.
  4639. // If we are in the child process of a death test, don't
  4640. // create/delete the premature exit file, as doing so is unnecessary
  4641. // and will confuse the parent process. Otherwise, create/delete
  4642. // the file upon entering/leaving this function. If the program
  4643. // somehow exits before this function has a chance to return, the
  4644. // premature-exit file will be left undeleted, causing a test runner
  4645. // that understands the premature-exit-file protocol to report the
  4646. // test as having failed.
  4647. const internal::ScopedPrematureExitFile premature_exit_file(
  4648. in_death_test_child_process
  4649. ? nullptr
  4650. : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
  4651. // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
  4652. // used for the duration of the program.
  4653. impl()->set_catch_exceptions(GTEST_FLAG_GET(catch_exceptions));
  4654. #if GTEST_OS_WINDOWS
  4655. // Either the user wants Google Test to catch exceptions thrown by the
  4656. // tests or this is executing in the context of death test child
  4657. // process. In either case the user does not want to see pop-up dialogs
  4658. // about crashes - they are expected.
  4659. if (impl()->catch_exceptions() || in_death_test_child_process) {
  4660. #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  4661. // SetErrorMode doesn't exist on CE.
  4662. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
  4663. SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
  4664. #endif // !GTEST_OS_WINDOWS_MOBILE
  4665. #if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
  4666. // Death test children can be terminated with _abort(). On Windows,
  4667. // _abort() can show a dialog with a warning message. This forces the
  4668. // abort message to go to stderr instead.
  4669. _set_error_mode(_OUT_TO_STDERR);
  4670. #endif
  4671. #if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
  4672. // In the debug version, Visual Studio pops up a separate dialog
  4673. // offering a choice to debug the aborted program. We need to suppress
  4674. // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
  4675. // executed. Google Test will notify the user of any unexpected
  4676. // failure via stderr.
  4677. if (!GTEST_FLAG_GET(break_on_failure))
  4678. _set_abort_behavior(
  4679. 0x0, // Clear the following flags:
  4680. _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
  4681. // In debug mode, the Windows CRT can crash with an assertion over invalid
  4682. // input (e.g. passing an invalid file descriptor). The default handling
  4683. // for these assertions is to pop up a dialog and wait for user input.
  4684. // Instead ask the CRT to dump such assertions to stderr non-interactively.
  4685. if (!IsDebuggerPresent()) {
  4686. (void)_CrtSetReportMode(_CRT_ASSERT,
  4687. _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  4688. (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
  4689. }
  4690. #endif
  4691. }
  4692. #endif // GTEST_OS_WINDOWS
  4693. return internal::HandleExceptionsInMethodIfSupported(
  4694. impl(), &internal::UnitTestImpl::RunAllTests,
  4695. "auxiliary test code (environments or event listeners)")
  4696. ? 0
  4697. : 1;
  4698. }
  4699. // Returns the working directory when the first TEST() or TEST_F() was
  4700. // executed.
  4701. const char* UnitTest::original_working_dir() const {
  4702. return impl_->original_working_dir_.c_str();
  4703. }
  4704. // Returns the TestSuite object for the test that's currently running,
  4705. // or NULL if no test is running.
  4706. const TestSuite* UnitTest::current_test_suite() const
  4707. GTEST_LOCK_EXCLUDED_(mutex_) {
  4708. internal::MutexLock lock(&mutex_);
  4709. return impl_->current_test_suite();
  4710. }
  4711. // Legacy API is still available but deprecated
  4712. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4713. const TestCase* UnitTest::current_test_case() const
  4714. GTEST_LOCK_EXCLUDED_(mutex_) {
  4715. internal::MutexLock lock(&mutex_);
  4716. return impl_->current_test_suite();
  4717. }
  4718. #endif
  4719. // Returns the TestInfo object for the test that's currently running,
  4720. // or NULL if no test is running.
  4721. const TestInfo* UnitTest::current_test_info() const
  4722. GTEST_LOCK_EXCLUDED_(mutex_) {
  4723. internal::MutexLock lock(&mutex_);
  4724. return impl_->current_test_info();
  4725. }
  4726. // Returns the random seed used at the start of the current test run.
  4727. int UnitTest::random_seed() const { return impl_->random_seed(); }
  4728. // Returns ParameterizedTestSuiteRegistry object used to keep track of
  4729. // value-parameterized tests and instantiate and register them.
  4730. internal::ParameterizedTestSuiteRegistry&
  4731. UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
  4732. return impl_->parameterized_test_registry();
  4733. }
  4734. // Creates an empty UnitTest.
  4735. UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); }
  4736. // Destructor of UnitTest.
  4737. UnitTest::~UnitTest() { delete impl_; }
  4738. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  4739. // Google Test trace stack.
  4740. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
  4741. GTEST_LOCK_EXCLUDED_(mutex_) {
  4742. internal::MutexLock lock(&mutex_);
  4743. impl_->gtest_trace_stack().push_back(trace);
  4744. }
  4745. // Pops a trace from the per-thread Google Test trace stack.
  4746. void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) {
  4747. internal::MutexLock lock(&mutex_);
  4748. impl_->gtest_trace_stack().pop_back();
  4749. }
  4750. namespace internal {
  4751. UnitTestImpl::UnitTestImpl(UnitTest* parent)
  4752. : parent_(parent),
  4753. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
  4754. default_global_test_part_result_reporter_(this),
  4755. default_per_thread_test_part_result_reporter_(this),
  4756. GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
  4757. &default_global_test_part_result_reporter_),
  4758. per_thread_test_part_result_reporter_(
  4759. &default_per_thread_test_part_result_reporter_),
  4760. parameterized_test_registry_(),
  4761. parameterized_tests_registered_(false),
  4762. last_death_test_suite_(-1),
  4763. current_test_suite_(nullptr),
  4764. current_test_info_(nullptr),
  4765. ad_hoc_test_result_(),
  4766. os_stack_trace_getter_(nullptr),
  4767. post_flag_parse_init_performed_(false),
  4768. random_seed_(0), // Will be overridden by the flag before first use.
  4769. random_(0), // Will be reseeded before first use.
  4770. start_timestamp_(0),
  4771. elapsed_time_(0),
  4772. #if GTEST_HAS_DEATH_TEST
  4773. death_test_factory_(new DefaultDeathTestFactory),
  4774. #endif
  4775. // Will be overridden by the flag before first use.
  4776. catch_exceptions_(false) {
  4777. listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
  4778. }
  4779. UnitTestImpl::~UnitTestImpl() {
  4780. // Deletes every TestSuite.
  4781. ForEach(test_suites_, internal::Delete<TestSuite>);
  4782. // Deletes every Environment.
  4783. ForEach(environments_, internal::Delete<Environment>);
  4784. delete os_stack_trace_getter_;
  4785. }
  4786. // Adds a TestProperty to the current TestResult object when invoked in a
  4787. // context of a test, to current test suite's ad_hoc_test_result when invoke
  4788. // from SetUpTestSuite/TearDownTestSuite, or to the global property set
  4789. // otherwise. If the result already contains a property with the same key,
  4790. // the value will be updated.
  4791. void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
  4792. std::string xml_element;
  4793. TestResult* test_result; // TestResult appropriate for property recording.
  4794. if (current_test_info_ != nullptr) {
  4795. xml_element = "testcase";
  4796. test_result = &(current_test_info_->result_);
  4797. } else if (current_test_suite_ != nullptr) {
  4798. xml_element = "testsuite";
  4799. test_result = &(current_test_suite_->ad_hoc_test_result_);
  4800. } else {
  4801. xml_element = "testsuites";
  4802. test_result = &ad_hoc_test_result_;
  4803. }
  4804. test_result->RecordProperty(xml_element, test_property);
  4805. }
  4806. #if GTEST_HAS_DEATH_TEST
  4807. // Disables event forwarding if the control is currently in a death test
  4808. // subprocess. Must not be called before InitGoogleTest.
  4809. void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
  4810. if (internal_run_death_test_flag_.get() != nullptr)
  4811. listeners()->SuppressEventForwarding();
  4812. }
  4813. #endif // GTEST_HAS_DEATH_TEST
  4814. // Initializes event listeners performing XML output as specified by
  4815. // UnitTestOptions. Must not be called before InitGoogleTest.
  4816. void UnitTestImpl::ConfigureXmlOutput() {
  4817. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  4818. if (output_format == "xml") {
  4819. listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
  4820. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  4821. } else if (output_format == "json") {
  4822. listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
  4823. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  4824. } else if (output_format != "") {
  4825. GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
  4826. << output_format << "\" ignored.";
  4827. }
  4828. }
  4829. #if GTEST_CAN_STREAM_RESULTS_
  4830. // Initializes event listeners for streaming test results in string form.
  4831. // Must not be called before InitGoogleTest.
  4832. void UnitTestImpl::ConfigureStreamingOutput() {
  4833. const std::string& target = GTEST_FLAG_GET(stream_result_to);
  4834. if (!target.empty()) {
  4835. const size_t pos = target.find(':');
  4836. if (pos != std::string::npos) {
  4837. listeners()->Append(
  4838. new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));
  4839. } else {
  4840. GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
  4841. << "\" ignored.";
  4842. }
  4843. }
  4844. }
  4845. #endif // GTEST_CAN_STREAM_RESULTS_
  4846. // Performs initialization dependent upon flag values obtained in
  4847. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  4848. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  4849. // this function is also called from RunAllTests. Since this function can be
  4850. // called more than once, it has to be idempotent.
  4851. void UnitTestImpl::PostFlagParsingInit() {
  4852. // Ensures that this function does not execute more than once.
  4853. if (!post_flag_parse_init_performed_) {
  4854. post_flag_parse_init_performed_ = true;
  4855. #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  4856. // Register to send notifications about key process state changes.
  4857. listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
  4858. #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  4859. #if GTEST_HAS_DEATH_TEST
  4860. InitDeathTestSubprocessControlInfo();
  4861. SuppressTestEventsIfInSubprocess();
  4862. #endif // GTEST_HAS_DEATH_TEST
  4863. // Registers parameterized tests. This makes parameterized tests
  4864. // available to the UnitTest reflection API without running
  4865. // RUN_ALL_TESTS.
  4866. RegisterParameterizedTests();
  4867. // Configures listeners for XML output. This makes it possible for users
  4868. // to shut down the default XML output before invoking RUN_ALL_TESTS.
  4869. ConfigureXmlOutput();
  4870. if (GTEST_FLAG_GET(brief)) {
  4871. listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter);
  4872. }
  4873. #if GTEST_CAN_STREAM_RESULTS_
  4874. // Configures listeners for streaming test results to the specified server.
  4875. ConfigureStreamingOutput();
  4876. #endif // GTEST_CAN_STREAM_RESULTS_
  4877. #if GTEST_HAS_ABSL
  4878. if (GTEST_FLAG_GET(install_failure_signal_handler)) {
  4879. absl::FailureSignalHandlerOptions options;
  4880. absl::InstallFailureSignalHandler(options);
  4881. }
  4882. #endif // GTEST_HAS_ABSL
  4883. }
  4884. }
  4885. // A predicate that checks the name of a TestSuite against a known
  4886. // value.
  4887. //
  4888. // This is used for implementation of the UnitTest class only. We put
  4889. // it in the anonymous namespace to prevent polluting the outer
  4890. // namespace.
  4891. //
  4892. // TestSuiteNameIs is copyable.
  4893. class TestSuiteNameIs {
  4894. public:
  4895. // Constructor.
  4896. explicit TestSuiteNameIs(const std::string& name) : name_(name) {}
  4897. // Returns true if and only if the name of test_suite matches name_.
  4898. bool operator()(const TestSuite* test_suite) const {
  4899. return test_suite != nullptr &&
  4900. strcmp(test_suite->name(), name_.c_str()) == 0;
  4901. }
  4902. private:
  4903. std::string name_;
  4904. };
  4905. // Finds and returns a TestSuite with the given name. If one doesn't
  4906. // exist, creates one and returns it. It's the CALLER'S
  4907. // RESPONSIBILITY to ensure that this function is only called WHEN THE
  4908. // TESTS ARE NOT SHUFFLED.
  4909. //
  4910. // Arguments:
  4911. //
  4912. // test_suite_name: name of the test suite
  4913. // type_param: the name of the test suite's type parameter, or NULL if
  4914. // this is not a typed or a type-parameterized test suite.
  4915. // set_up_tc: pointer to the function that sets up the test suite
  4916. // tear_down_tc: pointer to the function that tears down the test suite
  4917. TestSuite* UnitTestImpl::GetTestSuite(
  4918. const char* test_suite_name, const char* type_param,
  4919. internal::SetUpTestSuiteFunc set_up_tc,
  4920. internal::TearDownTestSuiteFunc tear_down_tc) {
  4921. // Can we find a TestSuite with the given name?
  4922. const auto test_suite =
  4923. std::find_if(test_suites_.rbegin(), test_suites_.rend(),
  4924. TestSuiteNameIs(test_suite_name));
  4925. if (test_suite != test_suites_.rend()) return *test_suite;
  4926. // No. Let's create one.
  4927. auto* const new_test_suite =
  4928. new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
  4929. const UnitTestFilter death_test_suite_filter(kDeathTestSuiteFilter);
  4930. // Is this a death test suite?
  4931. if (death_test_suite_filter.MatchesName(test_suite_name)) {
  4932. // Yes. Inserts the test suite after the last death test suite
  4933. // defined so far. This only works when the test suites haven't
  4934. // been shuffled. Otherwise we may end up running a death test
  4935. // after a non-death test.
  4936. ++last_death_test_suite_;
  4937. test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
  4938. new_test_suite);
  4939. } else {
  4940. // No. Appends to the end of the list.
  4941. test_suites_.push_back(new_test_suite);
  4942. }
  4943. test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
  4944. return new_test_suite;
  4945. }
  4946. // Helpers for setting up / tearing down the given environment. They
  4947. // are for use in the ForEach() function.
  4948. static void SetUpEnvironment(Environment* env) { env->SetUp(); }
  4949. static void TearDownEnvironment(Environment* env) { env->TearDown(); }
  4950. // Runs all tests in this UnitTest object, prints the result, and
  4951. // returns true if all tests are successful. If any exception is
  4952. // thrown during a test, the test is considered to be failed, but the
  4953. // rest of the tests will still be run.
  4954. //
  4955. // When parameterized tests are enabled, it expands and registers
  4956. // parameterized tests first in RegisterParameterizedTests().
  4957. // All other functions called from RunAllTests() may safely assume that
  4958. // parameterized tests are ready to be counted and run.
  4959. bool UnitTestImpl::RunAllTests() {
  4960. // True if and only if Google Test is initialized before RUN_ALL_TESTS() is
  4961. // called.
  4962. const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
  4963. // Do not run any test if the --help flag was specified.
  4964. if (g_help_flag) return true;
  4965. // Repeats the call to the post-flag parsing initialization in case the
  4966. // user didn't call InitGoogleTest.
  4967. PostFlagParsingInit();
  4968. // Even if sharding is not on, test runners may want to use the
  4969. // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
  4970. // protocol.
  4971. internal::WriteToShardStatusFileIfNeeded();
  4972. // True if and only if we are in a subprocess for running a thread-safe-style
  4973. // death test.
  4974. bool in_subprocess_for_death_test = false;
  4975. #if GTEST_HAS_DEATH_TEST
  4976. in_subprocess_for_death_test =
  4977. (internal_run_death_test_flag_.get() != nullptr);
  4978. #if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  4979. if (in_subprocess_for_death_test) {
  4980. GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
  4981. }
  4982. #endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  4983. #endif // GTEST_HAS_DEATH_TEST
  4984. const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
  4985. in_subprocess_for_death_test);
  4986. // Compares the full test names with the filter to decide which
  4987. // tests to run.
  4988. const bool has_tests_to_run =
  4989. FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL
  4990. : IGNORE_SHARDING_PROTOCOL) > 0;
  4991. // Lists the tests and exits if the --gtest_list_tests flag was specified.
  4992. if (GTEST_FLAG_GET(list_tests)) {
  4993. // This must be called *after* FilterTests() has been called.
  4994. ListTestsMatchingFilter();
  4995. return true;
  4996. }
  4997. random_seed_ = GetRandomSeedFromFlag(GTEST_FLAG_GET(random_seed));
  4998. // True if and only if at least one test has failed.
  4999. bool failed = false;
  5000. TestEventListener* repeater = listeners()->repeater();
  5001. start_timestamp_ = GetTimeInMillis();
  5002. repeater->OnTestProgramStart(*parent_);
  5003. // How many times to repeat the tests? We don't want to repeat them
  5004. // when we are inside the subprocess of a death test.
  5005. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG_GET(repeat);
  5006. // Repeats forever if the repeat count is negative.
  5007. const bool gtest_repeat_forever = repeat < 0;
  5008. // Should test environments be set up and torn down for each repeat, or only
  5009. // set up on the first and torn down on the last iteration? If there is no
  5010. // "last" iteration because the tests will repeat forever, always recreate the
  5011. // environments to avoid leaks in case one of the environments is using
  5012. // resources that are external to this process. Without this check there would
  5013. // be no way to clean up those external resources automatically.
  5014. const bool recreate_environments_when_repeating =
  5015. GTEST_FLAG_GET(recreate_environments_when_repeating) ||
  5016. gtest_repeat_forever;
  5017. for (int i = 0; gtest_repeat_forever || i != repeat; i++) {
  5018. // We want to preserve failures generated by ad-hoc test
  5019. // assertions executed before RUN_ALL_TESTS().
  5020. ClearNonAdHocTestResult();
  5021. Timer timer;
  5022. // Shuffles test suites and tests if requested.
  5023. if (has_tests_to_run && GTEST_FLAG_GET(shuffle)) {
  5024. random()->Reseed(static_cast<uint32_t>(random_seed_));
  5025. // This should be done before calling OnTestIterationStart(),
  5026. // such that a test event listener can see the actual test order
  5027. // in the event.
  5028. ShuffleTests();
  5029. }
  5030. // Tells the unit test event listeners that the tests are about to start.
  5031. repeater->OnTestIterationStart(*parent_, i);
  5032. // Runs each test suite if there is at least one test to run.
  5033. if (has_tests_to_run) {
  5034. // Sets up all environments beforehand. If test environments aren't
  5035. // recreated for each iteration, only do so on the first iteration.
  5036. if (i == 0 || recreate_environments_when_repeating) {
  5037. repeater->OnEnvironmentsSetUpStart(*parent_);
  5038. ForEach(environments_, SetUpEnvironment);
  5039. repeater->OnEnvironmentsSetUpEnd(*parent_);
  5040. }
  5041. // Runs the tests only if there was no fatal failure or skip triggered
  5042. // during global set-up.
  5043. if (Test::IsSkipped()) {
  5044. // Emit diagnostics when global set-up calls skip, as it will not be
  5045. // emitted by default.
  5046. TestResult& test_result =
  5047. *internal::GetUnitTestImpl()->current_test_result();
  5048. for (int j = 0; j < test_result.total_part_count(); ++j) {
  5049. const TestPartResult& test_part_result =
  5050. test_result.GetTestPartResult(j);
  5051. if (test_part_result.type() == TestPartResult::kSkip) {
  5052. const std::string& result = test_part_result.message();
  5053. printf("%s\n", result.c_str());
  5054. }
  5055. }
  5056. fflush(stdout);
  5057. } else if (!Test::HasFatalFailure()) {
  5058. for (int test_index = 0; test_index < total_test_suite_count();
  5059. test_index++) {
  5060. GetMutableSuiteCase(test_index)->Run();
  5061. if (GTEST_FLAG_GET(fail_fast) &&
  5062. GetMutableSuiteCase(test_index)->Failed()) {
  5063. for (int j = test_index + 1; j < total_test_suite_count(); j++) {
  5064. GetMutableSuiteCase(j)->Skip();
  5065. }
  5066. break;
  5067. }
  5068. }
  5069. } else if (Test::HasFatalFailure()) {
  5070. // If there was a fatal failure during the global setup then we know we
  5071. // aren't going to run any tests. Explicitly mark all of the tests as
  5072. // skipped to make this obvious in the output.
  5073. for (int test_index = 0; test_index < total_test_suite_count();
  5074. test_index++) {
  5075. GetMutableSuiteCase(test_index)->Skip();
  5076. }
  5077. }
  5078. // Tears down all environments in reverse order afterwards. If test
  5079. // environments aren't recreated for each iteration, only do so on the
  5080. // last iteration.
  5081. if (i == repeat - 1 || recreate_environments_when_repeating) {
  5082. repeater->OnEnvironmentsTearDownStart(*parent_);
  5083. std::for_each(environments_.rbegin(), environments_.rend(),
  5084. TearDownEnvironment);
  5085. repeater->OnEnvironmentsTearDownEnd(*parent_);
  5086. }
  5087. }
  5088. elapsed_time_ = timer.Elapsed();
  5089. // Tells the unit test event listener that the tests have just finished.
  5090. repeater->OnTestIterationEnd(*parent_, i);
  5091. // Gets the result and clears it.
  5092. if (!Passed()) {
  5093. failed = true;
  5094. }
  5095. // Restores the original test order after the iteration. This
  5096. // allows the user to quickly repro a failure that happens in the
  5097. // N-th iteration without repeating the first (N - 1) iterations.
  5098. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
  5099. // case the user somehow changes the value of the flag somewhere
  5100. // (it's always safe to unshuffle the tests).
  5101. UnshuffleTests();
  5102. if (GTEST_FLAG_GET(shuffle)) {
  5103. // Picks a new random seed for each iteration.
  5104. random_seed_ = GetNextRandomSeed(random_seed_);
  5105. }
  5106. }
  5107. repeater->OnTestProgramEnd(*parent_);
  5108. if (!gtest_is_initialized_before_run_all_tests) {
  5109. ColoredPrintf(
  5110. GTestColor::kRed,
  5111. "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
  5112. "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
  5113. "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
  5114. " will start to enforce the valid usage. "
  5115. "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
  5116. #if GTEST_FOR_GOOGLE_
  5117. ColoredPrintf(GTestColor::kRed,
  5118. "For more details, see http://wiki/Main/ValidGUnitMain.\n");
  5119. #endif // GTEST_FOR_GOOGLE_
  5120. }
  5121. return !failed;
  5122. }
  5123. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  5124. // if the variable is present. If a file already exists at this location, this
  5125. // function will write over it. If the variable is present, but the file cannot
  5126. // be created, prints an error and exits.
  5127. void WriteToShardStatusFileIfNeeded() {
  5128. const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
  5129. if (test_shard_file != nullptr) {
  5130. FILE* const file = posix::FOpen(test_shard_file, "w");
  5131. if (file == nullptr) {
  5132. ColoredPrintf(GTestColor::kRed,
  5133. "Could not write to the test shard status file \"%s\" "
  5134. "specified by the %s environment variable.\n",
  5135. test_shard_file, kTestShardStatusFile);
  5136. fflush(stdout);
  5137. exit(EXIT_FAILURE);
  5138. }
  5139. fclose(file);
  5140. }
  5141. }
  5142. // Checks whether sharding is enabled by examining the relevant
  5143. // environment variable values. If the variables are present,
  5144. // but inconsistent (i.e., shard_index >= total_shards), prints
  5145. // an error and exits. If in_subprocess_for_death_test, sharding is
  5146. // disabled because it must only be applied to the original test
  5147. // process. Otherwise, we could filter out death tests we intended to execute.
  5148. bool ShouldShard(const char* total_shards_env, const char* shard_index_env,
  5149. bool in_subprocess_for_death_test) {
  5150. if (in_subprocess_for_death_test) {
  5151. return false;
  5152. }
  5153. const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1);
  5154. const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1);
  5155. if (total_shards == -1 && shard_index == -1) {
  5156. return false;
  5157. } else if (total_shards == -1 && shard_index != -1) {
  5158. const Message msg = Message() << "Invalid environment variables: you have "
  5159. << kTestShardIndex << " = " << shard_index
  5160. << ", but have left " << kTestTotalShards
  5161. << " unset.\n";
  5162. ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
  5163. fflush(stdout);
  5164. exit(EXIT_FAILURE);
  5165. } else if (total_shards != -1 && shard_index == -1) {
  5166. const Message msg = Message()
  5167. << "Invalid environment variables: you have "
  5168. << kTestTotalShards << " = " << total_shards
  5169. << ", but have left " << kTestShardIndex << " unset.\n";
  5170. ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
  5171. fflush(stdout);
  5172. exit(EXIT_FAILURE);
  5173. } else if (shard_index < 0 || shard_index >= total_shards) {
  5174. const Message msg =
  5175. Message() << "Invalid environment variables: we require 0 <= "
  5176. << kTestShardIndex << " < " << kTestTotalShards
  5177. << ", but you have " << kTestShardIndex << "=" << shard_index
  5178. << ", " << kTestTotalShards << "=" << total_shards << ".\n";
  5179. ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
  5180. fflush(stdout);
  5181. exit(EXIT_FAILURE);
  5182. }
  5183. return total_shards > 1;
  5184. }
  5185. // Parses the environment variable var as an Int32. If it is unset,
  5186. // returns default_val. If it is not an Int32, prints an error
  5187. // and aborts.
  5188. int32_t Int32FromEnvOrDie(const char* var, int32_t default_val) {
  5189. const char* str_val = posix::GetEnv(var);
  5190. if (str_val == nullptr) {
  5191. return default_val;
  5192. }
  5193. int32_t result;
  5194. if (!ParseInt32(Message() << "The value of environment variable " << var,
  5195. str_val, &result)) {
  5196. exit(EXIT_FAILURE);
  5197. }
  5198. return result;
  5199. }
  5200. // Given the total number of shards, the shard index, and the test id,
  5201. // returns true if and only if the test should be run on this shard. The test id
  5202. // is some arbitrary but unique non-negative integer assigned to each test
  5203. // method. Assumes that 0 <= shard_index < total_shards.
  5204. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
  5205. return (test_id % total_shards) == shard_index;
  5206. }
  5207. // Compares the name of each test with the user-specified filter to
  5208. // decide whether the test should be run, then records the result in
  5209. // each TestSuite and TestInfo object.
  5210. // If shard_tests == true, further filters tests based on sharding
  5211. // variables in the environment - see
  5212. // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
  5213. // . Returns the number of tests that should run.
  5214. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
  5215. const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL
  5216. ? Int32FromEnvOrDie(kTestTotalShards, -1)
  5217. : -1;
  5218. const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL
  5219. ? Int32FromEnvOrDie(kTestShardIndex, -1)
  5220. : -1;
  5221. const PositiveAndNegativeUnitTestFilter gtest_flag_filter(
  5222. GTEST_FLAG_GET(filter));
  5223. const UnitTestFilter disable_test_filter(kDisableTestFilter);
  5224. // num_runnable_tests are the number of tests that will
  5225. // run across all shards (i.e., match filter and are not disabled).
  5226. // num_selected_tests are the number of tests to be run on
  5227. // this shard.
  5228. int num_runnable_tests = 0;
  5229. int num_selected_tests = 0;
  5230. for (auto* test_suite : test_suites_) {
  5231. const std::string& test_suite_name = test_suite->name();
  5232. test_suite->set_should_run(false);
  5233. for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
  5234. TestInfo* const test_info = test_suite->test_info_list()[j];
  5235. const std::string test_name(test_info->name());
  5236. // A test is disabled if test suite name or test name matches
  5237. // kDisableTestFilter.
  5238. const bool is_disabled =
  5239. disable_test_filter.MatchesName(test_suite_name) ||
  5240. disable_test_filter.MatchesName(test_name);
  5241. test_info->is_disabled_ = is_disabled;
  5242. const bool matches_filter =
  5243. gtest_flag_filter.MatchesTest(test_suite_name, test_name);
  5244. test_info->matches_filter_ = matches_filter;
  5245. const bool is_runnable =
  5246. (GTEST_FLAG_GET(also_run_disabled_tests) || !is_disabled) &&
  5247. matches_filter;
  5248. const bool is_in_another_shard =
  5249. shard_tests != IGNORE_SHARDING_PROTOCOL &&
  5250. !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
  5251. test_info->is_in_another_shard_ = is_in_another_shard;
  5252. const bool is_selected = is_runnable && !is_in_another_shard;
  5253. num_runnable_tests += is_runnable;
  5254. num_selected_tests += is_selected;
  5255. test_info->should_run_ = is_selected;
  5256. test_suite->set_should_run(test_suite->should_run() || is_selected);
  5257. }
  5258. }
  5259. return num_selected_tests;
  5260. }
  5261. // Prints the given C-string on a single line by replacing all '\n'
  5262. // characters with string "\\n". If the output takes more than
  5263. // max_length characters, only prints the first max_length characters
  5264. // and "...".
  5265. static void PrintOnOneLine(const char* str, int max_length) {
  5266. if (str != nullptr) {
  5267. for (int i = 0; *str != '\0'; ++str) {
  5268. if (i >= max_length) {
  5269. printf("...");
  5270. break;
  5271. }
  5272. if (*str == '\n') {
  5273. printf("\\n");
  5274. i += 2;
  5275. } else {
  5276. printf("%c", *str);
  5277. ++i;
  5278. }
  5279. }
  5280. }
  5281. }
  5282. // Prints the names of the tests matching the user-specified filter flag.
  5283. void UnitTestImpl::ListTestsMatchingFilter() {
  5284. // Print at most this many characters for each type/value parameter.
  5285. const int kMaxParamLength = 250;
  5286. for (auto* test_suite : test_suites_) {
  5287. bool printed_test_suite_name = false;
  5288. for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
  5289. const TestInfo* const test_info = test_suite->test_info_list()[j];
  5290. if (test_info->matches_filter_) {
  5291. if (!printed_test_suite_name) {
  5292. printed_test_suite_name = true;
  5293. printf("%s.", test_suite->name());
  5294. if (test_suite->type_param() != nullptr) {
  5295. printf(" # %s = ", kTypeParamLabel);
  5296. // We print the type parameter on a single line to make
  5297. // the output easy to parse by a program.
  5298. PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
  5299. }
  5300. printf("\n");
  5301. }
  5302. printf(" %s", test_info->name());
  5303. if (test_info->value_param() != nullptr) {
  5304. printf(" # %s = ", kValueParamLabel);
  5305. // We print the value parameter on a single line to make the
  5306. // output easy to parse by a program.
  5307. PrintOnOneLine(test_info->value_param(), kMaxParamLength);
  5308. }
  5309. printf("\n");
  5310. }
  5311. }
  5312. }
  5313. fflush(stdout);
  5314. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  5315. if (output_format == "xml" || output_format == "json") {
  5316. FILE* fileout = OpenFileForWriting(
  5317. UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
  5318. std::stringstream stream;
  5319. if (output_format == "xml") {
  5320. XmlUnitTestResultPrinter(
  5321. UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  5322. .PrintXmlTestsList(&stream, test_suites_);
  5323. } else if (output_format == "json") {
  5324. JsonUnitTestResultPrinter(
  5325. UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  5326. .PrintJsonTestList(&stream, test_suites_);
  5327. }
  5328. fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
  5329. fclose(fileout);
  5330. }
  5331. }
  5332. // Sets the OS stack trace getter.
  5333. //
  5334. // Does nothing if the input and the current OS stack trace getter are
  5335. // the same; otherwise, deletes the old getter and makes the input the
  5336. // current getter.
  5337. void UnitTestImpl::set_os_stack_trace_getter(
  5338. OsStackTraceGetterInterface* getter) {
  5339. if (os_stack_trace_getter_ != getter) {
  5340. delete os_stack_trace_getter_;
  5341. os_stack_trace_getter_ = getter;
  5342. }
  5343. }
  5344. // Returns the current OS stack trace getter if it is not NULL;
  5345. // otherwise, creates an OsStackTraceGetter, makes it the current
  5346. // getter, and returns it.
  5347. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
  5348. if (os_stack_trace_getter_ == nullptr) {
  5349. #ifdef GTEST_OS_STACK_TRACE_GETTER_
  5350. os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
  5351. #else
  5352. os_stack_trace_getter_ = new OsStackTraceGetter;
  5353. #endif // GTEST_OS_STACK_TRACE_GETTER_
  5354. }
  5355. return os_stack_trace_getter_;
  5356. }
  5357. // Returns the most specific TestResult currently running.
  5358. TestResult* UnitTestImpl::current_test_result() {
  5359. if (current_test_info_ != nullptr) {
  5360. return &current_test_info_->result_;
  5361. }
  5362. if (current_test_suite_ != nullptr) {
  5363. return &current_test_suite_->ad_hoc_test_result_;
  5364. }
  5365. return &ad_hoc_test_result_;
  5366. }
  5367. // Shuffles all test suites, and the tests within each test suite,
  5368. // making sure that death tests are still run first.
  5369. void UnitTestImpl::ShuffleTests() {
  5370. // Shuffles the death test suites.
  5371. ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
  5372. // Shuffles the non-death test suites.
  5373. ShuffleRange(random(), last_death_test_suite_ + 1,
  5374. static_cast<int>(test_suites_.size()), &test_suite_indices_);
  5375. // Shuffles the tests inside each test suite.
  5376. for (auto& test_suite : test_suites_) {
  5377. test_suite->ShuffleTests(random());
  5378. }
  5379. }
  5380. // Restores the test suites and tests to their order before the first shuffle.
  5381. void UnitTestImpl::UnshuffleTests() {
  5382. for (size_t i = 0; i < test_suites_.size(); i++) {
  5383. // Unshuffles the tests in each test suite.
  5384. test_suites_[i]->UnshuffleTests();
  5385. // Resets the index of each test suite.
  5386. test_suite_indices_[i] = static_cast<int>(i);
  5387. }
  5388. }
  5389. // Returns the current OS stack trace as an std::string.
  5390. //
  5391. // The maximum number of stack frames to be included is specified by
  5392. // the gtest_stack_trace_depth flag. The skip_count parameter
  5393. // specifies the number of top frames to be skipped, which doesn't
  5394. // count against the number of frames to be included.
  5395. //
  5396. // For example, if Foo() calls Bar(), which in turn calls
  5397. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  5398. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  5399. GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_ std::string
  5400. GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) {
  5401. // We pass skip_count + 1 to skip this wrapper function in addition
  5402. // to what the user really wants to skip.
  5403. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
  5404. }
  5405. // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
  5406. // suppress unreachable code warnings.
  5407. namespace {
  5408. class ClassUniqueToAlwaysTrue {};
  5409. } // namespace
  5410. bool IsTrue(bool condition) { return condition; }
  5411. bool AlwaysTrue() {
  5412. #if GTEST_HAS_EXCEPTIONS
  5413. // This condition is always false so AlwaysTrue() never actually throws,
  5414. // but it makes the compiler think that it may throw.
  5415. if (IsTrue(false)) throw ClassUniqueToAlwaysTrue();
  5416. #endif // GTEST_HAS_EXCEPTIONS
  5417. return true;
  5418. }
  5419. // If *pstr starts with the given prefix, modifies *pstr to be right
  5420. // past the prefix and returns true; otherwise leaves *pstr unchanged
  5421. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  5422. bool SkipPrefix(const char* prefix, const char** pstr) {
  5423. const size_t prefix_len = strlen(prefix);
  5424. if (strncmp(*pstr, prefix, prefix_len) == 0) {
  5425. *pstr += prefix_len;
  5426. return true;
  5427. }
  5428. return false;
  5429. }
  5430. // Parses a string as a command line flag. The string should have
  5431. // the format "--flag=value". When def_optional is true, the "=value"
  5432. // part can be omitted.
  5433. //
  5434. // Returns the value of the flag, or NULL if the parsing failed.
  5435. static const char* ParseFlagValue(const char* str, const char* flag_name,
  5436. bool def_optional) {
  5437. // str and flag must not be NULL.
  5438. if (str == nullptr || flag_name == nullptr) return nullptr;
  5439. // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
  5440. const std::string flag_str =
  5441. std::string("--") + GTEST_FLAG_PREFIX_ + flag_name;
  5442. const size_t flag_len = flag_str.length();
  5443. if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
  5444. // Skips the flag name.
  5445. const char* flag_end = str + flag_len;
  5446. // When def_optional is true, it's OK to not have a "=value" part.
  5447. if (def_optional && (flag_end[0] == '\0')) {
  5448. return flag_end;
  5449. }
  5450. // If def_optional is true and there are more characters after the
  5451. // flag name, or if def_optional is false, there must be a '=' after
  5452. // the flag name.
  5453. if (flag_end[0] != '=') return nullptr;
  5454. // Returns the string after "=".
  5455. return flag_end + 1;
  5456. }
  5457. // Parses a string for a bool flag, in the form of either
  5458. // "--flag=value" or "--flag".
  5459. //
  5460. // In the former case, the value is taken as true as long as it does
  5461. // not start with '0', 'f', or 'F'.
  5462. //
  5463. // In the latter case, the value is taken as true.
  5464. //
  5465. // On success, stores the value of the flag in *value, and returns
  5466. // true. On failure, returns false without changing *value.
  5467. static bool ParseFlag(const char* str, const char* flag_name, bool* value) {
  5468. // Gets the value of the flag as a string.
  5469. const char* const value_str = ParseFlagValue(str, flag_name, true);
  5470. // Aborts if the parsing failed.
  5471. if (value_str == nullptr) return false;
  5472. // Converts the string value to a bool.
  5473. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  5474. return true;
  5475. }
  5476. // Parses a string for an int32_t flag, in the form of "--flag=value".
  5477. //
  5478. // On success, stores the value of the flag in *value, and returns
  5479. // true. On failure, returns false without changing *value.
  5480. bool ParseFlag(const char* str, const char* flag_name, int32_t* value) {
  5481. // Gets the value of the flag as a string.
  5482. const char* const value_str = ParseFlagValue(str, flag_name, false);
  5483. // Aborts if the parsing failed.
  5484. if (value_str == nullptr) return false;
  5485. // Sets *value to the value of the flag.
  5486. return ParseInt32(Message() << "The value of flag --" << flag_name, value_str,
  5487. value);
  5488. }
  5489. // Parses a string for a string flag, in the form of "--flag=value".
  5490. //
  5491. // On success, stores the value of the flag in *value, and returns
  5492. // true. On failure, returns false without changing *value.
  5493. template <typename String>
  5494. static bool ParseFlag(const char* str, const char* flag_name, String* value) {
  5495. // Gets the value of the flag as a string.
  5496. const char* const value_str = ParseFlagValue(str, flag_name, false);
  5497. // Aborts if the parsing failed.
  5498. if (value_str == nullptr) return false;
  5499. // Sets *value to the value of the flag.
  5500. *value = value_str;
  5501. return true;
  5502. }
  5503. // Determines whether a string has a prefix that Google Test uses for its
  5504. // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
  5505. // If Google Test detects that a command line flag has its prefix but is not
  5506. // recognized, it will print its help message. Flags starting with
  5507. // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
  5508. // internal flags and do not trigger the help message.
  5509. static bool HasGoogleTestFlagPrefix(const char* str) {
  5510. return (SkipPrefix("--", &str) || SkipPrefix("-", &str) ||
  5511. SkipPrefix("/", &str)) &&
  5512. !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
  5513. (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
  5514. SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
  5515. }
  5516. // Prints a string containing code-encoded text. The following escape
  5517. // sequences can be used in the string to control the text color:
  5518. //
  5519. // @@ prints a single '@' character.
  5520. // @R changes the color to red.
  5521. // @G changes the color to green.
  5522. // @Y changes the color to yellow.
  5523. // @D changes to the default terminal text color.
  5524. //
  5525. static void PrintColorEncoded(const char* str) {
  5526. GTestColor color = GTestColor::kDefault; // The current color.
  5527. // Conceptually, we split the string into segments divided by escape
  5528. // sequences. Then we print one segment at a time. At the end of
  5529. // each iteration, the str pointer advances to the beginning of the
  5530. // next segment.
  5531. for (;;) {
  5532. const char* p = strchr(str, '@');
  5533. if (p == nullptr) {
  5534. ColoredPrintf(color, "%s", str);
  5535. return;
  5536. }
  5537. ColoredPrintf(color, "%s", std::string(str, p).c_str());
  5538. const char ch = p[1];
  5539. str = p + 2;
  5540. if (ch == '@') {
  5541. ColoredPrintf(color, "@");
  5542. } else if (ch == 'D') {
  5543. color = GTestColor::kDefault;
  5544. } else if (ch == 'R') {
  5545. color = GTestColor::kRed;
  5546. } else if (ch == 'G') {
  5547. color = GTestColor::kGreen;
  5548. } else if (ch == 'Y') {
  5549. color = GTestColor::kYellow;
  5550. } else {
  5551. --str;
  5552. }
  5553. }
  5554. }
  5555. static const char kColorEncodedHelpMessage[] =
  5556. "This program contains tests written using " GTEST_NAME_
  5557. ". You can use the\n"
  5558. "following command line flags to control its behavior:\n"
  5559. "\n"
  5560. "Test Selection:\n"
  5561. " @G--" GTEST_FLAG_PREFIX_
  5562. "list_tests@D\n"
  5563. " List the names of all tests instead of running them. The name of\n"
  5564. " TEST(Foo, Bar) is \"Foo.Bar\".\n"
  5565. " @G--" GTEST_FLAG_PREFIX_
  5566. "filter=@YPOSITIVE_PATTERNS"
  5567. "[@G-@YNEGATIVE_PATTERNS]@D\n"
  5568. " Run only the tests whose name matches one of the positive patterns "
  5569. "but\n"
  5570. " none of the negative patterns. '?' matches any single character; "
  5571. "'*'\n"
  5572. " matches any substring; ':' separates two patterns.\n"
  5573. " @G--" GTEST_FLAG_PREFIX_
  5574. "also_run_disabled_tests@D\n"
  5575. " Run all disabled tests too.\n"
  5576. "\n"
  5577. "Test Execution:\n"
  5578. " @G--" GTEST_FLAG_PREFIX_
  5579. "repeat=@Y[COUNT]@D\n"
  5580. " Run the tests repeatedly; use a negative count to repeat forever.\n"
  5581. " @G--" GTEST_FLAG_PREFIX_
  5582. "shuffle@D\n"
  5583. " Randomize tests' orders on every iteration.\n"
  5584. " @G--" GTEST_FLAG_PREFIX_
  5585. "random_seed=@Y[NUMBER]@D\n"
  5586. " Random number seed to use for shuffling test orders (between 1 and\n"
  5587. " 99999, or 0 to use a seed based on the current time).\n"
  5588. " @G--" GTEST_FLAG_PREFIX_
  5589. "recreate_environments_when_repeating@D\n"
  5590. " Sets up and tears down the global test environment on each repeat\n"
  5591. " of the test.\n"
  5592. "\n"
  5593. "Test Output:\n"
  5594. " @G--" GTEST_FLAG_PREFIX_
  5595. "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
  5596. " Enable/disable colored output. The default is @Gauto@D.\n"
  5597. " @G--" GTEST_FLAG_PREFIX_
  5598. "brief=1@D\n"
  5599. " Only print test failures.\n"
  5600. " @G--" GTEST_FLAG_PREFIX_
  5601. "print_time=0@D\n"
  5602. " Don't print the elapsed time of each test.\n"
  5603. " @G--" GTEST_FLAG_PREFIX_
  5604. "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
  5605. "@Y|@G:@YFILE_PATH]@D\n"
  5606. " Generate a JSON or XML report in the given directory or with the "
  5607. "given\n"
  5608. " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
  5609. #if GTEST_CAN_STREAM_RESULTS_
  5610. " @G--" GTEST_FLAG_PREFIX_
  5611. "stream_result_to=@YHOST@G:@YPORT@D\n"
  5612. " Stream test results to the given server.\n"
  5613. #endif // GTEST_CAN_STREAM_RESULTS_
  5614. "\n"
  5615. "Assertion Behavior:\n"
  5616. #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  5617. " @G--" GTEST_FLAG_PREFIX_
  5618. "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
  5619. " Set the default death test style.\n"
  5620. #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  5621. " @G--" GTEST_FLAG_PREFIX_
  5622. "break_on_failure@D\n"
  5623. " Turn assertion failures into debugger break-points.\n"
  5624. " @G--" GTEST_FLAG_PREFIX_
  5625. "throw_on_failure@D\n"
  5626. " Turn assertion failures into C++ exceptions for use by an external\n"
  5627. " test framework.\n"
  5628. " @G--" GTEST_FLAG_PREFIX_
  5629. "catch_exceptions=0@D\n"
  5630. " Do not report exceptions as test failures. Instead, allow them\n"
  5631. " to crash the program or throw a pop-up (on Windows).\n"
  5632. "\n"
  5633. "Except for @G--" GTEST_FLAG_PREFIX_
  5634. "list_tests@D, you can alternatively set "
  5635. "the corresponding\n"
  5636. "environment variable of a flag (all letters in upper-case). For example, "
  5637. "to\n"
  5638. "disable colored text output, you can either specify "
  5639. "@G--" GTEST_FLAG_PREFIX_
  5640. "color=no@D or set\n"
  5641. "the @G" GTEST_FLAG_PREFIX_UPPER_
  5642. "COLOR@D environment variable to @Gno@D.\n"
  5643. "\n"
  5644. "For more information, please read the " GTEST_NAME_
  5645. " documentation at\n"
  5646. "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_
  5647. "\n"
  5648. "(not one in your own code or tests), please report it to\n"
  5649. "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
  5650. static bool ParseGoogleTestFlag(const char* const arg) {
  5651. #define GTEST_INTERNAL_PARSE_FLAG(flag_name) \
  5652. do { \
  5653. auto value = GTEST_FLAG_GET(flag_name); \
  5654. if (ParseFlag(arg, #flag_name, &value)) { \
  5655. GTEST_FLAG_SET(flag_name, value); \
  5656. return true; \
  5657. } \
  5658. } while (false)
  5659. GTEST_INTERNAL_PARSE_FLAG(also_run_disabled_tests);
  5660. GTEST_INTERNAL_PARSE_FLAG(break_on_failure);
  5661. GTEST_INTERNAL_PARSE_FLAG(catch_exceptions);
  5662. GTEST_INTERNAL_PARSE_FLAG(color);
  5663. GTEST_INTERNAL_PARSE_FLAG(death_test_style);
  5664. GTEST_INTERNAL_PARSE_FLAG(death_test_use_fork);
  5665. GTEST_INTERNAL_PARSE_FLAG(fail_fast);
  5666. GTEST_INTERNAL_PARSE_FLAG(filter);
  5667. GTEST_INTERNAL_PARSE_FLAG(internal_run_death_test);
  5668. GTEST_INTERNAL_PARSE_FLAG(list_tests);
  5669. GTEST_INTERNAL_PARSE_FLAG(output);
  5670. GTEST_INTERNAL_PARSE_FLAG(brief);
  5671. GTEST_INTERNAL_PARSE_FLAG(print_time);
  5672. GTEST_INTERNAL_PARSE_FLAG(print_utf8);
  5673. GTEST_INTERNAL_PARSE_FLAG(random_seed);
  5674. GTEST_INTERNAL_PARSE_FLAG(repeat);
  5675. GTEST_INTERNAL_PARSE_FLAG(recreate_environments_when_repeating);
  5676. GTEST_INTERNAL_PARSE_FLAG(shuffle);
  5677. GTEST_INTERNAL_PARSE_FLAG(stack_trace_depth);
  5678. GTEST_INTERNAL_PARSE_FLAG(stream_result_to);
  5679. GTEST_INTERNAL_PARSE_FLAG(throw_on_failure);
  5680. return false;
  5681. }
  5682. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  5683. static void LoadFlagsFromFile(const std::string& path) {
  5684. FILE* flagfile = posix::FOpen(path.c_str(), "r");
  5685. if (!flagfile) {
  5686. GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG_GET(flagfile)
  5687. << "\"";
  5688. }
  5689. std::string contents(ReadEntireFile(flagfile));
  5690. posix::FClose(flagfile);
  5691. std::vector<std::string> lines;
  5692. SplitString(contents, '\n', &lines);
  5693. for (size_t i = 0; i < lines.size(); ++i) {
  5694. if (lines[i].empty()) continue;
  5695. if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true;
  5696. }
  5697. }
  5698. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  5699. // Parses the command line for Google Test flags, without initializing
  5700. // other parts of Google Test. The type parameter CharType can be
  5701. // instantiated to either char or wchar_t.
  5702. template <typename CharType>
  5703. void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
  5704. std::string flagfile_value;
  5705. for (int i = 1; i < *argc; i++) {
  5706. const std::string arg_string = StreamableToString(argv[i]);
  5707. const char* const arg = arg_string.c_str();
  5708. using internal::ParseFlag;
  5709. bool remove_flag = false;
  5710. if (ParseGoogleTestFlag(arg)) {
  5711. remove_flag = true;
  5712. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  5713. } else if (ParseFlag(arg, "flagfile", &flagfile_value)) {
  5714. GTEST_FLAG_SET(flagfile, flagfile_value);
  5715. LoadFlagsFromFile(flagfile_value);
  5716. remove_flag = true;
  5717. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  5718. } else if (arg_string == "--help" || HasGoogleTestFlagPrefix(arg)) {
  5719. // Both help flag and unrecognized Google Test flags (excluding
  5720. // internal ones) trigger help display.
  5721. g_help_flag = true;
  5722. }
  5723. if (remove_flag) {
  5724. // Shift the remainder of the argv list left by one. Note
  5725. // that argv has (*argc + 1) elements, the last one always being
  5726. // NULL. The following loop moves the trailing NULL element as
  5727. // well.
  5728. for (int j = i; j != *argc; j++) {
  5729. argv[j] = argv[j + 1];
  5730. }
  5731. // Decrements the argument count.
  5732. (*argc)--;
  5733. // We also need to decrement the iterator as we just removed
  5734. // an element.
  5735. i--;
  5736. }
  5737. }
  5738. if (g_help_flag) {
  5739. // We print the help here instead of in RUN_ALL_TESTS(), as the
  5740. // latter may not be called at all if the user is using Google
  5741. // Test with another testing framework.
  5742. PrintColorEncoded(kColorEncodedHelpMessage);
  5743. }
  5744. }
  5745. // Parses the command line for Google Test flags, without initializing
  5746. // other parts of Google Test.
  5747. void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
  5748. #if GTEST_HAS_ABSL
  5749. if (*argc > 0) {
  5750. // absl::ParseCommandLine() requires *argc > 0.
  5751. auto positional_args = absl::flags_internal::ParseCommandLineImpl(
  5752. *argc, argv, absl::flags_internal::ArgvListAction::kRemoveParsedArgs,
  5753. absl::flags_internal::UsageFlagsAction::kHandleUsage,
  5754. absl::flags_internal::OnUndefinedFlag::kReportUndefined);
  5755. // Any command-line positional arguments not part of any command-line flag
  5756. // (or arguments to a flag) are copied back out to argv, with the program
  5757. // invocation name at position 0, and argc is resized. This includes
  5758. // positional arguments after the flag-terminating delimiter '--'.
  5759. // See https://abseil.io/docs/cpp/guides/flags.
  5760. std::copy(positional_args.begin(), positional_args.end(), argv);
  5761. if (static_cast<int>(positional_args.size()) < *argc) {
  5762. argv[positional_args.size()] = nullptr;
  5763. *argc = static_cast<int>(positional_args.size());
  5764. }
  5765. }
  5766. #else
  5767. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  5768. #endif
  5769. // Fix the value of *_NSGetArgc() on macOS, but if and only if
  5770. // *_NSGetArgv() == argv
  5771. // Only applicable to char** version of argv
  5772. #if GTEST_OS_MAC
  5773. #ifndef GTEST_OS_IOS
  5774. if (*_NSGetArgv() == argv) {
  5775. *_NSGetArgc() = *argc;
  5776. }
  5777. #endif
  5778. #endif
  5779. }
  5780. void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
  5781. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  5782. }
  5783. // The internal implementation of InitGoogleTest().
  5784. //
  5785. // The type parameter CharType can be instantiated to either char or
  5786. // wchar_t.
  5787. template <typename CharType>
  5788. void InitGoogleTestImpl(int* argc, CharType** argv) {
  5789. // We don't want to run the initialization code twice.
  5790. if (GTestIsInitialized()) return;
  5791. if (*argc <= 0) return;
  5792. g_argvs.clear();
  5793. for (int i = 0; i != *argc; i++) {
  5794. g_argvs.push_back(StreamableToString(argv[i]));
  5795. }
  5796. #if GTEST_HAS_ABSL
  5797. absl::InitializeSymbolizer(g_argvs[0].c_str());
  5798. // When using the Abseil Flags library, set the program usage message to the
  5799. // help message, but remove the color-encoding from the message first.
  5800. absl::SetProgramUsageMessage(absl::StrReplaceAll(
  5801. kColorEncodedHelpMessage,
  5802. {{"@D", ""}, {"@R", ""}, {"@G", ""}, {"@Y", ""}, {"@@", "@"}}));
  5803. #endif // GTEST_HAS_ABSL
  5804. ParseGoogleTestFlagsOnly(argc, argv);
  5805. GetUnitTestImpl()->PostFlagParsingInit();
  5806. }
  5807. } // namespace internal
  5808. // Initializes Google Test. This must be called before calling
  5809. // RUN_ALL_TESTS(). In particular, it parses a command line for the
  5810. // flags that Google Test recognizes. Whenever a Google Test flag is
  5811. // seen, it is removed from argv, and *argc is decremented.
  5812. //
  5813. // No value is returned. Instead, the Google Test flag variables are
  5814. // updated.
  5815. //
  5816. // Calling the function for the second time has no user-visible effect.
  5817. void InitGoogleTest(int* argc, char** argv) {
  5818. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5819. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  5820. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5821. internal::InitGoogleTestImpl(argc, argv);
  5822. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5823. }
  5824. // This overloaded version can be used in Windows programs compiled in
  5825. // UNICODE mode.
  5826. void InitGoogleTest(int* argc, wchar_t** argv) {
  5827. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5828. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  5829. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5830. internal::InitGoogleTestImpl(argc, argv);
  5831. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5832. }
  5833. // This overloaded version can be used on Arduino/embedded platforms where
  5834. // there is no argc/argv.
  5835. void InitGoogleTest() {
  5836. // Since Arduino doesn't have a command line, fake out the argc/argv arguments
  5837. int argc = 1;
  5838. const auto arg0 = "dummy";
  5839. char* argv0 = const_cast<char*>(arg0);
  5840. char** argv = &argv0;
  5841. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5842. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
  5843. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5844. internal::InitGoogleTestImpl(&argc, argv);
  5845. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  5846. }
  5847. #if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
  5848. // Return value of first environment variable that is set and contains
  5849. // a non-empty string. If there are none, return the "fallback" string.
  5850. // Since we like the temporary directory to have a directory separator suffix,
  5851. // add it if not provided in the environment variable value.
  5852. static std::string GetTempDirFromEnv(
  5853. std::initializer_list<const char*> environment_variables,
  5854. const char* fallback, char separator) {
  5855. for (const char* variable_name : environment_variables) {
  5856. const char* value = internal::posix::GetEnv(variable_name);
  5857. if (value != nullptr && value[0] != '\0') {
  5858. if (value[strlen(value) - 1] != separator) {
  5859. return std::string(value).append(1, separator);
  5860. }
  5861. return value;
  5862. }
  5863. }
  5864. return fallback;
  5865. }
  5866. #endif
  5867. std::string TempDir() {
  5868. #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
  5869. return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
  5870. #elif GTEST_OS_WINDOWS || GTEST_OS_WINDOWS_MOBILE
  5871. return GetTempDirFromEnv({"TEST_TMPDIR", "TEMP"}, "\\temp\\", '\\');
  5872. #elif GTEST_OS_LINUX_ANDROID
  5873. return GetTempDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/data/local/tmp/", '/');
  5874. #else
  5875. return GetTempDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/tmp/", '/');
  5876. #endif
  5877. }
  5878. // Class ScopedTrace
  5879. // Pushes the given source file location and message onto a per-thread
  5880. // trace stack maintained by Google Test.
  5881. void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
  5882. internal::TraceInfo trace;
  5883. trace.file = file;
  5884. trace.line = line;
  5885. trace.message.swap(message);
  5886. UnitTest::GetInstance()->PushGTestTrace(trace);
  5887. }
  5888. // Pops the info pushed by the c'tor.
  5889. ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
  5890. UnitTest::GetInstance()->PopGTestTrace();
  5891. }
  5892. } // namespace testing