gtest-all.cc 329 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132
  1. // Copyright 2008, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Author: [email protected] (Markus Heule)
  31. //
  32. // Google C++ Testing Framework (Google Test)
  33. //
  34. // Sometimes it's desirable to build Google Test by compiling a single file.
  35. // This file serves this purpose.
  36. // This line ensures that gtest.h can be compiled on its own, even
  37. // when it's fused.
  38. #include "gtest/gtest.h"
  39. #if __clang__
  40. #pragma clang diagnostic push
  41. #pragma clang diagnostic ignored "-Wsign-conversion"
  42. #elif __GNUC__
  43. #pragma GCC diagnostic push
  44. #pragma GCC diagnostic ignored "-Wsign-conversion"
  45. #pragma GCC diagnostic ignored "-Wconversion"
  46. #endif
  47. // The following lines pull in the real gtest *.cc files.
  48. // Copyright 2005, Google Inc.
  49. // All rights reserved.
  50. //
  51. // Redistribution and use in source and binary forms, with or without
  52. // modification, are permitted provided that the following conditions are
  53. // met:
  54. //
  55. // * Redistributions of source code must retain the above copyright
  56. // notice, this list of conditions and the following disclaimer.
  57. // * Redistributions in binary form must reproduce the above
  58. // copyright notice, this list of conditions and the following disclaimer
  59. // in the documentation and/or other materials provided with the
  60. // distribution.
  61. // * Neither the name of Google Inc. nor the names of its
  62. // contributors may be used to endorse or promote products derived from
  63. // this software without specific prior written permission.
  64. //
  65. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  66. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  67. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  68. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  69. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  70. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  71. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  72. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  73. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  74. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  75. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  76. //
  77. // Author: [email protected] (Zhanyong Wan)
  78. //
  79. // The Google C++ Testing Framework (Google Test)
  80. // Copyright 2007, Google Inc.
  81. // All rights reserved.
  82. //
  83. // Redistribution and use in source and binary forms, with or without
  84. // modification, are permitted provided that the following conditions are
  85. // met:
  86. //
  87. // * Redistributions of source code must retain the above copyright
  88. // notice, this list of conditions and the following disclaimer.
  89. // * Redistributions in binary form must reproduce the above
  90. // copyright notice, this list of conditions and the following disclaimer
  91. // in the documentation and/or other materials provided with the
  92. // distribution.
  93. // * Neither the name of Google Inc. nor the names of its
  94. // contributors may be used to endorse or promote products derived from
  95. // this software without specific prior written permission.
  96. //
  97. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  98. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  99. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  100. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  101. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  102. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  103. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  104. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  105. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  106. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  107. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  108. //
  109. // Author: [email protected] (Zhanyong Wan)
  110. //
  111. // Utilities for testing Google Test itself and code that uses Google Test
  112. // (e.g. frameworks built on top of Google Test).
  113. #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
  114. #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
  115. namespace testing {
  116. // This helper class can be used to mock out Google Test failure reporting
  117. // so that we can test Google Test or code that builds on Google Test.
  118. //
  119. // An object of this class appends a TestPartResult object to the
  120. // TestPartResultArray object given in the constructor whenever a Google Test
  121. // failure is reported. It can either intercept only failures that are
  122. // generated in the same thread that created this object or it can intercept
  123. // all generated failures. The scope of this mock object can be controlled with
  124. // the second argument to the two arguments constructor.
  125. class GTEST_API_ ScopedFakeTestPartResultReporter
  126. : public TestPartResultReporterInterface {
  127. public:
  128. // The two possible mocking modes of this object.
  129. enum InterceptMode {
  130. INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
  131. INTERCEPT_ALL_THREADS // Intercepts all failures.
  132. };
  133. // The c'tor sets this object as the test part result reporter used
  134. // by Google Test. The 'result' parameter specifies where to report the
  135. // results. This reporter will only catch failures generated in the current
  136. // thread. DEPRECATED
  137. explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
  138. // Same as above, but you can choose the interception scope of this object.
  139. ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
  140. TestPartResultArray* result);
  141. // The d'tor restores the previous test part result reporter.
  142. virtual ~ScopedFakeTestPartResultReporter();
  143. // Appends the TestPartResult object to the TestPartResultArray
  144. // received in the constructor.
  145. //
  146. // This method is from the TestPartResultReporterInterface
  147. // interface.
  148. virtual void ReportTestPartResult(const TestPartResult& result);
  149. private:
  150. void Init();
  151. const InterceptMode intercept_mode_;
  152. TestPartResultReporterInterface* old_reporter_;
  153. TestPartResultArray* const result_;
  154. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
  155. };
  156. namespace internal {
  157. // A helper class for implementing EXPECT_FATAL_FAILURE() and
  158. // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
  159. // TestPartResultArray contains exactly one failure that has the given
  160. // type and contains the given substring. If that's not the case, a
  161. // non-fatal failure will be generated.
  162. class GTEST_API_ SingleFailureChecker {
  163. public:
  164. // The constructor remembers the arguments.
  165. SingleFailureChecker(const TestPartResultArray* results,
  166. TestPartResult::Type type,
  167. const string& substr);
  168. ~SingleFailureChecker();
  169. private:
  170. const TestPartResultArray* const results_;
  171. const TestPartResult::Type type_;
  172. const string substr_;
  173. GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
  174. };
  175. } // namespace internal
  176. } // namespace testing
  177. // A set of macros for testing Google Test assertions or code that's expected
  178. // to generate Google Test fatal failures. It verifies that the given
  179. // statement will cause exactly one fatal Google Test failure with 'substr'
  180. // being part of the failure message.
  181. //
  182. // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
  183. // affects and considers failures generated in the current thread and
  184. // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
  185. //
  186. // The verification of the assertion is done correctly even when the statement
  187. // throws an exception or aborts the current function.
  188. //
  189. // Known restrictions:
  190. // - 'statement' cannot reference local non-static variables or
  191. // non-static members of the current object.
  192. // - 'statement' cannot return a value.
  193. // - You cannot stream a failure message to this macro.
  194. //
  195. // Note that even though the implementations of the following two
  196. // macros are much alike, we cannot refactor them to use a common
  197. // helper macro, due to some peculiarity in how the preprocessor
  198. // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
  199. // gtest_unittest.cc will fail to compile if we do that.
  200. #define EXPECT_FATAL_FAILURE(statement, substr) \
  201. do { \
  202. class GTestExpectFatalFailureHelper {\
  203. public:\
  204. static void Execute() { statement; }\
  205. };\
  206. ::testing::TestPartResultArray gtest_failures;\
  207. ::testing::internal::SingleFailureChecker gtest_checker(\
  208. &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
  209. {\
  210. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  211. ::testing::ScopedFakeTestPartResultReporter:: \
  212. INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
  213. GTestExpectFatalFailureHelper::Execute();\
  214. }\
  215. } while (::testing::internal::AlwaysFalse())
  216. #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
  217. do { \
  218. class GTestExpectFatalFailureHelper {\
  219. public:\
  220. static void Execute() { statement; }\
  221. };\
  222. ::testing::TestPartResultArray gtest_failures;\
  223. ::testing::internal::SingleFailureChecker gtest_checker(\
  224. &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
  225. {\
  226. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  227. ::testing::ScopedFakeTestPartResultReporter:: \
  228. INTERCEPT_ALL_THREADS, &gtest_failures);\
  229. GTestExpectFatalFailureHelper::Execute();\
  230. }\
  231. } while (::testing::internal::AlwaysFalse())
  232. // A macro for testing Google Test assertions or code that's expected to
  233. // generate Google Test non-fatal failures. It asserts that the given
  234. // statement will cause exactly one non-fatal Google Test failure with 'substr'
  235. // being part of the failure message.
  236. //
  237. // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
  238. // affects and considers failures generated in the current thread and
  239. // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
  240. //
  241. // 'statement' is allowed to reference local variables and members of
  242. // the current object.
  243. //
  244. // The verification of the assertion is done correctly even when the statement
  245. // throws an exception or aborts the current function.
  246. //
  247. // Known restrictions:
  248. // - You cannot stream a failure message to this macro.
  249. //
  250. // Note that even though the implementations of the following two
  251. // macros are much alike, we cannot refactor them to use a common
  252. // helper macro, due to some peculiarity in how the preprocessor
  253. // works. If we do that, the code won't compile when the user gives
  254. // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
  255. // expands to code containing an unprotected comma. The
  256. // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
  257. // catches that.
  258. //
  259. // For the same reason, we have to write
  260. // if (::testing::internal::AlwaysTrue()) { statement; }
  261. // instead of
  262. // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
  263. // to avoid an MSVC warning on unreachable code.
  264. #define EXPECT_NONFATAL_FAILURE(statement, substr) \
  265. do {\
  266. ::testing::TestPartResultArray gtest_failures;\
  267. ::testing::internal::SingleFailureChecker gtest_checker(\
  268. &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
  269. (substr));\
  270. {\
  271. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  272. ::testing::ScopedFakeTestPartResultReporter:: \
  273. INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
  274. if (::testing::internal::AlwaysTrue()) { statement; }\
  275. }\
  276. } while (::testing::internal::AlwaysFalse())
  277. #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
  278. do {\
  279. ::testing::TestPartResultArray gtest_failures;\
  280. ::testing::internal::SingleFailureChecker gtest_checker(\
  281. &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
  282. (substr));\
  283. {\
  284. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  285. ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS,\
  286. &gtest_failures);\
  287. if (::testing::internal::AlwaysTrue()) { statement; }\
  288. }\
  289. } while (::testing::internal::AlwaysFalse())
  290. #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
  291. #include <ctype.h>
  292. #include <math.h>
  293. #include <stdarg.h>
  294. #include <stdio.h>
  295. #include <stdlib.h>
  296. #include <wchar.h>
  297. #include <wctype.h>
  298. #include <algorithm>
  299. #include <ostream> // NOLINT
  300. #include <sstream>
  301. #include <vector>
  302. #if GTEST_OS_LINUX
  303. // TODO([email protected]): Use autoconf to detect availability of
  304. // gettimeofday().
  305. # define GTEST_HAS_GETTIMEOFDAY_ 1
  306. # include <fcntl.h> // NOLINT
  307. # include <limits.h> // NOLINT
  308. # include <sched.h> // NOLINT
  309. // Declares vsnprintf(). This header is not available on Windows.
  310. # include <strings.h> // NOLINT
  311. # include <sys/mman.h> // NOLINT
  312. # include <sys/time.h> // NOLINT
  313. # include <unistd.h> // NOLINT
  314. # include <string>
  315. #elif GTEST_OS_SYMBIAN
  316. # define GTEST_HAS_GETTIMEOFDAY_ 1
  317. # include <sys/time.h> // NOLINT
  318. #elif GTEST_OS_ZOS
  319. # define GTEST_HAS_GETTIMEOFDAY_ 1
  320. # include <sys/time.h> // NOLINT
  321. // On z/OS we additionally need strings.h for strcasecmp.
  322. # include <strings.h> // NOLINT
  323. #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
  324. # include <windows.h> // NOLINT
  325. #elif GTEST_OS_WINDOWS // We are on Windows proper.
  326. # include <io.h> // NOLINT
  327. # include <sys/timeb.h> // NOLINT
  328. # include <sys/types.h> // NOLINT
  329. # include <sys/stat.h> // NOLINT
  330. # if GTEST_OS_WINDOWS_MINGW
  331. // MinGW has gettimeofday() but not _ftime64().
  332. // TODO([email protected]): Use autoconf to detect availability of
  333. // gettimeofday().
  334. // TODO([email protected]): There are other ways to get the time on
  335. // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
  336. // supports these. consider using them instead.
  337. # define GTEST_HAS_GETTIMEOFDAY_ 1
  338. # include <sys/time.h> // NOLINT
  339. # endif // GTEST_OS_WINDOWS_MINGW
  340. // cpplint thinks that the header is already included, so we want to
  341. // silence it.
  342. # include <windows.h> // NOLINT
  343. #else
  344. // Assume other platforms have gettimeofday().
  345. // TODO([email protected]): Use autoconf to detect availability of
  346. // gettimeofday().
  347. # define GTEST_HAS_GETTIMEOFDAY_ 1
  348. // cpplint thinks that the header is already included, so we want to
  349. // silence it.
  350. # include <sys/time.h> // NOLINT
  351. # include <unistd.h> // NOLINT
  352. #endif // GTEST_OS_LINUX
  353. #if GTEST_HAS_EXCEPTIONS
  354. # include <stdexcept>
  355. #endif
  356. #if GTEST_CAN_STREAM_RESULTS_
  357. # include <arpa/inet.h> // NOLINT
  358. # include <netdb.h> // NOLINT
  359. #endif
  360. // Indicates that this translation unit is part of Google Test's
  361. // implementation. It must come before gtest-internal-inl.h is
  362. // included, or there will be a compiler error. This trick is to
  363. // prevent a user from accidentally including gtest-internal-inl.h in
  364. // his code.
  365. #define GTEST_IMPLEMENTATION_ 1
  366. // Copyright 2005, Google Inc.
  367. // All rights reserved.
  368. //
  369. // Redistribution and use in source and binary forms, with or without
  370. // modification, are permitted provided that the following conditions are
  371. // met:
  372. //
  373. // * Redistributions of source code must retain the above copyright
  374. // notice, this list of conditions and the following disclaimer.
  375. // * Redistributions in binary form must reproduce the above
  376. // copyright notice, this list of conditions and the following disclaimer
  377. // in the documentation and/or other materials provided with the
  378. // distribution.
  379. // * Neither the name of Google Inc. nor the names of its
  380. // contributors may be used to endorse or promote products derived from
  381. // this software without specific prior written permission.
  382. //
  383. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  384. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  385. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  386. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  387. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  388. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  389. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  390. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  391. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  392. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  393. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  394. // Utility functions and classes used by the Google C++ testing framework.
  395. //
  396. // Author: [email protected] (Zhanyong Wan)
  397. //
  398. // This file contains purely Google Test's internal implementation. Please
  399. // DO NOT #INCLUDE IT IN A USER PROGRAM.
  400. #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
  401. #define GTEST_SRC_GTEST_INTERNAL_INL_H_
  402. // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
  403. // part of Google Test's implementation; otherwise it's undefined.
  404. #if !GTEST_IMPLEMENTATION_
  405. // A user is trying to include this from his code - just say no.
  406. # error "gtest-internal-inl.h is part of Google Test's internal implementation."
  407. # error "It must not be included except by Google Test itself."
  408. #endif // GTEST_IMPLEMENTATION_
  409. #ifndef _WIN32_WCE
  410. # include <errno.h>
  411. #endif // !_WIN32_WCE
  412. #include <stddef.h>
  413. #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
  414. #include <string.h> // For memmove.
  415. #include <algorithm>
  416. #include <string>
  417. #include <vector>
  418. #if GTEST_OS_WINDOWS
  419. # include <windows.h> // NOLINT
  420. #endif // GTEST_OS_WINDOWS
  421. namespace testing {
  422. // Declares the flags.
  423. //
  424. // We don't want the users to modify this flag in the code, but want
  425. // Google Test's own unit tests to be able to access it. Therefore we
  426. // declare it here as opposed to in gtest.h.
  427. GTEST_DECLARE_bool_(death_test_use_fork);
  428. namespace internal {
  429. // The value of GetTestTypeId() as seen from within the Google Test
  430. // library. This is solely for testing GetTestTypeId().
  431. GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
  432. // Names of the flags (needed for parsing Google Test flags).
  433. const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
  434. const char kBreakOnFailureFlag[] = "break_on_failure";
  435. const char kCatchExceptionsFlag[] = "catch_exceptions";
  436. const char kColorFlag[] = "color";
  437. const char kFilterFlag[] = "filter";
  438. const char kListTestsFlag[] = "list_tests";
  439. const char kOutputFlag[] = "output";
  440. const char kPrintTimeFlag[] = "print_time";
  441. const char kRandomSeedFlag[] = "random_seed";
  442. const char kRepeatFlag[] = "repeat";
  443. const char kShuffleFlag[] = "shuffle";
  444. const char kStackTraceDepthFlag[] = "stack_trace_depth";
  445. const char kStreamResultToFlag[] = "stream_result_to";
  446. const char kThrowOnFailureFlag[] = "throw_on_failure";
  447. // A valid random seed must be in [1, kMaxRandomSeed].
  448. const int kMaxRandomSeed = 99999;
  449. // g_help_flag is true iff the --help flag or an equivalent form is
  450. // specified on the command line.
  451. GTEST_API_ extern bool g_help_flag;
  452. // Returns the current time in milliseconds.
  453. GTEST_API_ TimeInMillis GetTimeInMillis();
  454. // Returns true iff Google Test should use colors in the output.
  455. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
  456. // Formats the given time in milliseconds as seconds.
  457. GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
  458. // Parses a string for an Int32 flag, in the form of "--flag=value".
  459. //
  460. // On success, stores the value of the flag in *value, and returns
  461. // true. On failure, returns false without changing *value.
  462. GTEST_API_ bool ParseInt32Flag(
  463. const char* str, const char* flag, Int32* value);
  464. // Returns a random seed in range [1, kMaxRandomSeed] based on the
  465. // given --gtest_random_seed flag value.
  466. inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
  467. const unsigned int raw_seed = (random_seed_flag == 0) ?
  468. static_cast<unsigned int>(GetTimeInMillis()) :
  469. static_cast<unsigned int>(random_seed_flag);
  470. // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
  471. // it's easy to type.
  472. const int normalized_seed =
  473. static_cast<int>((raw_seed - 1U) %
  474. static_cast<unsigned int>(kMaxRandomSeed)) + 1;
  475. return normalized_seed;
  476. }
  477. // Returns the first valid random seed after 'seed'. The behavior is
  478. // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
  479. // considered to be 1.
  480. inline int GetNextRandomSeed(int seed) {
  481. GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
  482. << "Invalid random seed " << seed << " - must be in [1, "
  483. << kMaxRandomSeed << "].";
  484. const int next_seed = seed + 1;
  485. return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
  486. }
  487. // This class saves the values of all Google Test flags in its c'tor, and
  488. // restores them in its d'tor.
  489. class GTestFlagSaver {
  490. public:
  491. // The c'tor.
  492. GTestFlagSaver() {
  493. also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
  494. break_on_failure_ = GTEST_FLAG(break_on_failure);
  495. catch_exceptions_ = GTEST_FLAG(catch_exceptions);
  496. color_ = GTEST_FLAG(color);
  497. death_test_style_ = GTEST_FLAG(death_test_style);
  498. death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
  499. filter_ = GTEST_FLAG(filter);
  500. internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
  501. list_tests_ = GTEST_FLAG(list_tests);
  502. output_ = GTEST_FLAG(output);
  503. print_time_ = GTEST_FLAG(print_time);
  504. random_seed_ = GTEST_FLAG(random_seed);
  505. repeat_ = GTEST_FLAG(repeat);
  506. shuffle_ = GTEST_FLAG(shuffle);
  507. stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
  508. stream_result_to_ = GTEST_FLAG(stream_result_to);
  509. throw_on_failure_ = GTEST_FLAG(throw_on_failure);
  510. }
  511. // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
  512. ~GTestFlagSaver() {
  513. GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
  514. GTEST_FLAG(break_on_failure) = break_on_failure_;
  515. GTEST_FLAG(catch_exceptions) = catch_exceptions_;
  516. GTEST_FLAG(color) = color_;
  517. GTEST_FLAG(death_test_style) = death_test_style_;
  518. GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
  519. GTEST_FLAG(filter) = filter_;
  520. GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
  521. GTEST_FLAG(list_tests) = list_tests_;
  522. GTEST_FLAG(output) = output_;
  523. GTEST_FLAG(print_time) = print_time_;
  524. GTEST_FLAG(random_seed) = random_seed_;
  525. GTEST_FLAG(repeat) = repeat_;
  526. GTEST_FLAG(shuffle) = shuffle_;
  527. GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
  528. GTEST_FLAG(stream_result_to) = stream_result_to_;
  529. GTEST_FLAG(throw_on_failure) = throw_on_failure_;
  530. }
  531. private:
  532. // Fields for saving the original values of flags.
  533. bool also_run_disabled_tests_;
  534. bool break_on_failure_;
  535. bool catch_exceptions_;
  536. String color_;
  537. String death_test_style_;
  538. bool death_test_use_fork_;
  539. String filter_;
  540. String internal_run_death_test_;
  541. bool list_tests_;
  542. String output_;
  543. bool print_time_;
  544. // bool pretty_;
  545. internal::Int32 random_seed_;
  546. internal::Int32 repeat_;
  547. bool shuffle_;
  548. internal::Int32 stack_trace_depth_;
  549. String stream_result_to_;
  550. bool throw_on_failure_;
  551. } GTEST_ATTRIBUTE_UNUSED_;
  552. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  553. // code_point parameter is of type UInt32 because wchar_t may not be
  554. // wide enough to contain a code point.
  555. // The output buffer str must containt at least 32 characters.
  556. // The function returns the address of the output buffer.
  557. // If the code_point is not a valid Unicode code point
  558. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
  559. // as '(Invalid Unicode 0xXXXXXXXX)'.
  560. GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str);
  561. // Converts a wide string to a narrow string in UTF-8 encoding.
  562. // The wide string is assumed to have the following encoding:
  563. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
  564. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  565. // Parameter str points to a null-terminated wide string.
  566. // Parameter num_chars may additionally limit the number
  567. // of wchar_t characters processed. -1 is used when the entire string
  568. // should be processed.
  569. // If the string contains code points that are not valid Unicode code points
  570. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  571. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  572. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  573. // will be encoded as individual Unicode characters from Basic Normal Plane.
  574. GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars);
  575. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  576. // if the variable is present. If a file already exists at this location, this
  577. // function will write over it. If the variable is present, but the file cannot
  578. // be created, prints an error and exits.
  579. void WriteToShardStatusFileIfNeeded();
  580. // Checks whether sharding is enabled by examining the relevant
  581. // environment variable values. If the variables are present,
  582. // but inconsistent (e.g., shard_index >= total_shards), prints
  583. // an error and exits. If in_subprocess_for_death_test, sharding is
  584. // disabled because it must only be applied to the original test
  585. // process. Otherwise, we could filter out death tests we intended to execute.
  586. GTEST_API_ bool ShouldShard(const char* total_shards_str,
  587. const char* shard_index_str,
  588. bool in_subprocess_for_death_test);
  589. // Parses the environment variable var as an Int32. If it is unset,
  590. // returns default_val. If it is not an Int32, prints an error and
  591. // and aborts.
  592. GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
  593. // Given the total number of shards, the shard index, and the test id,
  594. // returns true iff the test should be run on this shard. The test id is
  595. // some arbitrary but unique non-negative integer assigned to each test
  596. // method. Assumes that 0 <= shard_index < total_shards.
  597. GTEST_API_ bool ShouldRunTestOnShard(
  598. int total_shards, int shard_index, int test_id);
  599. // STL container utilities.
  600. // Returns the number of elements in the given container that satisfy
  601. // the given predicate.
  602. template <class Container, typename Predicate>
  603. inline int CountIf(const Container& c, Predicate predicate) {
  604. // Implemented as an explicit loop since std::count_if() in libCstd on
  605. // Solaris has a non-standard signature.
  606. int count = 0;
  607. for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
  608. if (predicate(*it))
  609. ++count;
  610. }
  611. return count;
  612. }
  613. // Applies a function/functor to each element in the container.
  614. template <class Container, typename Functor>
  615. void ForEach(const Container& c, Functor functor) {
  616. std::for_each(c.begin(), c.end(), functor);
  617. }
  618. // Returns the i-th element of the vector, or default_value if i is not
  619. // in range [0, v.size()).
  620. template <typename E>
  621. inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
  622. return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
  623. }
  624. // Performs an in-place shuffle of a range of the vector's elements.
  625. // 'begin' and 'end' are element indices as an STL-style range;
  626. // i.e. [begin, end) are shuffled, where 'end' == size() means to
  627. // shuffle to the end of the vector.
  628. template <typename E>
  629. void ShuffleRange(internal::Random* random, int begin, int end,
  630. std::vector<E>* v) {
  631. const int size = static_cast<int>(v->size());
  632. GTEST_CHECK_(0 <= begin && begin <= size)
  633. << "Invalid shuffle range start " << begin << ": must be in range [0, "
  634. << size << "].";
  635. GTEST_CHECK_(begin <= end && end <= size)
  636. << "Invalid shuffle range finish " << end << ": must be in range ["
  637. << begin << ", " << size << "].";
  638. // Fisher-Yates shuffle, from
  639. // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  640. for (int range_width = end - begin; range_width >= 2; range_width--) {
  641. const int last_in_range = begin + range_width - 1;
  642. const int selected = begin + random->Generate(range_width);
  643. std::swap((*v)[selected], (*v)[last_in_range]);
  644. }
  645. }
  646. // Performs an in-place shuffle of the vector's elements.
  647. template <typename E>
  648. inline void Shuffle(internal::Random* random, std::vector<E>* v) {
  649. ShuffleRange(random, 0, static_cast<int>(v->size()), v);
  650. }
  651. // A function for deleting an object. Handy for being used as a
  652. // functor.
  653. template <typename T>
  654. static void Delete(T* x) {
  655. delete x;
  656. }
  657. // A predicate that checks the key of a TestProperty against a known key.
  658. //
  659. // TestPropertyKeyIs is copyable.
  660. class TestPropertyKeyIs {
  661. public:
  662. // Constructor.
  663. //
  664. // TestPropertyKeyIs has NO default constructor.
  665. explicit TestPropertyKeyIs(const char* key)
  666. : key_(key) {}
  667. // Returns true iff the test name of test property matches on key_.
  668. bool operator()(const TestProperty& test_property) const {
  669. return String(test_property.key()).Compare(key_) == 0;
  670. }
  671. private:
  672. String key_;
  673. };
  674. // Class UnitTestOptions.
  675. //
  676. // This class contains functions for processing options the user
  677. // specifies when running the tests. It has only static members.
  678. //
  679. // In most cases, the user can specify an option using either an
  680. // environment variable or a command line flag. E.g. you can set the
  681. // test filter using either GTEST_FILTER or --gtest_filter. If both
  682. // the variable and the flag are present, the latter overrides the
  683. // former.
  684. class GTEST_API_ UnitTestOptions {
  685. public:
  686. // Functions for processing the gtest_output flag.
  687. // Returns the output format, or "" for normal printed output.
  688. static String GetOutputFormat();
  689. // Returns the absolute path of the requested output file, or the
  690. // default (test_detail.xml in the original working directory) if
  691. // none was explicitly specified.
  692. static String GetAbsolutePathToOutputFile();
  693. // Functions for processing the gtest_filter flag.
  694. // Returns true iff the wildcard pattern matches the string. The
  695. // first ':' or '\0' character in pattern marks the end of it.
  696. //
  697. // This recursive algorithm isn't very efficient, but is clear and
  698. // works well enough for matching test names, which are short.
  699. static bool PatternMatchesString(const char *pattern, const char *str);
  700. // Returns true iff the user-specified filter matches the test case
  701. // name and the test name.
  702. static bool FilterMatchesTest(const String &test_case_name,
  703. const String &test_name);
  704. #if GTEST_OS_WINDOWS
  705. // Function for supporting the gtest_catch_exception flag.
  706. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  707. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  708. // This function is useful as an __except condition.
  709. static int GTestShouldProcessSEH(DWORD exception_code);
  710. #endif // GTEST_OS_WINDOWS
  711. // Returns true if "name" matches the ':' separated list of glob-style
  712. // filters in "filter".
  713. static bool MatchesFilter(const String& name, const char* filter);
  714. };
  715. // Returns the current application's name, removing directory path if that
  716. // is present. Used by UnitTestOptions::GetOutputFile.
  717. GTEST_API_ FilePath GetCurrentExecutableName();
  718. // The role interface for getting the OS stack trace as a string.
  719. class OsStackTraceGetterInterface {
  720. public:
  721. OsStackTraceGetterInterface() {}
  722. virtual ~OsStackTraceGetterInterface() {}
  723. // Returns the current OS stack trace as a String. Parameters:
  724. //
  725. // max_depth - the maximum number of stack frames to be included
  726. // in the trace.
  727. // skip_count - the number of top frames to be skipped; doesn't count
  728. // against max_depth.
  729. virtual String CurrentStackTrace(int max_depth, int skip_count) = 0;
  730. // UponLeavingGTest() should be called immediately before Google Test calls
  731. // user code. It saves some information about the current stack that
  732. // CurrentStackTrace() will use to find and hide Google Test stack frames.
  733. virtual void UponLeavingGTest() = 0;
  734. private:
  735. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
  736. };
  737. // A working implementation of the OsStackTraceGetterInterface interface.
  738. class OsStackTraceGetter : public OsStackTraceGetterInterface {
  739. public:
  740. OsStackTraceGetter() : caller_frame_(NULL) {}
  741. virtual String CurrentStackTrace(int max_depth, int skip_count);
  742. virtual void UponLeavingGTest();
  743. // This string is inserted in place of stack frames that are part of
  744. // Google Test's implementation.
  745. static const char* const kElidedFramesMarker;
  746. private:
  747. Mutex mutex_; // protects all internal state
  748. // We save the stack frame below the frame that calls user code.
  749. // We do this because the address of the frame immediately below
  750. // the user code changes between the call to UponLeavingGTest()
  751. // and any calls to CurrentStackTrace() from within the user code.
  752. void* caller_frame_;
  753. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
  754. };
  755. // Information about a Google Test trace point.
  756. struct TraceInfo {
  757. const char* file;
  758. int line;
  759. String message;
  760. };
  761. // This is the default global test part result reporter used in UnitTestImpl.
  762. // This class should only be used by UnitTestImpl.
  763. class DefaultGlobalTestPartResultReporter
  764. : public TestPartResultReporterInterface {
  765. public:
  766. explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
  767. // Implements the TestPartResultReporterInterface. Reports the test part
  768. // result in the current test.
  769. virtual void ReportTestPartResult(const TestPartResult& result);
  770. private:
  771. UnitTestImpl* const unit_test_;
  772. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
  773. };
  774. // This is the default per thread test part result reporter used in
  775. // UnitTestImpl. This class should only be used by UnitTestImpl.
  776. class DefaultPerThreadTestPartResultReporter
  777. : public TestPartResultReporterInterface {
  778. public:
  779. explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
  780. // Implements the TestPartResultReporterInterface. The implementation just
  781. // delegates to the current global test part result reporter of *unit_test_.
  782. virtual void ReportTestPartResult(const TestPartResult& result);
  783. private:
  784. UnitTestImpl* const unit_test_;
  785. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
  786. };
  787. // The private implementation of the UnitTest class. We don't protect
  788. // the methods under a mutex, as this class is not accessible by a
  789. // user and the UnitTest class that delegates work to this class does
  790. // proper locking.
  791. class GTEST_API_ UnitTestImpl {
  792. public:
  793. explicit UnitTestImpl(UnitTest* parent);
  794. virtual ~UnitTestImpl();
  795. // There are two different ways to register your own TestPartResultReporter.
  796. // You can register your own repoter to listen either only for test results
  797. // from the current thread or for results from all threads.
  798. // By default, each per-thread test result repoter just passes a new
  799. // TestPartResult to the global test result reporter, which registers the
  800. // test part result for the currently running test.
  801. // Returns the global test part result reporter.
  802. TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
  803. // Sets the global test part result reporter.
  804. void SetGlobalTestPartResultReporter(
  805. TestPartResultReporterInterface* reporter);
  806. // Returns the test part result reporter for the current thread.
  807. TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
  808. // Sets the test part result reporter for the current thread.
  809. void SetTestPartResultReporterForCurrentThread(
  810. TestPartResultReporterInterface* reporter);
  811. // Gets the number of successful test cases.
  812. int successful_test_case_count() const;
  813. // Gets the number of failed test cases.
  814. int failed_test_case_count() const;
  815. // Gets the number of all test cases.
  816. int total_test_case_count() const;
  817. // Gets the number of all test cases that contain at least one test
  818. // that should run.
  819. int test_case_to_run_count() const;
  820. // Gets the number of successful tests.
  821. int successful_test_count() const;
  822. // Gets the number of failed tests.
  823. int failed_test_count() const;
  824. // Gets the number of disabled tests.
  825. int disabled_test_count() const;
  826. // Gets the number of all tests.
  827. int total_test_count() const;
  828. // Gets the number of tests that should run.
  829. int test_to_run_count() const;
  830. // Gets the elapsed time, in milliseconds.
  831. TimeInMillis elapsed_time() const { return elapsed_time_; }
  832. // Returns true iff the unit test passed (i.e. all test cases passed).
  833. bool Passed() const { return !Failed(); }
  834. // Returns true iff the unit test failed (i.e. some test case failed
  835. // or something outside of all tests failed).
  836. bool Failed() const {
  837. return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
  838. }
  839. // Gets the i-th test case among all the test cases. i can range from 0 to
  840. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  841. const TestCase* GetTestCase(int i) const {
  842. const int index = GetElementOr(test_case_indices_, i, -1);
  843. return index < 0 ? NULL : test_cases_[i];
  844. }
  845. // Gets the i-th test case among all the test cases. i can range from 0 to
  846. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  847. TestCase* GetMutableTestCase(int i) {
  848. const int index = GetElementOr(test_case_indices_, i, -1);
  849. return index < 0 ? NULL : test_cases_[index];
  850. }
  851. // Provides access to the event listener list.
  852. TestEventListeners* listeners() { return &listeners_; }
  853. // Returns the TestResult for the test that's currently running, or
  854. // the TestResult for the ad hoc test if no test is running.
  855. TestResult* current_test_result();
  856. // Returns the TestResult for the ad hoc test.
  857. const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
  858. // Sets the OS stack trace getter.
  859. //
  860. // Does nothing if the input and the current OS stack trace getter
  861. // are the same; otherwise, deletes the old getter and makes the
  862. // input the current getter.
  863. void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
  864. // Returns the current OS stack trace getter if it is not NULL;
  865. // otherwise, creates an OsStackTraceGetter, makes it the current
  866. // getter, and returns it.
  867. OsStackTraceGetterInterface* os_stack_trace_getter();
  868. // Returns the current OS stack trace as a String.
  869. //
  870. // The maximum number of stack frames to be included is specified by
  871. // the gtest_stack_trace_depth flag. The skip_count parameter
  872. // specifies the number of top frames to be skipped, which doesn't
  873. // count against the number of frames to be included.
  874. //
  875. // For example, if Foo() calls Bar(), which in turn calls
  876. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  877. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  878. String CurrentOsStackTraceExceptTop(int skip_count);
  879. // Finds and returns a TestCase with the given name. If one doesn't
  880. // exist, creates one and returns it.
  881. //
  882. // Arguments:
  883. //
  884. // test_case_name: name of the test case
  885. // type_param: the name of the test's type parameter, or NULL if
  886. // this is not a typed or a type-parameterized test.
  887. // set_up_tc: pointer to the function that sets up the test case
  888. // tear_down_tc: pointer to the function that tears down the test case
  889. TestCase* GetTestCase(const char* test_case_name,
  890. const char* type_param,
  891. Test::SetUpTestCaseFunc set_up_tc,
  892. Test::TearDownTestCaseFunc tear_down_tc);
  893. // Adds a TestInfo to the unit test.
  894. //
  895. // Arguments:
  896. //
  897. // set_up_tc: pointer to the function that sets up the test case
  898. // tear_down_tc: pointer to the function that tears down the test case
  899. // test_info: the TestInfo object
  900. void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
  901. Test::TearDownTestCaseFunc tear_down_tc,
  902. TestInfo* test_info) {
  903. // In order to support thread-safe death tests, we need to
  904. // remember the original working directory when the test program
  905. // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
  906. // the user may have changed the current directory before calling
  907. // RUN_ALL_TESTS(). Therefore we capture the current directory in
  908. // AddTestInfo(), which is called to register a TEST or TEST_F
  909. // before main() is reached.
  910. if (original_working_dir_.IsEmpty()) {
  911. original_working_dir_.Set(FilePath::GetCurrentDir());
  912. GTEST_CHECK_(!original_working_dir_.IsEmpty())
  913. << "Failed to get the current working directory.";
  914. }
  915. GetTestCase(test_info->test_case_name(),
  916. test_info->type_param(),
  917. set_up_tc,
  918. tear_down_tc)->AddTestInfo(test_info);
  919. }
  920. #if GTEST_HAS_PARAM_TEST
  921. // Returns ParameterizedTestCaseRegistry object used to keep track of
  922. // value-parameterized tests and instantiate and register them.
  923. internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
  924. return parameterized_test_registry_;
  925. }
  926. #endif // GTEST_HAS_PARAM_TEST
  927. // Sets the TestCase object for the test that's currently running.
  928. void set_current_test_case(TestCase* a_current_test_case) {
  929. current_test_case_ = a_current_test_case;
  930. }
  931. // Sets the TestInfo object for the test that's currently running. If
  932. // current_test_info is NULL, the assertion results will be stored in
  933. // ad_hoc_test_result_.
  934. void set_current_test_info(TestInfo* a_current_test_info) {
  935. current_test_info_ = a_current_test_info;
  936. }
  937. // Registers all parameterized tests defined using TEST_P and
  938. // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
  939. // combination. This method can be called more then once; it has guards
  940. // protecting from registering the tests more then once. If
  941. // value-parameterized tests are disabled, RegisterParameterizedTests is
  942. // present but does nothing.
  943. void RegisterParameterizedTests();
  944. // Runs all tests in this UnitTest object, prints the result, and
  945. // returns true if all tests are successful. If any exception is
  946. // thrown during a test, this test is considered to be failed, but
  947. // the rest of the tests will still be run.
  948. bool RunAllTests();
  949. // Clears the results of all tests, except the ad hoc tests.
  950. void ClearNonAdHocTestResult() {
  951. ForEach(test_cases_, TestCase::ClearTestCaseResult);
  952. }
  953. // Clears the results of ad-hoc test assertions.
  954. void ClearAdHocTestResult() {
  955. ad_hoc_test_result_.Clear();
  956. }
  957. enum ReactionToSharding {
  958. HONOR_SHARDING_PROTOCOL,
  959. IGNORE_SHARDING_PROTOCOL
  960. };
  961. // Matches the full name of each test against the user-specified
  962. // filter to decide whether the test should run, then records the
  963. // result in each TestCase and TestInfo object.
  964. // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
  965. // based on sharding variables in the environment.
  966. // Returns the number of tests that should run.
  967. int FilterTests(ReactionToSharding shard_tests);
  968. // Prints the names of the tests matching the user-specified filter flag.
  969. void ListTestsMatchingFilter();
  970. const TestCase* current_test_case() const { return current_test_case_; }
  971. TestInfo* current_test_info() { return current_test_info_; }
  972. const TestInfo* current_test_info() const { return current_test_info_; }
  973. // Returns the vector of environments that need to be set-up/torn-down
  974. // before/after the tests are run.
  975. std::vector<Environment*>& environments() { return environments_; }
  976. // Getters for the per-thread Google Test trace stack.
  977. std::vector<TraceInfo>& gtest_trace_stack() {
  978. return *(gtest_trace_stack_.pointer());
  979. }
  980. const std::vector<TraceInfo>& gtest_trace_stack() const {
  981. return gtest_trace_stack_.get();
  982. }
  983. #if GTEST_HAS_DEATH_TEST
  984. void InitDeathTestSubprocessControlInfo() {
  985. internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
  986. }
  987. // Returns a pointer to the parsed --gtest_internal_run_death_test
  988. // flag, or NULL if that flag was not specified.
  989. // This information is useful only in a death test child process.
  990. // Must not be called before a call to InitGoogleTest.
  991. const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
  992. return internal_run_death_test_flag_.get();
  993. }
  994. // Returns a pointer to the current death test factory.
  995. internal::DeathTestFactory* death_test_factory() {
  996. return death_test_factory_.get();
  997. }
  998. void SuppressTestEventsIfInSubprocess();
  999. friend class ReplaceDeathTestFactory;
  1000. #endif // GTEST_HAS_DEATH_TEST
  1001. // Initializes the event listener performing XML output as specified by
  1002. // UnitTestOptions. Must not be called before InitGoogleTest.
  1003. void ConfigureXmlOutput();
  1004. #if GTEST_CAN_STREAM_RESULTS_
  1005. // Initializes the event listener for streaming test results to a socket.
  1006. // Must not be called before InitGoogleTest.
  1007. void ConfigureStreamingOutput();
  1008. #endif
  1009. // Performs initialization dependent upon flag values obtained in
  1010. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  1011. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  1012. // this function is also called from RunAllTests. Since this function can be
  1013. // called more than once, it has to be idempotent.
  1014. void PostFlagParsingInit();
  1015. // Gets the random seed used at the start of the current test iteration.
  1016. int random_seed() const { return random_seed_; }
  1017. // Gets the random number generator.
  1018. internal::Random* random() { return &random_; }
  1019. // Shuffles all test cases, and the tests within each test case,
  1020. // making sure that death tests are still run first.
  1021. void ShuffleTests();
  1022. // Restores the test cases and tests to their order before the first shuffle.
  1023. void UnshuffleTests();
  1024. // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
  1025. // UnitTest::Run() starts.
  1026. bool catch_exceptions() const { return catch_exceptions_; }
  1027. private:
  1028. friend class ::testing::UnitTest;
  1029. // Used by UnitTest::Run() to capture the state of
  1030. // GTEST_FLAG(catch_exceptions) at the moment it starts.
  1031. void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
  1032. // The UnitTest object that owns this implementation object.
  1033. UnitTest* const parent_;
  1034. // The working directory when the first TEST() or TEST_F() was
  1035. // executed.
  1036. internal::FilePath original_working_dir_;
  1037. // The default test part result reporters.
  1038. DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
  1039. DefaultPerThreadTestPartResultReporter
  1040. default_per_thread_test_part_result_reporter_;
  1041. // Points to (but doesn't own) the global test part result reporter.
  1042. TestPartResultReporterInterface* global_test_part_result_repoter_;
  1043. // Protects read and write access to global_test_part_result_reporter_.
  1044. internal::Mutex global_test_part_result_reporter_mutex_;
  1045. // Points to (but doesn't own) the per-thread test part result reporter.
  1046. internal::ThreadLocal<TestPartResultReporterInterface*>
  1047. per_thread_test_part_result_reporter_;
  1048. // The vector of environments that need to be set-up/torn-down
  1049. // before/after the tests are run.
  1050. std::vector<Environment*> environments_;
  1051. // The vector of TestCases in their original order. It owns the
  1052. // elements in the vector.
  1053. std::vector<TestCase*> test_cases_;
  1054. // Provides a level of indirection for the test case list to allow
  1055. // easy shuffling and restoring the test case order. The i-th
  1056. // element of this vector is the index of the i-th test case in the
  1057. // shuffled order.
  1058. std::vector<int> test_case_indices_;
  1059. #if GTEST_HAS_PARAM_TEST
  1060. // ParameterizedTestRegistry object used to register value-parameterized
  1061. // tests.
  1062. internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
  1063. // Indicates whether RegisterParameterizedTests() has been called already.
  1064. bool parameterized_tests_registered_;
  1065. #endif // GTEST_HAS_PARAM_TEST
  1066. // Index of the last death test case registered. Initially -1.
  1067. int last_death_test_case_;
  1068. // This points to the TestCase for the currently running test. It
  1069. // changes as Google Test goes through one test case after another.
  1070. // When no test is running, this is set to NULL and Google Test
  1071. // stores assertion results in ad_hoc_test_result_. Initially NULL.
  1072. TestCase* current_test_case_;
  1073. // This points to the TestInfo for the currently running test. It
  1074. // changes as Google Test goes through one test after another. When
  1075. // no test is running, this is set to NULL and Google Test stores
  1076. // assertion results in ad_hoc_test_result_. Initially NULL.
  1077. TestInfo* current_test_info_;
  1078. // Normally, a user only writes assertions inside a TEST or TEST_F,
  1079. // or inside a function called by a TEST or TEST_F. Since Google
  1080. // Test keeps track of which test is current running, it can
  1081. // associate such an assertion with the test it belongs to.
  1082. //
  1083. // If an assertion is encountered when no TEST or TEST_F is running,
  1084. // Google Test attributes the assertion result to an imaginary "ad hoc"
  1085. // test, and records the result in ad_hoc_test_result_.
  1086. TestResult ad_hoc_test_result_;
  1087. // The list of event listeners that can be used to track events inside
  1088. // Google Test.
  1089. TestEventListeners listeners_;
  1090. // The OS stack trace getter. Will be deleted when the UnitTest
  1091. // object is destructed. By default, an OsStackTraceGetter is used,
  1092. // but the user can set this field to use a custom getter if that is
  1093. // desired.
  1094. OsStackTraceGetterInterface* os_stack_trace_getter_;
  1095. // True iff PostFlagParsingInit() has been called.
  1096. bool post_flag_parse_init_performed_;
  1097. // The random number seed used at the beginning of the test run.
  1098. int random_seed_;
  1099. // Our random number generator.
  1100. internal::Random random_;
  1101. // How long the test took to run, in milliseconds.
  1102. TimeInMillis elapsed_time_;
  1103. #if GTEST_HAS_DEATH_TEST
  1104. // The decomposed components of the gtest_internal_run_death_test flag,
  1105. // parsed when RUN_ALL_TESTS is called.
  1106. internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
  1107. internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
  1108. #endif // GTEST_HAS_DEATH_TEST
  1109. // A per-thread stack of traces created by the SCOPED_TRACE() macro.
  1110. internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
  1111. // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
  1112. // starts.
  1113. bool catch_exceptions_;
  1114. GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
  1115. }; // class UnitTestImpl
  1116. // Convenience function for accessing the global UnitTest
  1117. // implementation object.
  1118. inline UnitTestImpl* GetUnitTestImpl() {
  1119. return UnitTest::GetInstance()->impl();
  1120. }
  1121. #if GTEST_USES_SIMPLE_RE
  1122. // Internal helper functions for implementing the simple regular
  1123. // expression matcher.
  1124. GTEST_API_ bool IsInSet(char ch, const char* str);
  1125. GTEST_API_ bool IsAsciiDigit(char ch);
  1126. GTEST_API_ bool IsAsciiPunct(char ch);
  1127. GTEST_API_ bool IsRepeat(char ch);
  1128. GTEST_API_ bool IsAsciiWhiteSpace(char ch);
  1129. GTEST_API_ bool IsAsciiWordChar(char ch);
  1130. GTEST_API_ bool IsValidEscape(char ch);
  1131. GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
  1132. GTEST_API_ bool ValidateRegex(const char* regex);
  1133. GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
  1134. GTEST_API_ bool MatchRepetitionAndRegexAtHead(
  1135. bool escaped, char ch, char repeat, const char* regex, const char* str);
  1136. GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
  1137. #endif // GTEST_USES_SIMPLE_RE
  1138. // Parses the command line for Google Test flags, without initializing
  1139. // other parts of Google Test.
  1140. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
  1141. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
  1142. #if GTEST_HAS_DEATH_TEST
  1143. // Returns the message describing the last system error, regardless of the
  1144. // platform.
  1145. GTEST_API_ String GetLastErrnoDescription();
  1146. # if GTEST_OS_WINDOWS
  1147. // Provides leak-safe Windows kernel handle ownership.
  1148. class AutoHandle {
  1149. public:
  1150. AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
  1151. explicit AutoHandle(HANDLE handle) : handle_(handle) {}
  1152. ~AutoHandle() { Reset(); }
  1153. HANDLE Get() const { return handle_; }
  1154. void Reset() { Reset(INVALID_HANDLE_VALUE); }
  1155. void Reset(HANDLE handle) {
  1156. if (handle != handle_) {
  1157. if (handle_ != INVALID_HANDLE_VALUE)
  1158. ::CloseHandle(handle_);
  1159. handle_ = handle;
  1160. }
  1161. }
  1162. private:
  1163. HANDLE handle_;
  1164. GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
  1165. };
  1166. # endif // GTEST_OS_WINDOWS
  1167. // Attempts to parse a string into a positive integer pointed to by the
  1168. // number parameter. Returns true if that is possible.
  1169. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
  1170. // it here.
  1171. template <typename Integer>
  1172. bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
  1173. // Fail fast if the given string does not begin with a digit;
  1174. // this bypasses strtoXXX's "optional leading whitespace and plus
  1175. // or minus sign" semantics, which are undesirable here.
  1176. if (str.empty() || !IsDigit(str[0])) {
  1177. return false;
  1178. }
  1179. errno = 0;
  1180. char* end;
  1181. // BiggestConvertible is the largest integer type that system-provided
  1182. // string-to-number conversion routines can return.
  1183. # if GTEST_OS_WINDOWS && !defined(__GNUC__)
  1184. // MSVC and C++ Builder define __int64 instead of the standard long long.
  1185. typedef unsigned __int64 BiggestConvertible;
  1186. const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
  1187. # else
  1188. typedef unsigned long long BiggestConvertible; // NOLINT
  1189. const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
  1190. # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
  1191. const bool parse_success = *end == '\0' && errno == 0;
  1192. // TODO([email protected]): Convert this to compile time assertion when it is
  1193. // available.
  1194. GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
  1195. const Integer result = static_cast<Integer>(parsed);
  1196. if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
  1197. *number = result;
  1198. return true;
  1199. }
  1200. return false;
  1201. }
  1202. #endif // GTEST_HAS_DEATH_TEST
  1203. // TestResult contains some private methods that should be hidden from
  1204. // Google Test user but are required for testing. This class allow our tests
  1205. // to access them.
  1206. //
  1207. // This class is supplied only for the purpose of testing Google Test's own
  1208. // constructs. Do not use it in user tests, either directly or indirectly.
  1209. class TestResultAccessor {
  1210. public:
  1211. static void RecordProperty(TestResult* test_result,
  1212. const TestProperty& property) {
  1213. test_result->RecordProperty(property);
  1214. }
  1215. static void ClearTestPartResults(TestResult* test_result) {
  1216. test_result->ClearTestPartResults();
  1217. }
  1218. static const std::vector<testing::TestPartResult>& test_part_results(
  1219. const TestResult& test_result) {
  1220. return test_result.test_part_results();
  1221. }
  1222. };
  1223. } // namespace internal
  1224. } // namespace testing
  1225. #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
  1226. #undef GTEST_IMPLEMENTATION_
  1227. #if GTEST_OS_WINDOWS
  1228. # define vsnprintf _vsnprintf
  1229. #endif // GTEST_OS_WINDOWS
  1230. namespace testing {
  1231. using internal::CountIf;
  1232. using internal::ForEach;
  1233. using internal::GetElementOr;
  1234. using internal::Shuffle;
  1235. // Constants.
  1236. // A test whose test case name or test name matches this filter is
  1237. // disabled and not run.
  1238. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
  1239. // A test case whose name matches this filter is considered a death
  1240. // test case and will be run before test cases whose name doesn't
  1241. // match this filter.
  1242. static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
  1243. // A test filter that matches everything.
  1244. static const char kUniversalFilter[] = "*";
  1245. // The default output file for XML output.
  1246. static const char kDefaultOutputFile[] = "test_detail.xml";
  1247. // The environment variable name for the test shard index.
  1248. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
  1249. // The environment variable name for the total number of test shards.
  1250. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
  1251. // The environment variable name for the test shard status file.
  1252. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
  1253. namespace internal {
  1254. // The text used in failure messages to indicate the start of the
  1255. // stack trace.
  1256. const char kStackTraceMarker[] = "\nStack trace:\n";
  1257. // g_help_flag is true iff the --help flag or an equivalent form is
  1258. // specified on the command line.
  1259. bool g_help_flag = false;
  1260. } // namespace internal
  1261. GTEST_DEFINE_bool_(
  1262. also_run_disabled_tests,
  1263. internal::BoolFromGTestEnv("also_run_disabled_tests", false),
  1264. "Run disabled tests too, in addition to the tests normally being run.");
  1265. GTEST_DEFINE_bool_(
  1266. break_on_failure,
  1267. internal::BoolFromGTestEnv("break_on_failure", false),
  1268. "True iff a failed assertion should be a debugger break-point.");
  1269. GTEST_DEFINE_bool_(
  1270. catch_exceptions,
  1271. internal::BoolFromGTestEnv("catch_exceptions", true),
  1272. "True iff " GTEST_NAME_
  1273. " should catch exceptions and treat them as test failures.");
  1274. GTEST_DEFINE_string_(
  1275. color,
  1276. internal::StringFromGTestEnv("color", "auto"),
  1277. "Whether to use colors in the output. Valid values: yes, no, "
  1278. "and auto. 'auto' means to use colors if the output is "
  1279. "being sent to a terminal and the TERM environment variable "
  1280. "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
  1281. GTEST_DEFINE_string_(
  1282. filter,
  1283. internal::StringFromGTestEnv("filter", kUniversalFilter),
  1284. "A colon-separated list of glob (not regex) patterns "
  1285. "for filtering the tests to run, optionally followed by a "
  1286. "'-' and a : separated list of negative patterns (tests to "
  1287. "exclude). A test is run if it matches one of the positive "
  1288. "patterns and does not match any of the negative patterns.");
  1289. GTEST_DEFINE_bool_(list_tests, false,
  1290. "List all tests without running them.");
  1291. GTEST_DEFINE_string_(
  1292. output,
  1293. internal::StringFromGTestEnv("output", ""),
  1294. "A format (currently must be \"xml\"), optionally followed "
  1295. "by a colon and an output file name or directory. A directory "
  1296. "is indicated by a trailing pathname separator. "
  1297. "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
  1298. "If a directory is specified, output files will be created "
  1299. "within that directory, with file-names based on the test "
  1300. "executable's name and, if necessary, made unique by adding "
  1301. "digits.");
  1302. GTEST_DEFINE_bool_(
  1303. print_time,
  1304. internal::BoolFromGTestEnv("print_time", true),
  1305. "True iff " GTEST_NAME_
  1306. " should display elapsed time in text output.");
  1307. GTEST_DEFINE_int32_(
  1308. random_seed,
  1309. internal::Int32FromGTestEnv("random_seed", 0),
  1310. "Random number seed to use when shuffling test orders. Must be in range "
  1311. "[1, 99999], or 0 to use a seed based on the current time.");
  1312. GTEST_DEFINE_int32_(
  1313. repeat,
  1314. internal::Int32FromGTestEnv("repeat", 1),
  1315. "How many times to repeat each test. Specify a negative number "
  1316. "for repeating forever. Useful for shaking out flaky tests.");
  1317. GTEST_DEFINE_bool_(
  1318. show_internal_stack_frames, false,
  1319. "True iff " GTEST_NAME_ " should include internal stack frames when "
  1320. "printing test failure stack traces.");
  1321. GTEST_DEFINE_bool_(
  1322. shuffle,
  1323. internal::BoolFromGTestEnv("shuffle", false),
  1324. "True iff " GTEST_NAME_
  1325. " should randomize tests' order on every run.");
  1326. GTEST_DEFINE_int32_(
  1327. stack_trace_depth,
  1328. internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
  1329. "The maximum number of stack frames to print when an "
  1330. "assertion fails. The valid range is 0 through 100, inclusive.");
  1331. GTEST_DEFINE_string_(
  1332. stream_result_to,
  1333. internal::StringFromGTestEnv("stream_result_to", ""),
  1334. "This flag specifies the host name and the port number on which to stream "
  1335. "test results. Example: \"localhost:555\". The flag is effective only on "
  1336. "Linux.");
  1337. GTEST_DEFINE_bool_(
  1338. throw_on_failure,
  1339. internal::BoolFromGTestEnv("throw_on_failure", false),
  1340. "When this flag is specified, a failed assertion will throw an exception "
  1341. "if exceptions are enabled or exit the program with a non-zero code "
  1342. "otherwise.");
  1343. namespace internal {
  1344. // Generates a random number from [0, range), using a Linear
  1345. // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
  1346. // than kMaxRange.
  1347. UInt32 Random::Generate(UInt32 range) {
  1348. // These constants are the same as are used in glibc's rand(3).
  1349. state_ = (1103515245U*state_ + 12345U) % kMaxRange;
  1350. GTEST_CHECK_(range > 0)
  1351. << "Cannot generate a number in the range [0, 0).";
  1352. GTEST_CHECK_(range <= kMaxRange)
  1353. << "Generation of a number in [0, " << range << ") was requested, "
  1354. << "but this can only generate numbers in [0, " << kMaxRange << ").";
  1355. // Converting via modulus introduces a bit of downward bias, but
  1356. // it's simple, and a linear congruential generator isn't too good
  1357. // to begin with.
  1358. return state_ % range;
  1359. }
  1360. // GTestIsInitialized() returns true iff the user has initialized
  1361. // Google Test. Useful for catching the user mistake of not initializing
  1362. // Google Test before calling RUN_ALL_TESTS().
  1363. //
  1364. // A user must call testing::InitGoogleTest() to initialize Google
  1365. // Test. g_init_gtest_count is set to the number of times
  1366. // InitGoogleTest() has been called. We don't protect this variable
  1367. // under a mutex as it is only accessed in the main thread.
  1368. int g_init_gtest_count = 0;
  1369. static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
  1370. // Iterates over a vector of TestCases, keeping a running sum of the
  1371. // results of calling a given int-returning method on each.
  1372. // Returns the sum.
  1373. static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
  1374. int (TestCase::*method)() const) {
  1375. int sum = 0;
  1376. for (size_t i = 0; i < case_list.size(); i++) {
  1377. sum += (case_list[i]->*method)();
  1378. }
  1379. return sum;
  1380. }
  1381. // Returns true iff the test case passed.
  1382. static bool TestCasePassed(const TestCase* test_case) {
  1383. return test_case->should_run() && test_case->Passed();
  1384. }
  1385. // Returns true iff the test case failed.
  1386. static bool TestCaseFailed(const TestCase* test_case) {
  1387. return test_case->should_run() && test_case->Failed();
  1388. }
  1389. // Returns true iff test_case contains at least one test that should
  1390. // run.
  1391. static bool ShouldRunTestCase(const TestCase* test_case) {
  1392. return test_case->should_run();
  1393. }
  1394. // AssertHelper constructor.
  1395. AssertHelper::AssertHelper(TestPartResult::Type type,
  1396. const char* file,
  1397. int line,
  1398. const char* message)
  1399. : data_(new AssertHelperData(type, file, line, message)) {
  1400. }
  1401. AssertHelper::~AssertHelper() {
  1402. delete data_;
  1403. }
  1404. // Message assignment, for assertion streaming support.
  1405. void AssertHelper::operator=(const Message& message) const {
  1406. UnitTest::GetInstance()->
  1407. AddTestPartResult(data_->type, data_->file, data_->line,
  1408. AppendUserMessage(data_->message, message),
  1409. UnitTest::GetInstance()->impl()
  1410. ->CurrentOsStackTraceExceptTop(1)
  1411. // Skips the stack frame for this function itself.
  1412. ); // NOLINT
  1413. }
  1414. // Mutex for linked pointers.
  1415. GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
  1416. // Application pathname gotten in InitGoogleTest.
  1417. String g_executable_path;
  1418. // Returns the current application's name, removing directory path if that
  1419. // is present.
  1420. FilePath GetCurrentExecutableName() {
  1421. FilePath result;
  1422. #if GTEST_OS_WINDOWS
  1423. result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
  1424. #else
  1425. result.Set(FilePath(g_executable_path));
  1426. #endif // GTEST_OS_WINDOWS
  1427. return result.RemoveDirectoryName();
  1428. }
  1429. // Functions for processing the gtest_output flag.
  1430. // Returns the output format, or "" for normal printed output.
  1431. String UnitTestOptions::GetOutputFormat() {
  1432. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1433. if (gtest_output_flag == NULL) return String("");
  1434. const char* const colon = strchr(gtest_output_flag, ':');
  1435. return (colon == NULL) ?
  1436. String(gtest_output_flag) :
  1437. String(gtest_output_flag, colon - gtest_output_flag);
  1438. }
  1439. // Returns the name of the requested output file, or the default if none
  1440. // was explicitly specified.
  1441. String UnitTestOptions::GetAbsolutePathToOutputFile() {
  1442. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1443. if (gtest_output_flag == NULL)
  1444. return String("");
  1445. const char* const colon = strchr(gtest_output_flag, ':');
  1446. if (colon == NULL)
  1447. return String(internal::FilePath::ConcatPaths(
  1448. internal::FilePath(
  1449. UnitTest::GetInstance()->original_working_dir()),
  1450. internal::FilePath(kDefaultOutputFile)).ToString() );
  1451. internal::FilePath output_name(colon + 1);
  1452. if (!output_name.IsAbsolutePath())
  1453. // TODO([email protected]): on Windows \some\path is not an absolute
  1454. // path (as its meaning depends on the current drive), yet the
  1455. // following logic for turning it into an absolute path is wrong.
  1456. // Fix it.
  1457. output_name = internal::FilePath::ConcatPaths(
  1458. internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
  1459. internal::FilePath(colon + 1));
  1460. if (!output_name.IsDirectory())
  1461. return output_name.ToString();
  1462. internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
  1463. output_name, internal::GetCurrentExecutableName(),
  1464. GetOutputFormat().c_str()));
  1465. return result.ToString();
  1466. }
  1467. // Returns true iff the wildcard pattern matches the string. The
  1468. // first ':' or '\0' character in pattern marks the end of it.
  1469. //
  1470. // This recursive algorithm isn't very efficient, but is clear and
  1471. // works well enough for matching test names, which are short.
  1472. bool UnitTestOptions::PatternMatchesString(const char *pattern,
  1473. const char *str) {
  1474. switch (*pattern) {
  1475. case '\0':
  1476. case ':': // Either ':' or '\0' marks the end of the pattern.
  1477. return *str == '\0';
  1478. case '?': // Matches any single character.
  1479. return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
  1480. case '*': // Matches any string (possibly empty) of characters.
  1481. return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
  1482. PatternMatchesString(pattern + 1, str);
  1483. default: // Non-special character. Matches itself.
  1484. return *pattern == *str &&
  1485. PatternMatchesString(pattern + 1, str + 1);
  1486. }
  1487. }
  1488. bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
  1489. const char *cur_pattern = filter;
  1490. for (;;) {
  1491. if (PatternMatchesString(cur_pattern, name.c_str())) {
  1492. return true;
  1493. }
  1494. // Finds the next pattern in the filter.
  1495. cur_pattern = strchr(cur_pattern, ':');
  1496. // Returns if no more pattern can be found.
  1497. if (cur_pattern == NULL) {
  1498. return false;
  1499. }
  1500. // Skips the pattern separater (the ':' character).
  1501. cur_pattern++;
  1502. }
  1503. }
  1504. // TODO(keithray): move String function implementations to gtest-string.cc.
  1505. // Returns true iff the user-specified filter matches the test case
  1506. // name and the test name.
  1507. bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
  1508. const String &test_name) {
  1509. const String& full_name = String::Format("%s.%s",
  1510. test_case_name.c_str(),
  1511. test_name.c_str());
  1512. // Split --gtest_filter at '-', if there is one, to separate into
  1513. // positive filter and negative filter portions
  1514. const char* const p = GTEST_FLAG(filter).c_str();
  1515. const char* const dash = strchr(p, '-');
  1516. String positive;
  1517. String negative;
  1518. if (dash == NULL) {
  1519. positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
  1520. negative = String("");
  1521. } else {
  1522. positive = String(p, dash - p); // Everything up to the dash
  1523. negative = String(dash+1); // Everything after the dash
  1524. if (positive.empty()) {
  1525. // Treat '-test1' as the same as '*-test1'
  1526. positive = kUniversalFilter;
  1527. }
  1528. }
  1529. // A filter is a colon-separated list of patterns. It matches a
  1530. // test if any pattern in it matches the test.
  1531. return (MatchesFilter(full_name, positive.c_str()) &&
  1532. !MatchesFilter(full_name, negative.c_str()));
  1533. }
  1534. #if GTEST_HAS_SEH
  1535. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  1536. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  1537. // This function is useful as an __except condition.
  1538. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
  1539. // Google Test should handle a SEH exception if:
  1540. // 1. the user wants it to, AND
  1541. // 2. this is not a breakpoint exception, AND
  1542. // 3. this is not a C++ exception (VC++ implements them via SEH,
  1543. // apparently).
  1544. //
  1545. // SEH exception code for C++ exceptions.
  1546. // (see http://support.microsoft.com/kb/185294 for more information).
  1547. const DWORD kCxxExceptionCode = 0xe06d7363;
  1548. bool should_handle = true;
  1549. if (!GTEST_FLAG(catch_exceptions))
  1550. should_handle = false;
  1551. else if (exception_code == EXCEPTION_BREAKPOINT)
  1552. should_handle = false;
  1553. else if (exception_code == kCxxExceptionCode)
  1554. should_handle = false;
  1555. return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
  1556. }
  1557. #endif // GTEST_HAS_SEH
  1558. } // namespace internal
  1559. // The c'tor sets this object as the test part result reporter used by
  1560. // Google Test. The 'result' parameter specifies where to report the
  1561. // results. Intercepts only failures from the current thread.
  1562. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1563. TestPartResultArray* result)
  1564. : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
  1565. result_(result) {
  1566. Init();
  1567. }
  1568. // The c'tor sets this object as the test part result reporter used by
  1569. // Google Test. The 'result' parameter specifies where to report the
  1570. // results.
  1571. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1572. InterceptMode intercept_mode, TestPartResultArray* result)
  1573. : intercept_mode_(intercept_mode),
  1574. result_(result) {
  1575. Init();
  1576. }
  1577. void ScopedFakeTestPartResultReporter::Init() {
  1578. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1579. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1580. old_reporter_ = impl->GetGlobalTestPartResultReporter();
  1581. impl->SetGlobalTestPartResultReporter(this);
  1582. } else {
  1583. old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
  1584. impl->SetTestPartResultReporterForCurrentThread(this);
  1585. }
  1586. }
  1587. // The d'tor restores the test part result reporter used by Google Test
  1588. // before.
  1589. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
  1590. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1591. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1592. impl->SetGlobalTestPartResultReporter(old_reporter_);
  1593. } else {
  1594. impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
  1595. }
  1596. }
  1597. // Increments the test part result count and remembers the result.
  1598. // This method is from the TestPartResultReporterInterface interface.
  1599. void ScopedFakeTestPartResultReporter::ReportTestPartResult(
  1600. const TestPartResult& result) {
  1601. result_->Append(result);
  1602. }
  1603. namespace internal {
  1604. // Returns the type ID of ::testing::Test. We should always call this
  1605. // instead of GetTypeId< ::testing::Test>() to get the type ID of
  1606. // testing::Test. This is to work around a suspected linker bug when
  1607. // using Google Test as a framework on Mac OS X. The bug causes
  1608. // GetTypeId< ::testing::Test>() to return different values depending
  1609. // on whether the call is from the Google Test framework itself or
  1610. // from user test code. GetTestTypeId() is guaranteed to always
  1611. // return the same value, as it always calls GetTypeId<>() from the
  1612. // gtest.cc, which is within the Google Test framework.
  1613. TypeId GetTestTypeId() {
  1614. return GetTypeId<Test>();
  1615. }
  1616. // The value of GetTestTypeId() as seen from within the Google Test
  1617. // library. This is solely for testing GetTestTypeId().
  1618. extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
  1619. // This predicate-formatter checks that 'results' contains a test part
  1620. // failure of the given type and that the failure message contains the
  1621. // given substring.
  1622. AssertionResult HasOneFailure(const char* /* results_expr */,
  1623. const char* /* type_expr */,
  1624. const char* /* substr_expr */,
  1625. const TestPartResultArray& results,
  1626. TestPartResult::Type type,
  1627. const string& substr) {
  1628. const String expected(type == TestPartResult::kFatalFailure ?
  1629. "1 fatal failure" :
  1630. "1 non-fatal failure");
  1631. Message msg;
  1632. if (results.size() != 1) {
  1633. msg << "Expected: " << expected << "\n"
  1634. << " Actual: " << results.size() << " failures";
  1635. for (int i = 0; i < results.size(); i++) {
  1636. msg << "\n" << results.GetTestPartResult(i);
  1637. }
  1638. return AssertionFailure() << msg;
  1639. }
  1640. const TestPartResult& r = results.GetTestPartResult(0);
  1641. if (r.type() != type) {
  1642. return AssertionFailure() << "Expected: " << expected << "\n"
  1643. << " Actual:\n"
  1644. << r;
  1645. }
  1646. if (strstr(r.message(), substr.c_str()) == NULL) {
  1647. return AssertionFailure() << "Expected: " << expected << " containing \""
  1648. << substr << "\"\n"
  1649. << " Actual:\n"
  1650. << r;
  1651. }
  1652. return AssertionSuccess();
  1653. }
  1654. // The constructor of SingleFailureChecker remembers where to look up
  1655. // test part results, what type of failure we expect, and what
  1656. // substring the failure message should contain.
  1657. SingleFailureChecker:: SingleFailureChecker(
  1658. const TestPartResultArray* results,
  1659. TestPartResult::Type type,
  1660. const string& substr)
  1661. : results_(results),
  1662. type_(type),
  1663. substr_(substr) {}
  1664. // The destructor of SingleFailureChecker verifies that the given
  1665. // TestPartResultArray contains exactly one failure that has the given
  1666. // type and contains the given substring. If that's not the case, a
  1667. // non-fatal failure will be generated.
  1668. SingleFailureChecker::~SingleFailureChecker() {
  1669. EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
  1670. }
  1671. DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
  1672. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  1673. void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
  1674. const TestPartResult& result) {
  1675. unit_test_->current_test_result()->AddTestPartResult(result);
  1676. unit_test_->listeners()->repeater()->OnTestPartResult(result);
  1677. }
  1678. DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
  1679. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  1680. void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
  1681. const TestPartResult& result) {
  1682. unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
  1683. }
  1684. // Returns the global test part result reporter.
  1685. TestPartResultReporterInterface*
  1686. UnitTestImpl::GetGlobalTestPartResultReporter() {
  1687. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  1688. return global_test_part_result_repoter_;
  1689. }
  1690. // Sets the global test part result reporter.
  1691. void UnitTestImpl::SetGlobalTestPartResultReporter(
  1692. TestPartResultReporterInterface* reporter) {
  1693. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  1694. global_test_part_result_repoter_ = reporter;
  1695. }
  1696. // Returns the test part result reporter for the current thread.
  1697. TestPartResultReporterInterface*
  1698. UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
  1699. return per_thread_test_part_result_reporter_.get();
  1700. }
  1701. // Sets the test part result reporter for the current thread.
  1702. void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
  1703. TestPartResultReporterInterface* reporter) {
  1704. per_thread_test_part_result_reporter_.set(reporter);
  1705. }
  1706. // Gets the number of successful test cases.
  1707. int UnitTestImpl::successful_test_case_count() const {
  1708. return CountIf(test_cases_, TestCasePassed);
  1709. }
  1710. // Gets the number of failed test cases.
  1711. int UnitTestImpl::failed_test_case_count() const {
  1712. return CountIf(test_cases_, TestCaseFailed);
  1713. }
  1714. // Gets the number of all test cases.
  1715. int UnitTestImpl::total_test_case_count() const {
  1716. return static_cast<int>(test_cases_.size());
  1717. }
  1718. // Gets the number of all test cases that contain at least one test
  1719. // that should run.
  1720. int UnitTestImpl::test_case_to_run_count() const {
  1721. return CountIf(test_cases_, ShouldRunTestCase);
  1722. }
  1723. // Gets the number of successful tests.
  1724. int UnitTestImpl::successful_test_count() const {
  1725. return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
  1726. }
  1727. // Gets the number of failed tests.
  1728. int UnitTestImpl::failed_test_count() const {
  1729. return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
  1730. }
  1731. // Gets the number of disabled tests.
  1732. int UnitTestImpl::disabled_test_count() const {
  1733. return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
  1734. }
  1735. // Gets the number of all tests.
  1736. int UnitTestImpl::total_test_count() const {
  1737. return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
  1738. }
  1739. // Gets the number of tests that should run.
  1740. int UnitTestImpl::test_to_run_count() const {
  1741. return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
  1742. }
  1743. // Returns the current OS stack trace as a String.
  1744. //
  1745. // The maximum number of stack frames to be included is specified by
  1746. // the gtest_stack_trace_depth flag. The skip_count parameter
  1747. // specifies the number of top frames to be skipped, which doesn't
  1748. // count against the number of frames to be included.
  1749. //
  1750. // For example, if Foo() calls Bar(), which in turn calls
  1751. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  1752. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  1753. String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
  1754. (void)skip_count;
  1755. return String("");
  1756. }
  1757. // Returns the current time in milliseconds.
  1758. TimeInMillis GetTimeInMillis() {
  1759. #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
  1760. // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
  1761. // http://analogous.blogspot.com/2005/04/epoch.html
  1762. const TimeInMillis kJavaEpochToWinFileTimeDelta =
  1763. static_cast<TimeInMillis>(116444736UL) * 100000UL;
  1764. const DWORD kTenthMicrosInMilliSecond = 10000;
  1765. SYSTEMTIME now_systime;
  1766. FILETIME now_filetime;
  1767. ULARGE_INTEGER now_int64;
  1768. // TODO([email protected]): Shouldn't this just use
  1769. // GetSystemTimeAsFileTime()?
  1770. GetSystemTime(&now_systime);
  1771. if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
  1772. now_int64.LowPart = now_filetime.dwLowDateTime;
  1773. now_int64.HighPart = now_filetime.dwHighDateTime;
  1774. now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
  1775. kJavaEpochToWinFileTimeDelta;
  1776. return now_int64.QuadPart;
  1777. }
  1778. return 0;
  1779. #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
  1780. __timeb64 now;
  1781. # ifdef _MSC_VER
  1782. // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
  1783. // (deprecated function) there.
  1784. // TODO([email protected]): Use GetTickCount()? Or use
  1785. // SystemTimeToFileTime()
  1786. # pragma warning(push) // Saves the current warning state.
  1787. # pragma warning(disable:4996) // Temporarily disables warning 4996.
  1788. _ftime64(&now);
  1789. # pragma warning(pop) // Restores the warning state.
  1790. # else
  1791. _ftime64(&now);
  1792. # endif // _MSC_VER
  1793. return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
  1794. #elif GTEST_HAS_GETTIMEOFDAY_
  1795. struct timeval now;
  1796. gettimeofday(&now, NULL);
  1797. return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
  1798. #else
  1799. # error "Don't know how to get the current time on your system."
  1800. #endif
  1801. }
  1802. // Utilities
  1803. // class String
  1804. // Returns the input enclosed in double quotes if it's not NULL;
  1805. // otherwise returns "(null)". For example, "\"Hello\"" is returned
  1806. // for input "Hello".
  1807. //
  1808. // This is useful for printing a C string in the syntax of a literal.
  1809. //
  1810. // Known issue: escape sequences are not handled yet.
  1811. String String::ShowCStringQuoted(const char* c_str) {
  1812. return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
  1813. }
  1814. // Copies at most length characters from str into a newly-allocated
  1815. // piece of memory of size length+1. The memory is allocated with new[].
  1816. // A terminating null byte is written to the memory, and a pointer to it
  1817. // is returned. If str is NULL, NULL is returned.
  1818. static char* CloneString(const char* str, size_t length) {
  1819. if (str == NULL) {
  1820. return NULL;
  1821. } else {
  1822. char* const clone = new char[length + 1];
  1823. posix::StrNCpy(clone, str, length);
  1824. clone[length] = '\0';
  1825. return clone;
  1826. }
  1827. }
  1828. // Clones a 0-terminated C string, allocating memory using new. The
  1829. // caller is responsible for deleting[] the return value. Returns the
  1830. // cloned string, or NULL if the input is NULL.
  1831. const char * String::CloneCString(const char* c_str) {
  1832. return (c_str == NULL) ?
  1833. NULL : CloneString(c_str, strlen(c_str));
  1834. }
  1835. #if GTEST_OS_WINDOWS_MOBILE
  1836. // Creates a UTF-16 wide string from the given ANSI string, allocating
  1837. // memory using new. The caller is responsible for deleting the return
  1838. // value using delete[]. Returns the wide string, or NULL if the
  1839. // input is NULL.
  1840. LPCWSTR String::AnsiToUtf16(const char* ansi) {
  1841. if (!ansi) return NULL;
  1842. const int length = strlen(ansi);
  1843. const int unicode_length =
  1844. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  1845. NULL, 0);
  1846. WCHAR* unicode = new WCHAR[unicode_length + 1];
  1847. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  1848. unicode, unicode_length);
  1849. unicode[unicode_length] = 0;
  1850. return unicode;
  1851. }
  1852. // Creates an ANSI string from the given wide string, allocating
  1853. // memory using new. The caller is responsible for deleting the return
  1854. // value using delete[]. Returns the ANSI string, or NULL if the
  1855. // input is NULL.
  1856. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
  1857. if (!utf16_str) return NULL;
  1858. const int ansi_length =
  1859. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  1860. NULL, 0, NULL, NULL);
  1861. char* ansi = new char[ansi_length + 1];
  1862. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  1863. ansi, ansi_length, NULL, NULL);
  1864. ansi[ansi_length] = 0;
  1865. return ansi;
  1866. }
  1867. #endif // GTEST_OS_WINDOWS_MOBILE
  1868. // Compares two C strings. Returns true iff they have the same content.
  1869. //
  1870. // Unlike strcmp(), this function can handle NULL argument(s). A NULL
  1871. // C string is considered different to any non-NULL C string,
  1872. // including the empty string.
  1873. bool String::CStringEquals(const char * lhs, const char * rhs) {
  1874. if ( lhs == NULL ) return rhs == NULL;
  1875. if ( rhs == NULL ) return false;
  1876. return strcmp(lhs, rhs) == 0;
  1877. }
  1878. #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  1879. // Converts an array of wide chars to a narrow string using the UTF-8
  1880. // encoding, and streams the result to the given Message object.
  1881. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
  1882. Message* msg) {
  1883. // TODO(wan): consider allowing a testing::String object to
  1884. // contain '\0'. This will make it behave more like std::string,
  1885. // and will allow ToUtf8String() to return the correct encoding
  1886. // for '\0' s.t. we can get rid of the conditional here (and in
  1887. // several other places).
  1888. for (size_t i = 0; i != length; ) { // NOLINT
  1889. if (wstr[i] != L'\0') {
  1890. *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
  1891. while (i != length && wstr[i] != L'\0')
  1892. i++;
  1893. } else {
  1894. *msg << '\0';
  1895. i++;
  1896. }
  1897. }
  1898. }
  1899. #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  1900. } // namespace internal
  1901. #if GTEST_HAS_STD_WSTRING
  1902. // Converts the given wide string to a narrow string using the UTF-8
  1903. // encoding, and streams the result to this Message object.
  1904. Message& Message::operator <<(const ::std::wstring& wstr) {
  1905. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  1906. return *this;
  1907. }
  1908. #endif // GTEST_HAS_STD_WSTRING
  1909. #if GTEST_HAS_GLOBAL_WSTRING
  1910. // Converts the given wide string to a narrow string using the UTF-8
  1911. // encoding, and streams the result to this Message object.
  1912. Message& Message::operator <<(const ::wstring& wstr) {
  1913. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  1914. return *this;
  1915. }
  1916. #endif // GTEST_HAS_GLOBAL_WSTRING
  1917. // AssertionResult constructors.
  1918. // Used in EXPECT_TRUE/FALSE(assertion_result).
  1919. AssertionResult::AssertionResult(const AssertionResult& other)
  1920. : success_(other.success_),
  1921. message_(other.message_.get() != NULL ?
  1922. new ::std::string(*other.message_) :
  1923. static_cast< ::std::string*>(NULL)) {
  1924. }
  1925. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  1926. AssertionResult AssertionResult::operator!() const {
  1927. AssertionResult negation(!success_);
  1928. if (message_.get() != NULL)
  1929. negation << *message_;
  1930. return negation;
  1931. }
  1932. // Makes a successful assertion result.
  1933. AssertionResult AssertionSuccess() {
  1934. return AssertionResult(true);
  1935. }
  1936. // Makes a failed assertion result.
  1937. AssertionResult AssertionFailure() {
  1938. return AssertionResult(false);
  1939. }
  1940. // Makes a failed assertion result with the given failure message.
  1941. // Deprecated; use AssertionFailure() << message.
  1942. AssertionResult AssertionFailure(const Message& message) {
  1943. return AssertionFailure() << message;
  1944. }
  1945. namespace internal {
  1946. // Constructs and returns the message for an equality assertion
  1947. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  1948. //
  1949. // The first four parameters are the expressions used in the assertion
  1950. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  1951. // where foo is 5 and bar is 6, we have:
  1952. //
  1953. // expected_expression: "foo"
  1954. // actual_expression: "bar"
  1955. // expected_value: "5"
  1956. // actual_value: "6"
  1957. //
  1958. // The ignoring_case parameter is true iff the assertion is a
  1959. // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
  1960. // be inserted into the message.
  1961. AssertionResult EqFailure(const char* expected_expression,
  1962. const char* actual_expression,
  1963. const String& expected_value,
  1964. const String& actual_value,
  1965. bool ignoring_case) {
  1966. Message msg;
  1967. msg << "Value of: " << actual_expression;
  1968. if (actual_value != actual_expression) {
  1969. msg << "\n Actual: " << actual_value;
  1970. }
  1971. msg << "\nExpected: " << expected_expression;
  1972. if (ignoring_case) {
  1973. msg << " (ignoring case)";
  1974. }
  1975. if (expected_value != expected_expression) {
  1976. msg << "\nWhich is: " << expected_value;
  1977. }
  1978. return AssertionFailure() << msg;
  1979. }
  1980. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  1981. String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
  1982. const char* expression_text,
  1983. const char* actual_predicate_value,
  1984. const char* expected_predicate_value) {
  1985. const char* actual_message = assertion_result.message();
  1986. Message msg;
  1987. msg << "Value of: " << expression_text
  1988. << "\n Actual: " << actual_predicate_value;
  1989. if (actual_message[0] != '\0')
  1990. msg << " (" << actual_message << ")";
  1991. msg << "\nExpected: " << expected_predicate_value;
  1992. return msg.GetString();
  1993. }
  1994. // Helper function for implementing ASSERT_NEAR.
  1995. AssertionResult DoubleNearPredFormat(const char* expr1,
  1996. const char* expr2,
  1997. const char* abs_error_expr,
  1998. double val1,
  1999. double val2,
  2000. double abs_error) {
  2001. const double diff = fabs(val1 - val2);
  2002. if (diff <= abs_error) return AssertionSuccess();
  2003. // TODO(wan): do not print the value of an expression if it's
  2004. // already a literal.
  2005. return AssertionFailure()
  2006. << "The difference between " << expr1 << " and " << expr2
  2007. << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
  2008. << expr1 << " evaluates to " << val1 << ",\n"
  2009. << expr2 << " evaluates to " << val2 << ", and\n"
  2010. << abs_error_expr << " evaluates to " << abs_error << ".";
  2011. }
  2012. // Helper template for implementing FloatLE() and DoubleLE().
  2013. template <typename RawType>
  2014. AssertionResult FloatingPointLE(const char* expr1,
  2015. const char* expr2,
  2016. RawType val1,
  2017. RawType val2) {
  2018. // Returns success if val1 is less than val2,
  2019. if (val1 < val2) {
  2020. return AssertionSuccess();
  2021. }
  2022. // or if val1 is almost equal to val2.
  2023. const FloatingPoint<RawType> lhs(val1), rhs(val2);
  2024. if (lhs.AlmostEquals(rhs)) {
  2025. return AssertionSuccess();
  2026. }
  2027. // Note that the above two checks will both fail if either val1 or
  2028. // val2 is NaN, as the IEEE floating-point standard requires that
  2029. // any predicate involving a NaN must return false.
  2030. ::std::stringstream val1_ss;
  2031. val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2032. << val1;
  2033. ::std::stringstream val2_ss;
  2034. val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2035. << val2;
  2036. return AssertionFailure()
  2037. << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
  2038. << " Actual: " << StringStreamToString(&val1_ss) << " vs "
  2039. << StringStreamToString(&val2_ss);
  2040. }
  2041. } // namespace internal
  2042. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2043. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2044. AssertionResult FloatLE(const char* expr1, const char* expr2,
  2045. float val1, float val2) {
  2046. return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
  2047. }
  2048. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2049. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2050. AssertionResult DoubleLE(const char* expr1, const char* expr2,
  2051. double val1, double val2) {
  2052. return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
  2053. }
  2054. namespace internal {
  2055. // The helper function for {ASSERT|EXPECT}_EQ with int or enum
  2056. // arguments.
  2057. AssertionResult CmpHelperEQ(const char* expected_expression,
  2058. const char* actual_expression,
  2059. BiggestInt expected,
  2060. BiggestInt actual) {
  2061. if (expected == actual) {
  2062. return AssertionSuccess();
  2063. }
  2064. return EqFailure(expected_expression,
  2065. actual_expression,
  2066. FormatForComparisonFailureMessage(expected, actual),
  2067. FormatForComparisonFailureMessage(actual, expected),
  2068. false);
  2069. }
  2070. // A macro for implementing the helper functions needed to implement
  2071. // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
  2072. // just to avoid copy-and-paste of similar code.
  2073. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
  2074. AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
  2075. BiggestInt val1, BiggestInt val2) {\
  2076. if (val1 op val2) {\
  2077. return AssertionSuccess();\
  2078. } else {\
  2079. return AssertionFailure() \
  2080. << "Expected: (" << expr1 << ") " #op " (" << expr2\
  2081. << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
  2082. << " vs " << FormatForComparisonFailureMessage(val2, val1);\
  2083. }\
  2084. }
  2085. // Implements the helper function for {ASSERT|EXPECT}_NE with int or
  2086. // enum arguments.
  2087. GTEST_IMPL_CMP_HELPER_(NE, !=)
  2088. // Implements the helper function for {ASSERT|EXPECT}_LE with int or
  2089. // enum arguments.
  2090. GTEST_IMPL_CMP_HELPER_(LE, <=)
  2091. // Implements the helper function for {ASSERT|EXPECT}_LT with int or
  2092. // enum arguments.
  2093. GTEST_IMPL_CMP_HELPER_(LT, < )
  2094. // Implements the helper function for {ASSERT|EXPECT}_GE with int or
  2095. // enum arguments.
  2096. GTEST_IMPL_CMP_HELPER_(GE, >=)
  2097. // Implements the helper function for {ASSERT|EXPECT}_GT with int or
  2098. // enum arguments.
  2099. GTEST_IMPL_CMP_HELPER_(GT, > )
  2100. #undef GTEST_IMPL_CMP_HELPER_
  2101. // The helper function for {ASSERT|EXPECT}_STREQ.
  2102. AssertionResult CmpHelperSTREQ(const char* expected_expression,
  2103. const char* actual_expression,
  2104. const char* expected,
  2105. const char* actual) {
  2106. if (String::CStringEquals(expected, actual)) {
  2107. return AssertionSuccess();
  2108. }
  2109. return EqFailure(expected_expression,
  2110. actual_expression,
  2111. String::ShowCStringQuoted(expected),
  2112. String::ShowCStringQuoted(actual),
  2113. false);
  2114. }
  2115. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  2116. AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
  2117. const char* actual_expression,
  2118. const char* expected,
  2119. const char* actual) {
  2120. if (String::CaseInsensitiveCStringEquals(expected, actual)) {
  2121. return AssertionSuccess();
  2122. }
  2123. return EqFailure(expected_expression,
  2124. actual_expression,
  2125. String::ShowCStringQuoted(expected),
  2126. String::ShowCStringQuoted(actual),
  2127. true);
  2128. }
  2129. // The helper function for {ASSERT|EXPECT}_STRNE.
  2130. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  2131. const char* s2_expression,
  2132. const char* s1,
  2133. const char* s2) {
  2134. if (!String::CStringEquals(s1, s2)) {
  2135. return AssertionSuccess();
  2136. } else {
  2137. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  2138. << s2_expression << "), actual: \""
  2139. << s1 << "\" vs \"" << s2 << "\"";
  2140. }
  2141. }
  2142. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  2143. AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  2144. const char* s2_expression,
  2145. const char* s1,
  2146. const char* s2) {
  2147. if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
  2148. return AssertionSuccess();
  2149. } else {
  2150. return AssertionFailure()
  2151. << "Expected: (" << s1_expression << ") != ("
  2152. << s2_expression << ") (ignoring case), actual: \""
  2153. << s1 << "\" vs \"" << s2 << "\"";
  2154. }
  2155. }
  2156. } // namespace internal
  2157. namespace {
  2158. // Helper functions for implementing IsSubString() and IsNotSubstring().
  2159. // This group of overloaded functions return true iff needle is a
  2160. // substring of haystack. NULL is considered a substring of itself
  2161. // only.
  2162. bool IsSubstringPred(const char* needle, const char* haystack) {
  2163. if (needle == NULL || haystack == NULL)
  2164. return needle == haystack;
  2165. return strstr(haystack, needle) != NULL;
  2166. }
  2167. bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
  2168. if (needle == NULL || haystack == NULL)
  2169. return needle == haystack;
  2170. return wcsstr(haystack, needle) != NULL;
  2171. }
  2172. // StringType here can be either ::std::string or ::std::wstring.
  2173. template <typename StringType>
  2174. bool IsSubstringPred(const StringType& needle,
  2175. const StringType& haystack) {
  2176. return haystack.find(needle) != StringType::npos;
  2177. }
  2178. // This function implements either IsSubstring() or IsNotSubstring(),
  2179. // depending on the value of the expected_to_be_substring parameter.
  2180. // StringType here can be const char*, const wchar_t*, ::std::string,
  2181. // or ::std::wstring.
  2182. template <typename StringType>
  2183. AssertionResult IsSubstringImpl(
  2184. bool expected_to_be_substring,
  2185. const char* needle_expr, const char* haystack_expr,
  2186. const StringType& needle, const StringType& haystack) {
  2187. if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
  2188. return AssertionSuccess();
  2189. const bool is_wide_string = sizeof(needle[0]) > 1;
  2190. const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
  2191. return AssertionFailure()
  2192. << "Value of: " << needle_expr << "\n"
  2193. << " Actual: " << begin_string_quote << needle << "\"\n"
  2194. << "Expected: " << (expected_to_be_substring ? "" : "not ")
  2195. << "a substring of " << haystack_expr << "\n"
  2196. << "Which is: " << begin_string_quote << haystack << "\"";
  2197. }
  2198. } // namespace
  2199. // IsSubstring() and IsNotSubstring() check whether needle is a
  2200. // substring of haystack (NULL is considered a substring of itself
  2201. // only), and return an appropriate error message when they fail.
  2202. AssertionResult IsSubstring(
  2203. const char* needle_expr, const char* haystack_expr,
  2204. const char* needle, const char* haystack) {
  2205. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2206. }
  2207. AssertionResult IsSubstring(
  2208. const char* needle_expr, const char* haystack_expr,
  2209. const wchar_t* needle, const wchar_t* haystack) {
  2210. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2211. }
  2212. AssertionResult IsNotSubstring(
  2213. const char* needle_expr, const char* haystack_expr,
  2214. const char* needle, const char* haystack) {
  2215. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2216. }
  2217. AssertionResult IsNotSubstring(
  2218. const char* needle_expr, const char* haystack_expr,
  2219. const wchar_t* needle, const wchar_t* haystack) {
  2220. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2221. }
  2222. AssertionResult IsSubstring(
  2223. const char* needle_expr, const char* haystack_expr,
  2224. const ::std::string& needle, const ::std::string& haystack) {
  2225. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2226. }
  2227. AssertionResult IsNotSubstring(
  2228. const char* needle_expr, const char* haystack_expr,
  2229. const ::std::string& needle, const ::std::string& haystack) {
  2230. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2231. }
  2232. #if GTEST_HAS_STD_WSTRING
  2233. AssertionResult IsSubstring(
  2234. const char* needle_expr, const char* haystack_expr,
  2235. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2236. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2237. }
  2238. AssertionResult IsNotSubstring(
  2239. const char* needle_expr, const char* haystack_expr,
  2240. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2241. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2242. }
  2243. #endif // GTEST_HAS_STD_WSTRING
  2244. namespace internal {
  2245. #if GTEST_OS_WINDOWS
  2246. namespace {
  2247. // Helper function for IsHRESULT{SuccessFailure} predicates
  2248. AssertionResult HRESULTFailureHelper(const char* expr,
  2249. const char* expected,
  2250. long hr) { // NOLINT
  2251. # if GTEST_OS_WINDOWS_MOBILE
  2252. // Windows CE doesn't support FormatMessage.
  2253. const char error_text[] = "";
  2254. # else
  2255. // Looks up the human-readable system message for the HRESULT code
  2256. // and since we're not passing any params to FormatMessage, we don't
  2257. // want inserts expanded.
  2258. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
  2259. FORMAT_MESSAGE_IGNORE_INSERTS;
  2260. const DWORD kBufSize = 4096; // String::Format can't exceed this length.
  2261. // Gets the system's human readable message string for this HRESULT.
  2262. char error_text[kBufSize] = { '\0' };
  2263. DWORD message_length = ::FormatMessageA(kFlags,
  2264. 0, // no source, we're asking system
  2265. hr, // the error
  2266. 0, // no line width restrictions
  2267. error_text, // output buffer
  2268. kBufSize, // buf size
  2269. NULL); // no arguments for inserts
  2270. // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
  2271. for (; message_length && IsSpace(error_text[message_length - 1]);
  2272. --message_length) {
  2273. error_text[message_length - 1] = '\0';
  2274. }
  2275. # endif // GTEST_OS_WINDOWS_MOBILE
  2276. const String error_hex(String::Format("0x%08X ", hr));
  2277. return ::testing::AssertionFailure()
  2278. << "Expected: " << expr << " " << expected << ".\n"
  2279. << " Actual: " << error_hex << error_text << "\n";
  2280. }
  2281. } // namespace
  2282. AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
  2283. if (SUCCEEDED(hr)) {
  2284. return AssertionSuccess();
  2285. }
  2286. return HRESULTFailureHelper(expr, "succeeds", hr);
  2287. }
  2288. AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
  2289. if (FAILED(hr)) {
  2290. return AssertionSuccess();
  2291. }
  2292. return HRESULTFailureHelper(expr, "fails", hr);
  2293. }
  2294. #endif // GTEST_OS_WINDOWS
  2295. // Utility functions for encoding Unicode text (wide strings) in
  2296. // UTF-8.
  2297. // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
  2298. // like this:
  2299. //
  2300. // Code-point length Encoding
  2301. // 0 - 7 bits 0xxxxxxx
  2302. // 8 - 11 bits 110xxxxx 10xxxxxx
  2303. // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
  2304. // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  2305. // The maximum code-point a one-byte UTF-8 sequence can represent.
  2306. const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
  2307. // The maximum code-point a two-byte UTF-8 sequence can represent.
  2308. const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
  2309. // The maximum code-point a three-byte UTF-8 sequence can represent.
  2310. const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
  2311. // The maximum code-point a four-byte UTF-8 sequence can represent.
  2312. const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
  2313. // Chops off the n lowest bits from a bit pattern. Returns the n
  2314. // lowest bits. As a side effect, the original bit pattern will be
  2315. // shifted to the right by n bits.
  2316. inline UInt32 ChopLowBits(UInt32* bits, int n) {
  2317. const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
  2318. *bits >>= n;
  2319. return low_bits;
  2320. }
  2321. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  2322. // code_point parameter is of type UInt32 because wchar_t may not be
  2323. // wide enough to contain a code point.
  2324. // The output buffer str must containt at least 32 characters.
  2325. // The function returns the address of the output buffer.
  2326. // If the code_point is not a valid Unicode code point
  2327. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
  2328. // as '(Invalid Unicode 0xXXXXXXXX)'.
  2329. char* CodePointToUtf8(UInt32 code_point, char* str) {
  2330. if (code_point <= kMaxCodePoint1) {
  2331. str[1] = '\0';
  2332. str[0] = static_cast<char>(code_point); // 0xxxxxxx
  2333. } else if (code_point <= kMaxCodePoint2) {
  2334. str[2] = '\0';
  2335. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2336. str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
  2337. } else if (code_point <= kMaxCodePoint3) {
  2338. str[3] = '\0';
  2339. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2340. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2341. str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
  2342. } else if (code_point <= kMaxCodePoint4) {
  2343. str[4] = '\0';
  2344. str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2345. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2346. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2347. str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
  2348. } else {
  2349. // The longest string String::Format can produce when invoked
  2350. // with these parameters is 28 character long (not including
  2351. // the terminating nul character). We are asking for 32 character
  2352. // buffer just in case. This is also enough for strncpy to
  2353. // null-terminate the destination string.
  2354. posix::StrNCpy(
  2355. str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
  2356. str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
  2357. // the result unterminated.
  2358. }
  2359. return str;
  2360. }
  2361. // The following two functions only make sense if the the system
  2362. // uses UTF-16 for wide string encoding. All supported systems
  2363. // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
  2364. // Determines if the arguments constitute UTF-16 surrogate pair
  2365. // and thus should be combined into a single Unicode code point
  2366. // using CreateCodePointFromUtf16SurrogatePair.
  2367. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
  2368. return sizeof(wchar_t) == 2 &&
  2369. (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
  2370. }
  2371. // Creates a Unicode code point from UTF16 surrogate pair.
  2372. inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
  2373. wchar_t second) {
  2374. const UInt32 mask = (1 << 10) - 1;
  2375. return (sizeof(wchar_t) == 2) ?
  2376. (((first & mask) << 10) | (second & mask)) + 0x10000 :
  2377. // This function should not be called when the condition is
  2378. // false, but we provide a sensible default in case it is.
  2379. static_cast<UInt32>(first);
  2380. }
  2381. // Converts a wide string to a narrow string in UTF-8 encoding.
  2382. // The wide string is assumed to have the following encoding:
  2383. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
  2384. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  2385. // Parameter str points to a null-terminated wide string.
  2386. // Parameter num_chars may additionally limit the number
  2387. // of wchar_t characters processed. -1 is used when the entire string
  2388. // should be processed.
  2389. // If the string contains code points that are not valid Unicode code points
  2390. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  2391. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  2392. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  2393. // will be encoded as individual Unicode characters from Basic Normal Plane.
  2394. String WideStringToUtf8(const wchar_t* str, int num_chars) {
  2395. if (num_chars == -1)
  2396. num_chars = static_cast<int>(wcslen(str));
  2397. ::std::stringstream stream;
  2398. for (int i = 0; i < num_chars; ++i) {
  2399. UInt32 unicode_code_point;
  2400. if (str[i] == L'\0') {
  2401. break;
  2402. } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
  2403. unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
  2404. str[i + 1]);
  2405. i++;
  2406. } else {
  2407. unicode_code_point = static_cast<UInt32>(str[i]);
  2408. }
  2409. char buffer[32]; // CodePointToUtf8 requires a buffer this big.
  2410. stream << CodePointToUtf8(unicode_code_point, buffer);
  2411. }
  2412. return StringStreamToString(&stream);
  2413. }
  2414. // Converts a wide C string to a String using the UTF-8 encoding.
  2415. // NULL will be converted to "(null)".
  2416. String String::ShowWideCString(const wchar_t * wide_c_str) {
  2417. if (wide_c_str == NULL) return String("(null)");
  2418. return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
  2419. }
  2420. // Similar to ShowWideCString(), except that this function encloses
  2421. // the converted string in double quotes.
  2422. String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
  2423. if (wide_c_str == NULL) return String("(null)");
  2424. return String::Format("L\"%s\"",
  2425. String::ShowWideCString(wide_c_str).c_str());
  2426. }
  2427. // Compares two wide C strings. Returns true iff they have the same
  2428. // content.
  2429. //
  2430. // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
  2431. // C string is considered different to any non-NULL C string,
  2432. // including the empty string.
  2433. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
  2434. if (lhs == NULL) return rhs == NULL;
  2435. if (rhs == NULL) return false;
  2436. return wcscmp(lhs, rhs) == 0;
  2437. }
  2438. // Helper function for *_STREQ on wide strings.
  2439. AssertionResult CmpHelperSTREQ(const char* expected_expression,
  2440. const char* actual_expression,
  2441. const wchar_t* expected,
  2442. const wchar_t* actual) {
  2443. if (String::WideCStringEquals(expected, actual)) {
  2444. return AssertionSuccess();
  2445. }
  2446. return EqFailure(expected_expression,
  2447. actual_expression,
  2448. String::ShowWideCStringQuoted(expected),
  2449. String::ShowWideCStringQuoted(actual),
  2450. false);
  2451. }
  2452. // Helper function for *_STRNE on wide strings.
  2453. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  2454. const char* s2_expression,
  2455. const wchar_t* s1,
  2456. const wchar_t* s2) {
  2457. if (!String::WideCStringEquals(s1, s2)) {
  2458. return AssertionSuccess();
  2459. }
  2460. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  2461. << s2_expression << "), actual: "
  2462. << String::ShowWideCStringQuoted(s1)
  2463. << " vs " << String::ShowWideCStringQuoted(s2);
  2464. }
  2465. // Compares two C strings, ignoring case. Returns true iff they have
  2466. // the same content.
  2467. //
  2468. // Unlike strcasecmp(), this function can handle NULL argument(s). A
  2469. // NULL C string is considered different to any non-NULL C string,
  2470. // including the empty string.
  2471. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
  2472. if (lhs == NULL)
  2473. return rhs == NULL;
  2474. if (rhs == NULL)
  2475. return false;
  2476. return posix::StrCaseCmp(lhs, rhs) == 0;
  2477. }
  2478. // Compares two wide C strings, ignoring case. Returns true iff they
  2479. // have the same content.
  2480. //
  2481. // Unlike wcscasecmp(), this function can handle NULL argument(s).
  2482. // A NULL C string is considered different to any non-NULL wide C string,
  2483. // including the empty string.
  2484. // NB: The implementations on different platforms slightly differ.
  2485. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  2486. // environment variable. On GNU platform this method uses wcscasecmp
  2487. // which compares according to LC_CTYPE category of the current locale.
  2488. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  2489. // current locale.
  2490. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  2491. const wchar_t* rhs) {
  2492. if (lhs == NULL) return rhs == NULL;
  2493. if (rhs == NULL) return false;
  2494. #if GTEST_OS_WINDOWS
  2495. return _wcsicmp(lhs, rhs) == 0;
  2496. #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
  2497. return wcscasecmp(lhs, rhs) == 0;
  2498. #else
  2499. // Android, Mac OS X and Cygwin don't define wcscasecmp.
  2500. // Other unknown OSes may not define it either.
  2501. wint_t left, right;
  2502. do {
  2503. left = towlower(*lhs++);
  2504. right = towlower(*rhs++);
  2505. } while (left && left == right);
  2506. return left == right;
  2507. #endif // OS selector
  2508. }
  2509. // Compares this with another String.
  2510. // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
  2511. // if this is greater than rhs.
  2512. int String::Compare(const String & rhs) const {
  2513. const char* const lhs_c_str = c_str();
  2514. const char* const rhs_c_str = rhs.c_str();
  2515. if (lhs_c_str == NULL) {
  2516. return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL
  2517. } else if (rhs_c_str == NULL) {
  2518. return 1;
  2519. }
  2520. const size_t shorter_str_len =
  2521. length() <= rhs.length() ? length() : rhs.length();
  2522. for (size_t i = 0; i != shorter_str_len; i++) {
  2523. if (lhs_c_str[i] < rhs_c_str[i]) {
  2524. return -1;
  2525. } else if (lhs_c_str[i] > rhs_c_str[i]) {
  2526. return 1;
  2527. }
  2528. }
  2529. return (length() < rhs.length()) ? -1 :
  2530. (length() > rhs.length()) ? 1 : 0;
  2531. }
  2532. // Returns true iff this String ends with the given suffix. *Any*
  2533. // String is considered to end with a NULL or empty suffix.
  2534. bool String::EndsWith(const char* suffix) const {
  2535. if (suffix == NULL || CStringEquals(suffix, "")) return true;
  2536. if (c_str() == NULL) return false;
  2537. const size_t this_len = strlen(c_str());
  2538. const size_t suffix_len = strlen(suffix);
  2539. return (this_len >= suffix_len) &&
  2540. CStringEquals(c_str() + this_len - suffix_len, suffix);
  2541. }
  2542. // Returns true iff this String ends with the given suffix, ignoring case.
  2543. // Any String is considered to end with a NULL or empty suffix.
  2544. bool String::EndsWithCaseInsensitive(const char* suffix) const {
  2545. if (suffix == NULL || CStringEquals(suffix, "")) return true;
  2546. if (c_str() == NULL) return false;
  2547. const size_t this_len = strlen(c_str());
  2548. const size_t suffix_len = strlen(suffix);
  2549. return (this_len >= suffix_len) &&
  2550. CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
  2551. }
  2552. // Formats a list of arguments to a String, using the same format
  2553. // spec string as for printf.
  2554. //
  2555. // We do not use the StringPrintf class as it is not universally
  2556. // available.
  2557. //
  2558. // The result is limited to 4096 characters (including the tailing 0).
  2559. // If 4096 characters are not enough to format the input, or if
  2560. // there's an error, "<formatting error or buffer exceeded>" is
  2561. // returned.
  2562. String String::Format(const char * format, ...) {
  2563. va_list args;
  2564. va_start(args, format);
  2565. char buffer[4096];
  2566. const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
  2567. // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
  2568. // 4996 (deprecated function) there.
  2569. #ifdef _MSC_VER // We are using MSVC.
  2570. # pragma warning(push) // Saves the current warning state.
  2571. # pragma warning(disable:4996) // Temporarily disables warning 4996.
  2572. const int size = vsnprintf(buffer, kBufferSize, format, args);
  2573. # pragma warning(pop) // Restores the warning state.
  2574. #else // We are not using MSVC.
  2575. const int size = vsnprintf(buffer, kBufferSize, format, args);
  2576. #endif // _MSC_VER
  2577. va_end(args);
  2578. // vsnprintf()'s behavior is not portable. When the buffer is not
  2579. // big enough, it returns a negative value in MSVC, and returns the
  2580. // needed buffer size on Linux. When there is an output error, it
  2581. // always returns a negative value. For simplicity, we lump the two
  2582. // error cases together.
  2583. if (size < 0 || size >= kBufferSize) {
  2584. return String("<formatting error or buffer exceeded>");
  2585. } else {
  2586. return String(buffer, size);
  2587. }
  2588. }
  2589. // Converts the buffer in a stringstream to a String, converting NUL
  2590. // bytes to "\\0" along the way.
  2591. String StringStreamToString(::std::stringstream* ss) {
  2592. const ::std::string& str = ss->str();
  2593. const char* const start = str.c_str();
  2594. const char* const end = start + str.length();
  2595. // We need to use a helper stringstream to do this transformation
  2596. // because String doesn't support push_back().
  2597. ::std::stringstream helper;
  2598. for (const char* ch = start; ch != end; ++ch) {
  2599. if (*ch == '\0') {
  2600. helper << "\\0"; // Replaces NUL with "\\0";
  2601. } else {
  2602. helper.put(*ch);
  2603. }
  2604. }
  2605. return String(helper.str().c_str());
  2606. }
  2607. // Appends the user-supplied message to the Google-Test-generated message.
  2608. String AppendUserMessage(const String& gtest_msg,
  2609. const Message& user_msg) {
  2610. // Appends the user message if it's non-empty.
  2611. const String user_msg_string = user_msg.GetString();
  2612. if (user_msg_string.empty()) {
  2613. return gtest_msg;
  2614. }
  2615. Message msg;
  2616. msg << gtest_msg << "\n" << user_msg_string;
  2617. return msg.GetString();
  2618. }
  2619. } // namespace internal
  2620. // class TestResult
  2621. // Creates an empty TestResult.
  2622. TestResult::TestResult()
  2623. : death_test_count_(0),
  2624. elapsed_time_(0) {
  2625. }
  2626. // D'tor.
  2627. TestResult::~TestResult() {
  2628. }
  2629. // Returns the i-th test part result among all the results. i can
  2630. // range from 0 to total_part_count() - 1. If i is not in that range,
  2631. // aborts the program.
  2632. const TestPartResult& TestResult::GetTestPartResult(int i) const {
  2633. if (i < 0 || i >= total_part_count())
  2634. internal::posix::Abort();
  2635. return test_part_results_.at(i);
  2636. }
  2637. // Returns the i-th test property. i can range from 0 to
  2638. // test_property_count() - 1. If i is not in that range, aborts the
  2639. // program.
  2640. const TestProperty& TestResult::GetTestProperty(int i) const {
  2641. if (i < 0 || i >= test_property_count())
  2642. internal::posix::Abort();
  2643. return test_properties_.at(i);
  2644. }
  2645. // Clears the test part results.
  2646. void TestResult::ClearTestPartResults() {
  2647. test_part_results_.clear();
  2648. }
  2649. // Adds a test part result to the list.
  2650. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
  2651. test_part_results_.push_back(test_part_result);
  2652. }
  2653. // Adds a test property to the list. If a property with the same key as the
  2654. // supplied property is already represented, the value of this test_property
  2655. // replaces the old value for that key.
  2656. void TestResult::RecordProperty(const TestProperty& test_property) {
  2657. if (!ValidateTestProperty(test_property)) {
  2658. return;
  2659. }
  2660. internal::MutexLock lock(&test_properites_mutex_);
  2661. const std::vector<TestProperty>::iterator property_with_matching_key =
  2662. std::find_if(test_properties_.begin(), test_properties_.end(),
  2663. internal::TestPropertyKeyIs(test_property.key()));
  2664. if (property_with_matching_key == test_properties_.end()) {
  2665. test_properties_.push_back(test_property);
  2666. return;
  2667. }
  2668. property_with_matching_key->SetValue(test_property.value());
  2669. }
  2670. // Adds a failure if the key is a reserved attribute of Google Test
  2671. // testcase tags. Returns true if the property is valid.
  2672. bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
  2673. internal::String key(test_property.key());
  2674. if (key == "name" || key == "status" || key == "time" || key == "classname") {
  2675. ADD_FAILURE()
  2676. << "Reserved key used in RecordProperty(): "
  2677. << key
  2678. << " ('name', 'status', 'time', and 'classname' are reserved by "
  2679. << GTEST_NAME_ << ")";
  2680. return false;
  2681. }
  2682. return true;
  2683. }
  2684. // Clears the object.
  2685. void TestResult::Clear() {
  2686. test_part_results_.clear();
  2687. test_properties_.clear();
  2688. death_test_count_ = 0;
  2689. elapsed_time_ = 0;
  2690. }
  2691. // Returns true iff the test failed.
  2692. bool TestResult::Failed() const {
  2693. for (int i = 0; i < total_part_count(); ++i) {
  2694. if (GetTestPartResult(i).failed())
  2695. return true;
  2696. }
  2697. return false;
  2698. }
  2699. // Returns true iff the test part fatally failed.
  2700. static bool TestPartFatallyFailed(const TestPartResult& result) {
  2701. return result.fatally_failed();
  2702. }
  2703. // Returns true iff the test fatally failed.
  2704. bool TestResult::HasFatalFailure() const {
  2705. return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
  2706. }
  2707. // Returns true iff the test part non-fatally failed.
  2708. static bool TestPartNonfatallyFailed(const TestPartResult& result) {
  2709. return result.nonfatally_failed();
  2710. }
  2711. // Returns true iff the test has a non-fatal failure.
  2712. bool TestResult::HasNonfatalFailure() const {
  2713. return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
  2714. }
  2715. // Gets the number of all test parts. This is the sum of the number
  2716. // of successful test parts and the number of failed test parts.
  2717. int TestResult::total_part_count() const {
  2718. return static_cast<int>(test_part_results_.size());
  2719. }
  2720. // Returns the number of the test properties.
  2721. int TestResult::test_property_count() const {
  2722. return static_cast<int>(test_properties_.size());
  2723. }
  2724. // class Test
  2725. // Creates a Test object.
  2726. // The c'tor saves the values of all Google Test flags.
  2727. Test::Test()
  2728. : gtest_flag_saver_(new internal::GTestFlagSaver) {
  2729. }
  2730. // The d'tor restores the values of all Google Test flags.
  2731. Test::~Test() {
  2732. delete gtest_flag_saver_;
  2733. }
  2734. // Sets up the test fixture.
  2735. //
  2736. // A sub-class may override this.
  2737. void Test::SetUp() {
  2738. }
  2739. // Tears down the test fixture.
  2740. //
  2741. // A sub-class may override this.
  2742. void Test::TearDown() {
  2743. }
  2744. // Allows user supplied key value pairs to be recorded for later output.
  2745. void Test::RecordProperty(const char* key, const char* value) {
  2746. UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
  2747. }
  2748. // Allows user supplied key value pairs to be recorded for later output.
  2749. void Test::RecordProperty(const char* key, int value) {
  2750. Message value_message;
  2751. value_message << value;
  2752. RecordProperty(key, value_message.GetString().c_str());
  2753. }
  2754. namespace internal {
  2755. void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  2756. const String& message) {
  2757. // This function is a friend of UnitTest and as such has access to
  2758. // AddTestPartResult.
  2759. UnitTest::GetInstance()->AddTestPartResult(
  2760. result_type,
  2761. NULL, // No info about the source file where the exception occurred.
  2762. -1, // We have no info on which line caused the exception.
  2763. message,
  2764. String()); // No stack trace, either.
  2765. }
  2766. } // namespace internal
  2767. // Google Test requires all tests in the same test case to use the same test
  2768. // fixture class. This function checks if the current test has the
  2769. // same fixture class as the first test in the current test case. If
  2770. // yes, it returns true; otherwise it generates a Google Test failure and
  2771. // returns false.
  2772. bool Test::HasSameFixtureClass() {
  2773. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2774. const TestCase* const test_case = impl->current_test_case();
  2775. // Info about the first test in the current test case.
  2776. const TestInfo* const first_test_info = test_case->test_info_list()[0];
  2777. const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
  2778. const char* const first_test_name = first_test_info->name();
  2779. // Info about the current test.
  2780. const TestInfo* const this_test_info = impl->current_test_info();
  2781. const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
  2782. const char* const this_test_name = this_test_info->name();
  2783. if (this_fixture_id != first_fixture_id) {
  2784. // Is the first test defined using TEST?
  2785. const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
  2786. // Is this test defined using TEST?
  2787. const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
  2788. if (first_is_TEST || this_is_TEST) {
  2789. // The user mixed TEST and TEST_F in this test case - we'll tell
  2790. // him/her how to fix it.
  2791. // Gets the name of the TEST and the name of the TEST_F. Note
  2792. // that first_is_TEST and this_is_TEST cannot both be true, as
  2793. // the fixture IDs are different for the two tests.
  2794. const char* const TEST_name =
  2795. first_is_TEST ? first_test_name : this_test_name;
  2796. const char* const TEST_F_name =
  2797. first_is_TEST ? this_test_name : first_test_name;
  2798. ADD_FAILURE()
  2799. << "All tests in the same test case must use the same test fixture\n"
  2800. << "class, so mixing TEST_F and TEST in the same test case is\n"
  2801. << "illegal. In test case " << this_test_info->test_case_name()
  2802. << ",\n"
  2803. << "test " << TEST_F_name << " is defined using TEST_F but\n"
  2804. << "test " << TEST_name << " is defined using TEST. You probably\n"
  2805. << "want to change the TEST to TEST_F or move it to another test\n"
  2806. << "case.";
  2807. } else {
  2808. // The user defined two fixture classes with the same name in
  2809. // two namespaces - we'll tell him/her how to fix it.
  2810. ADD_FAILURE()
  2811. << "All tests in the same test case must use the same test fixture\n"
  2812. << "class. However, in test case "
  2813. << this_test_info->test_case_name() << ",\n"
  2814. << "you defined test " << first_test_name
  2815. << " and test " << this_test_name << "\n"
  2816. << "using two different test fixture classes. This can happen if\n"
  2817. << "the two classes are from different namespaces or translation\n"
  2818. << "units and have the same name. You should probably rename one\n"
  2819. << "of the classes to put the tests into different test cases.";
  2820. }
  2821. return false;
  2822. }
  2823. return true;
  2824. }
  2825. #if GTEST_HAS_SEH
  2826. // Adds an "exception thrown" fatal failure to the current test. This
  2827. // function returns its result via an output parameter pointer because VC++
  2828. // prohibits creation of objects with destructors on stack in functions
  2829. // using __try (see error C2712).
  2830. static internal::String* FormatSehExceptionMessage(DWORD exception_code,
  2831. const char* location) {
  2832. Message message;
  2833. message << "SEH exception with code 0x" << std::setbase(16) <<
  2834. exception_code << std::setbase(10) << " thrown in " << location << ".";
  2835. return new internal::String(message.GetString());
  2836. }
  2837. #endif // GTEST_HAS_SEH
  2838. #if GTEST_HAS_EXCEPTIONS
  2839. // Adds an "exception thrown" fatal failure to the current test.
  2840. static internal::String FormatCxxExceptionMessage(const char* description,
  2841. const char* location) {
  2842. Message message;
  2843. if (description != NULL) {
  2844. message << "C++ exception with description \"" << description << "\"";
  2845. } else {
  2846. message << "Unknown C++ exception";
  2847. }
  2848. message << " thrown in " << location << ".";
  2849. return message.GetString();
  2850. }
  2851. static internal::String PrintTestPartResultToString(
  2852. const TestPartResult& test_part_result);
  2853. // A failed Google Test assertion will throw an exception of this type when
  2854. // GTEST_FLAG(throw_on_failure) is true (if exceptions are enabled). We
  2855. // derive it from std::runtime_error, which is for errors presumably
  2856. // detectable only at run time. Since std::runtime_error inherits from
  2857. // std::exception, many testing frameworks know how to extract and print the
  2858. // message inside it.
  2859. class GoogleTestFailureException : public ::std::runtime_error {
  2860. public:
  2861. explicit GoogleTestFailureException(const TestPartResult& failure)
  2862. : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
  2863. };
  2864. #endif // GTEST_HAS_EXCEPTIONS
  2865. namespace internal {
  2866. // We put these helper functions in the internal namespace as IBM's xlC
  2867. // compiler rejects the code if they were declared static.
  2868. // Runs the given method and handles SEH exceptions it throws, when
  2869. // SEH is supported; returns the 0-value for type Result in case of an
  2870. // SEH exception. (Microsoft compilers cannot handle SEH and C++
  2871. // exceptions in the same function. Therefore, we provide a separate
  2872. // wrapper function for handling SEH exceptions.)
  2873. template <class T, typename Result>
  2874. Result HandleSehExceptionsInMethodIfSupported(
  2875. T* object, Result (T::*method)(), const char* location) {
  2876. #if GTEST_HAS_SEH
  2877. __try {
  2878. return (object->*method)();
  2879. } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
  2880. GetExceptionCode())) {
  2881. // We create the exception message on the heap because VC++ prohibits
  2882. // creation of objects with destructors on stack in functions using __try
  2883. // (see error C2712).
  2884. internal::String* exception_message = FormatSehExceptionMessage(
  2885. GetExceptionCode(), location);
  2886. internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
  2887. *exception_message);
  2888. delete exception_message;
  2889. return static_cast<Result>(0);
  2890. }
  2891. #else
  2892. (void)location;
  2893. return (object->*method)();
  2894. #endif // GTEST_HAS_SEH
  2895. }
  2896. // Runs the given method and catches and reports C++ and/or SEH-style
  2897. // exceptions, if they are supported; returns the 0-value for type
  2898. // Result in case of an SEH exception.
  2899. template <class T, typename Result>
  2900. Result HandleExceptionsInMethodIfSupported(
  2901. T* object, Result (T::*method)(), const char* location) {
  2902. // NOTE: The user code can affect the way in which Google Test handles
  2903. // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
  2904. // RUN_ALL_TESTS() starts. It is technically possible to check the flag
  2905. // after the exception is caught and either report or re-throw the
  2906. // exception based on the flag's value:
  2907. //
  2908. // try {
  2909. // // Perform the test method.
  2910. // } catch (...) {
  2911. // if (GTEST_FLAG(catch_exceptions))
  2912. // // Report the exception as failure.
  2913. // else
  2914. // throw; // Re-throws the original exception.
  2915. // }
  2916. //
  2917. // However, the purpose of this flag is to allow the program to drop into
  2918. // the debugger when the exception is thrown. On most platforms, once the
  2919. // control enters the catch block, the exception origin information is
  2920. // lost and the debugger will stop the program at the point of the
  2921. // re-throw in this function -- instead of at the point of the original
  2922. // throw statement in the code under test. For this reason, we perform
  2923. // the check early, sacrificing the ability to affect Google Test's
  2924. // exception handling in the method where the exception is thrown.
  2925. if (internal::GetUnitTestImpl()->catch_exceptions()) {
  2926. #if GTEST_HAS_EXCEPTIONS
  2927. try {
  2928. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  2929. } catch (const GoogleTestFailureException&) { // NOLINT
  2930. // This exception doesn't originate in code under test. It makes no
  2931. // sense to report it as a test failure.
  2932. throw;
  2933. } catch (const std::exception& e) { // NOLINT
  2934. internal::ReportFailureInUnknownLocation(
  2935. TestPartResult::kFatalFailure,
  2936. FormatCxxExceptionMessage(e.what(), location));
  2937. } catch (...) { // NOLINT
  2938. internal::ReportFailureInUnknownLocation(
  2939. TestPartResult::kFatalFailure,
  2940. FormatCxxExceptionMessage(NULL, location));
  2941. }
  2942. return static_cast<Result>(0);
  2943. #else
  2944. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  2945. #endif // GTEST_HAS_EXCEPTIONS
  2946. } else {
  2947. return (object->*method)();
  2948. }
  2949. }
  2950. } // namespace internal
  2951. // Runs the test and updates the test result.
  2952. void Test::Run() {
  2953. if (!HasSameFixtureClass()) return;
  2954. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2955. impl->os_stack_trace_getter()->UponLeavingGTest();
  2956. internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
  2957. // We will run the test only if SetUp() was successful.
  2958. if (!HasFatalFailure()) {
  2959. impl->os_stack_trace_getter()->UponLeavingGTest();
  2960. internal::HandleExceptionsInMethodIfSupported(
  2961. this, &Test::TestBody, "the test body");
  2962. }
  2963. // However, we want to clean up as much as possible. Hence we will
  2964. // always call TearDown(), even if SetUp() or the test body has
  2965. // failed.
  2966. impl->os_stack_trace_getter()->UponLeavingGTest();
  2967. internal::HandleExceptionsInMethodIfSupported(
  2968. this, &Test::TearDown, "TearDown()");
  2969. }
  2970. // Returns true iff the current test has a fatal failure.
  2971. bool Test::HasFatalFailure() {
  2972. return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
  2973. }
  2974. // Returns true iff the current test has a non-fatal failure.
  2975. bool Test::HasNonfatalFailure() {
  2976. return internal::GetUnitTestImpl()->current_test_result()->
  2977. HasNonfatalFailure();
  2978. }
  2979. // class TestInfo
  2980. // Constructs a TestInfo object. It assumes ownership of the test factory
  2981. // object.
  2982. // TODO([email protected]): Make a_test_case_name and a_name const string&'s
  2983. // to signify they cannot be NULLs.
  2984. TestInfo::TestInfo(const char* a_test_case_name,
  2985. const char* a_name,
  2986. const char* a_type_param,
  2987. const char* a_value_param,
  2988. internal::TypeId fixture_class_id,
  2989. internal::TestFactoryBase* factory)
  2990. : test_case_name_(a_test_case_name),
  2991. name_(a_name),
  2992. type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  2993. value_param_(a_value_param ? new std::string(a_value_param) : NULL),
  2994. fixture_class_id_(fixture_class_id),
  2995. should_run_(false),
  2996. is_disabled_(false),
  2997. matches_filter_(false),
  2998. factory_(factory),
  2999. result_() {}
  3000. // Destructs a TestInfo object.
  3001. TestInfo::~TestInfo() { delete factory_; }
  3002. namespace internal {
  3003. // Creates a new TestInfo object and registers it with Google Test;
  3004. // returns the created object.
  3005. //
  3006. // Arguments:
  3007. //
  3008. // test_case_name: name of the test case
  3009. // name: name of the test
  3010. // type_param: the name of the test's type parameter, or NULL if
  3011. // this is not a typed or a type-parameterized test.
  3012. // value_param: text representation of the test's value parameter,
  3013. // or NULL if this is not a value-parameterized test.
  3014. // fixture_class_id: ID of the test fixture class
  3015. // set_up_tc: pointer to the function that sets up the test case
  3016. // tear_down_tc: pointer to the function that tears down the test case
  3017. // factory: pointer to the factory that creates a test object.
  3018. // The newly created TestInfo instance will assume
  3019. // ownership of the factory object.
  3020. TestInfo* MakeAndRegisterTestInfo(
  3021. const char* test_case_name, const char* name,
  3022. const char* type_param,
  3023. const char* value_param,
  3024. TypeId fixture_class_id,
  3025. SetUpTestCaseFunc set_up_tc,
  3026. TearDownTestCaseFunc tear_down_tc,
  3027. TestFactoryBase* factory) {
  3028. TestInfo* const test_info =
  3029. new TestInfo(test_case_name, name, type_param, value_param,
  3030. fixture_class_id, factory);
  3031. GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
  3032. return test_info;
  3033. }
  3034. #if GTEST_HAS_PARAM_TEST
  3035. void ReportInvalidTestCaseType(const char* test_case_name,
  3036. const char* file, int line) {
  3037. Message errors;
  3038. errors
  3039. << "Attempted redefinition of test case " << test_case_name << ".\n"
  3040. << "All tests in the same test case must use the same test fixture\n"
  3041. << "class. However, in test case " << test_case_name << ", you tried\n"
  3042. << "to define a test using a fixture class different from the one\n"
  3043. << "used earlier. This can happen if the two fixture classes are\n"
  3044. << "from different namespaces and have the same name. You should\n"
  3045. << "probably rename one of the classes to put the tests into different\n"
  3046. << "test cases.";
  3047. fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
  3048. errors.GetString().c_str());
  3049. }
  3050. #endif // GTEST_HAS_PARAM_TEST
  3051. } // namespace internal
  3052. namespace {
  3053. // A predicate that checks the test name of a TestInfo against a known
  3054. // value.
  3055. //
  3056. // This is used for implementation of the TestCase class only. We put
  3057. // it in the anonymous namespace to prevent polluting the outer
  3058. // namespace.
  3059. //
  3060. // TestNameIs is copyable.
  3061. class TestNameIs {
  3062. public:
  3063. // Constructor.
  3064. //
  3065. // TestNameIs has NO default constructor.
  3066. explicit TestNameIs(const char* name)
  3067. : name_(name) {}
  3068. // Returns true iff the test name of test_info matches name_.
  3069. bool operator()(const TestInfo * test_info) const {
  3070. return test_info && internal::String(test_info->name()).Compare(name_) == 0;
  3071. }
  3072. private:
  3073. internal::String name_;
  3074. };
  3075. } // namespace
  3076. namespace internal {
  3077. // This method expands all parameterized tests registered with macros TEST_P
  3078. // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
  3079. // This will be done just once during the program runtime.
  3080. void UnitTestImpl::RegisterParameterizedTests() {
  3081. #if GTEST_HAS_PARAM_TEST
  3082. if (!parameterized_tests_registered_) {
  3083. parameterized_test_registry_.RegisterTests();
  3084. parameterized_tests_registered_ = true;
  3085. }
  3086. #endif
  3087. }
  3088. } // namespace internal
  3089. // Creates the test object, runs it, records its result, and then
  3090. // deletes it.
  3091. void TestInfo::Run() {
  3092. if (!should_run_) return;
  3093. // Tells UnitTest where to store test result.
  3094. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3095. impl->set_current_test_info(this);
  3096. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3097. // Notifies the unit test event listeners that a test is about to start.
  3098. repeater->OnTestStart(*this);
  3099. const TimeInMillis start = internal::GetTimeInMillis();
  3100. impl->os_stack_trace_getter()->UponLeavingGTest();
  3101. // Creates the test object.
  3102. Test* const test = internal::HandleExceptionsInMethodIfSupported(
  3103. factory_, &internal::TestFactoryBase::CreateTest,
  3104. "the test fixture's constructor");
  3105. // Runs the test only if the test object was created and its
  3106. // constructor didn't generate a fatal failure.
  3107. if ((test != NULL) && !Test::HasFatalFailure()) {
  3108. // This doesn't throw as all user code that can throw are wrapped into
  3109. // exception handling code.
  3110. test->Run();
  3111. }
  3112. // Deletes the test object.
  3113. impl->os_stack_trace_getter()->UponLeavingGTest();
  3114. internal::HandleExceptionsInMethodIfSupported(
  3115. test, &Test::DeleteSelf_, "the test fixture's destructor");
  3116. result_.set_elapsed_time(internal::GetTimeInMillis() - start);
  3117. // Notifies the unit test event listener that a test has just finished.
  3118. repeater->OnTestEnd(*this);
  3119. // Tells UnitTest to stop associating assertion results to this
  3120. // test.
  3121. impl->set_current_test_info(NULL);
  3122. }
  3123. // class TestCase
  3124. // Gets the number of successful tests in this test case.
  3125. int TestCase::successful_test_count() const {
  3126. return CountIf(test_info_list_, TestPassed);
  3127. }
  3128. // Gets the number of failed tests in this test case.
  3129. int TestCase::failed_test_count() const {
  3130. return CountIf(test_info_list_, TestFailed);
  3131. }
  3132. int TestCase::disabled_test_count() const {
  3133. return CountIf(test_info_list_, TestDisabled);
  3134. }
  3135. // Get the number of tests in this test case that should run.
  3136. int TestCase::test_to_run_count() const {
  3137. return CountIf(test_info_list_, ShouldRunTest);
  3138. }
  3139. // Gets the number of all tests.
  3140. int TestCase::total_test_count() const {
  3141. return static_cast<int>(test_info_list_.size());
  3142. }
  3143. // Creates a TestCase with the given name.
  3144. //
  3145. // Arguments:
  3146. //
  3147. // name: name of the test case
  3148. // a_type_param: the name of the test case's type parameter, or NULL if
  3149. // this is not a typed or a type-parameterized test case.
  3150. // set_up_tc: pointer to the function that sets up the test case
  3151. // tear_down_tc: pointer to the function that tears down the test case
  3152. TestCase::TestCase(const char* a_name, const char* a_type_param,
  3153. Test::SetUpTestCaseFunc set_up_tc,
  3154. Test::TearDownTestCaseFunc tear_down_tc)
  3155. : name_(a_name),
  3156. type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  3157. set_up_tc_(set_up_tc),
  3158. tear_down_tc_(tear_down_tc),
  3159. should_run_(false),
  3160. elapsed_time_(0) {
  3161. }
  3162. // Destructor of TestCase.
  3163. TestCase::~TestCase() {
  3164. // Deletes every Test in the collection.
  3165. ForEach(test_info_list_, internal::Delete<TestInfo>);
  3166. }
  3167. // Returns the i-th test among all the tests. i can range from 0 to
  3168. // total_test_count() - 1. If i is not in that range, returns NULL.
  3169. const TestInfo* TestCase::GetTestInfo(int i) const {
  3170. const int index = GetElementOr(test_indices_, i, -1);
  3171. return index < 0 ? NULL : test_info_list_[index];
  3172. }
  3173. // Returns the i-th test among all the tests. i can range from 0 to
  3174. // total_test_count() - 1. If i is not in that range, returns NULL.
  3175. TestInfo* TestCase::GetMutableTestInfo(int i) {
  3176. const int index = GetElementOr(test_indices_, i, -1);
  3177. return index < 0 ? NULL : test_info_list_[index];
  3178. }
  3179. // Adds a test to this test case. Will delete the test upon
  3180. // destruction of the TestCase object.
  3181. void TestCase::AddTestInfo(TestInfo * test_info) {
  3182. test_info_list_.push_back(test_info);
  3183. test_indices_.push_back(static_cast<int>(test_indices_.size()));
  3184. }
  3185. // Runs every test in this TestCase.
  3186. void TestCase::Run() {
  3187. if (!should_run_) return;
  3188. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3189. impl->set_current_test_case(this);
  3190. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3191. repeater->OnTestCaseStart(*this);
  3192. impl->os_stack_trace_getter()->UponLeavingGTest();
  3193. internal::HandleExceptionsInMethodIfSupported(
  3194. this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
  3195. const internal::TimeInMillis start = internal::GetTimeInMillis();
  3196. for (int i = 0; i < total_test_count(); i++) {
  3197. GetMutableTestInfo(i)->Run();
  3198. }
  3199. elapsed_time_ = internal::GetTimeInMillis() - start;
  3200. impl->os_stack_trace_getter()->UponLeavingGTest();
  3201. internal::HandleExceptionsInMethodIfSupported(
  3202. this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
  3203. repeater->OnTestCaseEnd(*this);
  3204. impl->set_current_test_case(NULL);
  3205. }
  3206. // Clears the results of all tests in this test case.
  3207. void TestCase::ClearResult() {
  3208. ForEach(test_info_list_, TestInfo::ClearTestResult);
  3209. }
  3210. // Shuffles the tests in this test case.
  3211. void TestCase::ShuffleTests(internal::Random* random) {
  3212. Shuffle(random, &test_indices_);
  3213. }
  3214. // Restores the test order to before the first shuffle.
  3215. void TestCase::UnshuffleTests() {
  3216. for (size_t i = 0; i < test_indices_.size(); i++) {
  3217. test_indices_[i] = static_cast<int>(i);
  3218. }
  3219. }
  3220. // Formats a countable noun. Depending on its quantity, either the
  3221. // singular form or the plural form is used. e.g.
  3222. //
  3223. // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
  3224. // FormatCountableNoun(5, "book", "books") returns "5 books".
  3225. static internal::String FormatCountableNoun(int count,
  3226. const char * singular_form,
  3227. const char * plural_form) {
  3228. return internal::String::Format("%d %s", count,
  3229. count == 1 ? singular_form : plural_form);
  3230. }
  3231. // Formats the count of tests.
  3232. static internal::String FormatTestCount(int test_count) {
  3233. return FormatCountableNoun(test_count, "test", "tests");
  3234. }
  3235. // Formats the count of test cases.
  3236. static internal::String FormatTestCaseCount(int test_case_count) {
  3237. return FormatCountableNoun(test_case_count, "test case", "test cases");
  3238. }
  3239. // Converts a TestPartResult::Type enum to human-friendly string
  3240. // representation. Both kNonFatalFailure and kFatalFailure are translated
  3241. // to "Failure", as the user usually doesn't care about the difference
  3242. // between the two when viewing the test result.
  3243. static const char * TestPartResultTypeToString(TestPartResult::Type type) {
  3244. switch (type) {
  3245. case TestPartResult::kSuccess:
  3246. return "Success";
  3247. case TestPartResult::kNonFatalFailure:
  3248. case TestPartResult::kFatalFailure:
  3249. #ifdef _MSC_VER
  3250. return "error: ";
  3251. #else
  3252. return "Failure\n";
  3253. #endif
  3254. default:
  3255. return "Unknown result type";
  3256. }
  3257. }
  3258. // Prints a TestPartResult to a String.
  3259. static internal::String PrintTestPartResultToString(
  3260. const TestPartResult& test_part_result) {
  3261. return (Message()
  3262. << internal::FormatFileLocation(test_part_result.file_name(),
  3263. test_part_result.line_number())
  3264. << " " << TestPartResultTypeToString(test_part_result.type())
  3265. << test_part_result.message()).GetString();
  3266. }
  3267. // Prints a TestPartResult.
  3268. static void PrintTestPartResult(const TestPartResult& test_part_result) {
  3269. const internal::String& result =
  3270. PrintTestPartResultToString(test_part_result);
  3271. printf("%s\n", result.c_str());
  3272. fflush(stdout);
  3273. // If the test program runs in Visual Studio or a debugger, the
  3274. // following statements add the test part result message to the Output
  3275. // window such that the user can double-click on it to jump to the
  3276. // corresponding source code location; otherwise they do nothing.
  3277. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3278. // We don't call OutputDebugString*() on Windows Mobile, as printing
  3279. // to stdout is done by OutputDebugString() there already - we don't
  3280. // want the same message printed twice.
  3281. ::OutputDebugStringA(result.c_str());
  3282. ::OutputDebugStringA("\n");
  3283. #endif
  3284. }
  3285. // class PrettyUnitTestResultPrinter
  3286. namespace internal {
  3287. enum GTestColor {
  3288. COLOR_DEFAULT,
  3289. COLOR_RED,
  3290. COLOR_GREEN,
  3291. COLOR_YELLOW
  3292. };
  3293. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3294. // Returns the character attribute for the given color.
  3295. WORD GetColorAttribute(GTestColor color) {
  3296. switch (color) {
  3297. case COLOR_RED: return FOREGROUND_RED;
  3298. case COLOR_GREEN: return FOREGROUND_GREEN;
  3299. case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
  3300. default: return 0;
  3301. }
  3302. }
  3303. #else
  3304. // Returns the ANSI color code for the given color. COLOR_DEFAULT is
  3305. // an invalid input.
  3306. const char* GetAnsiColorCode(GTestColor color) {
  3307. switch (color) {
  3308. case COLOR_RED: return "1";
  3309. case COLOR_GREEN: return "2";
  3310. case COLOR_YELLOW: return "3";
  3311. default: return NULL;
  3312. };
  3313. }
  3314. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3315. // Returns true iff Google Test should use colors in the output.
  3316. bool ShouldUseColor(bool stdout_is_tty) {
  3317. const char* const gtest_color = GTEST_FLAG(color).c_str();
  3318. if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
  3319. #if GTEST_OS_WINDOWS
  3320. // On Windows the TERM variable is usually not set, but the
  3321. // console there does support colors.
  3322. return stdout_is_tty;
  3323. #else
  3324. // On non-Windows platforms, we rely on the TERM variable.
  3325. const char* const term = posix::GetEnv("TERM");
  3326. const bool term_supports_color =
  3327. String::CStringEquals(term, "xterm") ||
  3328. String::CStringEquals(term, "xterm-color") ||
  3329. String::CStringEquals(term, "xterm-256color") ||
  3330. String::CStringEquals(term, "screen") ||
  3331. String::CStringEquals(term, "linux") ||
  3332. String::CStringEquals(term, "cygwin");
  3333. return stdout_is_tty && term_supports_color;
  3334. #endif // GTEST_OS_WINDOWS
  3335. }
  3336. return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
  3337. String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
  3338. String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
  3339. String::CStringEquals(gtest_color, "1");
  3340. // We take "yes", "true", "t", and "1" as meaning "yes". If the
  3341. // value is neither one of these nor "auto", we treat it as "no" to
  3342. // be conservative.
  3343. }
  3344. // Helpers for printing colored strings to stdout. Note that on Windows, we
  3345. // cannot simply emit special characters and have the terminal change colors.
  3346. // This routine must actually emit the characters rather than return a string
  3347. // that would be colored when printed, as can be done on Linux.
  3348. void ColoredPrintf(GTestColor color, const char* fmt, ...) {
  3349. va_list args;
  3350. va_start(args, fmt);
  3351. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
  3352. const bool use_color = false;
  3353. #else
  3354. static const bool in_color_mode =
  3355. ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
  3356. const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
  3357. #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
  3358. // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
  3359. if (!use_color) {
  3360. vprintf(fmt, args);
  3361. va_end(args);
  3362. return;
  3363. }
  3364. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3365. const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  3366. // Gets the current text color.
  3367. CONSOLE_SCREEN_BUFFER_INFO buffer_info;
  3368. GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
  3369. const WORD old_color_attrs = buffer_info.wAttributes;
  3370. // We need to flush the stream buffers into the console before each
  3371. // SetConsoleTextAttribute call lest it affect the text that is already
  3372. // printed but has not yet reached the console.
  3373. fflush(stdout);
  3374. SetConsoleTextAttribute(stdout_handle,
  3375. GetColorAttribute(color) | FOREGROUND_INTENSITY);
  3376. vprintf(fmt, args);
  3377. fflush(stdout);
  3378. // Restores the text color.
  3379. SetConsoleTextAttribute(stdout_handle, old_color_attrs);
  3380. #else
  3381. printf("\033[0;3%sm", GetAnsiColorCode(color));
  3382. vprintf(fmt, args);
  3383. printf("\033[m"); // Resets the terminal to default.
  3384. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3385. va_end(args);
  3386. }
  3387. void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
  3388. const char* const type_param = test_info.type_param();
  3389. const char* const value_param = test_info.value_param();
  3390. if (type_param != NULL || value_param != NULL) {
  3391. printf(", where ");
  3392. if (type_param != NULL) {
  3393. printf("TypeParam = %s", type_param);
  3394. if (value_param != NULL)
  3395. printf(" and ");
  3396. }
  3397. if (value_param != NULL) {
  3398. printf("GetParam() = %s", value_param);
  3399. }
  3400. }
  3401. }
  3402. // This class implements the TestEventListener interface.
  3403. //
  3404. // Class PrettyUnitTestResultPrinter is copyable.
  3405. class PrettyUnitTestResultPrinter : public TestEventListener {
  3406. public:
  3407. PrettyUnitTestResultPrinter() {}
  3408. static void PrintTestName(const char * test_case, const char * test) {
  3409. printf("%s.%s", test_case, test);
  3410. }
  3411. // The following methods override what's in the TestEventListener class.
  3412. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
  3413. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  3414. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  3415. virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
  3416. virtual void OnTestCaseStart(const TestCase& test_case);
  3417. virtual void OnTestStart(const TestInfo& test_info);
  3418. virtual void OnTestPartResult(const TestPartResult& result);
  3419. virtual void OnTestEnd(const TestInfo& test_info);
  3420. virtual void OnTestCaseEnd(const TestCase& test_case);
  3421. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  3422. virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
  3423. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3424. virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
  3425. private:
  3426. static void PrintFailedTests(const UnitTest& unit_test);
  3427. internal::String test_case_name_;
  3428. };
  3429. // Fired before each iteration of tests starts.
  3430. void PrettyUnitTestResultPrinter::OnTestIterationStart(
  3431. const UnitTest& unit_test, int iteration) {
  3432. if (GTEST_FLAG(repeat) != 1)
  3433. printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
  3434. const char* const filter = GTEST_FLAG(filter).c_str();
  3435. // Prints the filter if it's not *. This reminds the user that some
  3436. // tests may be skipped.
  3437. if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
  3438. ColoredPrintf(COLOR_YELLOW,
  3439. "Note: %s filter = %s\n", GTEST_NAME_, filter);
  3440. }
  3441. if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
  3442. const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
  3443. ColoredPrintf(COLOR_YELLOW,
  3444. "Note: This is test shard %d of %s.\n",
  3445. static_cast<int>(shard_index) + 1,
  3446. internal::posix::GetEnv(kTestTotalShards));
  3447. }
  3448. if (GTEST_FLAG(shuffle)) {
  3449. ColoredPrintf(COLOR_YELLOW,
  3450. "Note: Randomizing tests' orders with a seed of %d .\n",
  3451. unit_test.random_seed());
  3452. }
  3453. ColoredPrintf(COLOR_GREEN, "[==========] ");
  3454. printf("Running %s from %s.\n",
  3455. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  3456. FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  3457. fflush(stdout);
  3458. }
  3459. void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
  3460. const UnitTest& /*unit_test*/) {
  3461. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3462. printf("Global test environment set-up.\n");
  3463. fflush(stdout);
  3464. }
  3465. void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
  3466. test_case_name_ = test_case.name();
  3467. const internal::String counts =
  3468. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  3469. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3470. printf("%s from %s", counts.c_str(), test_case_name_.c_str());
  3471. if (test_case.type_param() == NULL) {
  3472. printf("\n");
  3473. } else {
  3474. printf(", where TypeParam = %s\n", test_case.type_param());
  3475. }
  3476. fflush(stdout);
  3477. }
  3478. void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
  3479. ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
  3480. PrintTestName(test_case_name_.c_str(), test_info.name());
  3481. printf("\n");
  3482. fflush(stdout);
  3483. }
  3484. // Called after an assertion failure.
  3485. void PrettyUnitTestResultPrinter::OnTestPartResult(
  3486. const TestPartResult& result) {
  3487. // If the test part succeeded, we don't need to do anything.
  3488. if (result.type() == TestPartResult::kSuccess)
  3489. return;
  3490. // Print failure message from the assertion (e.g. expected this and got that).
  3491. PrintTestPartResult(result);
  3492. fflush(stdout);
  3493. }
  3494. void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  3495. if (test_info.result()->Passed()) {
  3496. ColoredPrintf(COLOR_GREEN, "[ OK ] ");
  3497. } else {
  3498. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  3499. }
  3500. PrintTestName(test_case_name_.c_str(), test_info.name());
  3501. if (test_info.result()->Failed())
  3502. PrintFullTestCommentIfPresent(test_info);
  3503. if (GTEST_FLAG(print_time)) {
  3504. printf(" (%s ms)\n", internal::StreamableToString(
  3505. test_info.result()->elapsed_time()).c_str());
  3506. } else {
  3507. printf("\n");
  3508. }
  3509. fflush(stdout);
  3510. }
  3511. void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
  3512. if (!GTEST_FLAG(print_time)) return;
  3513. test_case_name_ = test_case.name();
  3514. const internal::String counts =
  3515. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  3516. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3517. printf("%s from %s (%s ms total)\n\n",
  3518. counts.c_str(), test_case_name_.c_str(),
  3519. internal::StreamableToString(test_case.elapsed_time()).c_str());
  3520. fflush(stdout);
  3521. }
  3522. void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
  3523. const UnitTest& /*unit_test*/) {
  3524. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3525. printf("Global test environment tear-down\n");
  3526. fflush(stdout);
  3527. }
  3528. // Internal helper for printing the list of failed tests.
  3529. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
  3530. const int failed_test_count = unit_test.failed_test_count();
  3531. if (failed_test_count == 0) {
  3532. return;
  3533. }
  3534. for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  3535. const TestCase& test_case = *unit_test.GetTestCase(i);
  3536. if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
  3537. continue;
  3538. }
  3539. for (int j = 0; j < test_case.total_test_count(); ++j) {
  3540. const TestInfo& test_info = *test_case.GetTestInfo(j);
  3541. if (!test_info.should_run() || test_info.result()->Passed()) {
  3542. continue;
  3543. }
  3544. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  3545. printf("%s.%s", test_case.name(), test_info.name());
  3546. PrintFullTestCommentIfPresent(test_info);
  3547. printf("\n");
  3548. }
  3549. }
  3550. }
  3551. void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  3552. int /*iteration*/) {
  3553. ColoredPrintf(COLOR_GREEN, "[==========] ");
  3554. printf("%s from %s ran.",
  3555. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  3556. FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  3557. if (GTEST_FLAG(print_time)) {
  3558. printf(" (%s ms total)",
  3559. internal::StreamableToString(unit_test.elapsed_time()).c_str());
  3560. }
  3561. printf("\n");
  3562. ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
  3563. printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  3564. int num_failures = unit_test.failed_test_count();
  3565. if (!unit_test.Passed()) {
  3566. const int failed_test_count = unit_test.failed_test_count();
  3567. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  3568. printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
  3569. PrintFailedTests(unit_test);
  3570. printf("\n%2d FAILED %s\n", num_failures,
  3571. num_failures == 1 ? "TEST" : "TESTS");
  3572. }
  3573. int num_disabled = unit_test.disabled_test_count();
  3574. if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
  3575. if (!num_failures) {
  3576. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
  3577. }
  3578. ColoredPrintf(COLOR_YELLOW,
  3579. " YOU HAVE %d DISABLED %s\n\n",
  3580. num_disabled,
  3581. num_disabled == 1 ? "TEST" : "TESTS");
  3582. }
  3583. // Ensure that Google Test output is printed before, e.g., heapchecker output.
  3584. fflush(stdout);
  3585. }
  3586. // End PrettyUnitTestResultPrinter
  3587. // class TestEventRepeater
  3588. //
  3589. // This class forwards events to other event listeners.
  3590. class TestEventRepeater : public TestEventListener {
  3591. public:
  3592. TestEventRepeater() : forwarding_enabled_(true) {}
  3593. virtual ~TestEventRepeater();
  3594. void Append(TestEventListener *listener);
  3595. TestEventListener* Release(TestEventListener* listener);
  3596. // Controls whether events will be forwarded to listeners_. Set to false
  3597. // in death test child processes.
  3598. bool forwarding_enabled() const { return forwarding_enabled_; }
  3599. void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
  3600. virtual void OnTestProgramStart(const UnitTest& unit_test);
  3601. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  3602. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  3603. virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
  3604. virtual void OnTestCaseStart(const TestCase& test_case);
  3605. virtual void OnTestStart(const TestInfo& test_info);
  3606. virtual void OnTestPartResult(const TestPartResult& result);
  3607. virtual void OnTestEnd(const TestInfo& test_info);
  3608. virtual void OnTestCaseEnd(const TestCase& test_case);
  3609. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  3610. virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
  3611. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3612. virtual void OnTestProgramEnd(const UnitTest& unit_test);
  3613. private:
  3614. // Controls whether events will be forwarded to listeners_. Set to false
  3615. // in death test child processes.
  3616. bool forwarding_enabled_;
  3617. // The list of listeners that receive events.
  3618. std::vector<TestEventListener*> listeners_;
  3619. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
  3620. };
  3621. TestEventRepeater::~TestEventRepeater() {
  3622. ForEach(listeners_, Delete<TestEventListener>);
  3623. }
  3624. void TestEventRepeater::Append(TestEventListener *listener) {
  3625. listeners_.push_back(listener);
  3626. }
  3627. // TODO([email protected]): Factor the search functionality into Vector::Find.
  3628. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
  3629. for (size_t i = 0; i < listeners_.size(); ++i) {
  3630. if (listeners_[i] == listener) {
  3631. listeners_.erase(listeners_.begin() + i);
  3632. return listener;
  3633. }
  3634. }
  3635. return NULL;
  3636. }
  3637. // Since most methods are very similar, use macros to reduce boilerplate.
  3638. // This defines a member that forwards the call to all listeners.
  3639. #define GTEST_REPEATER_METHOD_(Name, Type) \
  3640. void TestEventRepeater::Name(const Type& parameter) { \
  3641. if (forwarding_enabled_) { \
  3642. for (size_t i = 0; i < listeners_.size(); i++) { \
  3643. listeners_[i]->Name(parameter); \
  3644. } \
  3645. } \
  3646. }
  3647. // This defines a member that forwards the call to all listeners in reverse
  3648. // order.
  3649. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
  3650. void TestEventRepeater::Name(const Type& parameter) { \
  3651. if (forwarding_enabled_) { \
  3652. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
  3653. listeners_[i]->Name(parameter); \
  3654. } \
  3655. } \
  3656. }
  3657. GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
  3658. GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
  3659. GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
  3660. GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
  3661. GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
  3662. GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
  3663. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
  3664. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
  3665. GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
  3666. GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
  3667. GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
  3668. #undef GTEST_REPEATER_METHOD_
  3669. #undef GTEST_REVERSE_REPEATER_METHOD_
  3670. void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
  3671. int iteration) {
  3672. if (forwarding_enabled_) {
  3673. for (size_t i = 0; i < listeners_.size(); i++) {
  3674. listeners_[i]->OnTestIterationStart(unit_test, iteration);
  3675. }
  3676. }
  3677. }
  3678. void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
  3679. int iteration) {
  3680. if (forwarding_enabled_) {
  3681. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
  3682. listeners_[i]->OnTestIterationEnd(unit_test, iteration);
  3683. }
  3684. }
  3685. }
  3686. // End TestEventRepeater
  3687. // This class generates an XML output file.
  3688. class XmlUnitTestResultPrinter : public EmptyTestEventListener {
  3689. public:
  3690. explicit XmlUnitTestResultPrinter(const char* output_file);
  3691. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3692. private:
  3693. // Is c a whitespace character that is normalized to a space character
  3694. // when it appears in an XML attribute value?
  3695. static bool IsNormalizableWhitespace(char c) {
  3696. return c == 0x9 || c == 0xA || c == 0xD;
  3697. }
  3698. // May c appear in a well-formed XML document?
  3699. static bool IsValidXmlCharacter(char c) {
  3700. return IsNormalizableWhitespace(c) || c >= 0x20;
  3701. }
  3702. // Returns an XML-escaped copy of the input string str. If
  3703. // is_attribute is true, the text is meant to appear as an attribute
  3704. // value, and normalizable whitespace is preserved by replacing it
  3705. // with character references.
  3706. static String EscapeXml(const char* str, bool is_attribute);
  3707. // Returns the given string with all characters invalid in XML removed.
  3708. static string RemoveInvalidXmlCharacters(const string& str);
  3709. // Convenience wrapper around EscapeXml when str is an attribute value.
  3710. static String EscapeXmlAttribute(const char* str) {
  3711. return EscapeXml(str, true);
  3712. }
  3713. // Convenience wrapper around EscapeXml when str is not an attribute value.
  3714. static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
  3715. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  3716. static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
  3717. // Streams an XML representation of a TestInfo object.
  3718. static void OutputXmlTestInfo(::std::ostream* stream,
  3719. const char* test_case_name,
  3720. const TestInfo& test_info);
  3721. // Prints an XML representation of a TestCase object
  3722. static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
  3723. // Prints an XML summary of unit_test to output stream out.
  3724. static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
  3725. // Produces a string representing the test properties in a result as space
  3726. // delimited XML attributes based on the property key="value" pairs.
  3727. // When the String is not empty, it includes a space at the beginning,
  3728. // to delimit this attribute from prior attributes.
  3729. static String TestPropertiesAsXmlAttributes(const TestResult& result);
  3730. // The output file.
  3731. const String output_file_;
  3732. GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
  3733. };
  3734. // Creates a new XmlUnitTestResultPrinter.
  3735. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
  3736. : output_file_(output_file) {
  3737. if (output_file_.c_str() == NULL || output_file_.empty()) {
  3738. fprintf(stderr, "XML output file may not be null\n");
  3739. fflush(stderr);
  3740. exit(EXIT_FAILURE);
  3741. }
  3742. }
  3743. // Called after the unit test ends.
  3744. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  3745. int /*iteration*/) {
  3746. FILE* xmlout = NULL;
  3747. FilePath output_file(output_file_);
  3748. FilePath output_dir(output_file.RemoveFileName());
  3749. if (output_dir.CreateDirectoriesRecursively()) {
  3750. xmlout = posix::FOpen(output_file_.c_str(), "w");
  3751. }
  3752. if (xmlout == NULL) {
  3753. // TODO(wan): report the reason of the failure.
  3754. //
  3755. // We don't do it for now as:
  3756. //
  3757. // 1. There is no urgent need for it.
  3758. // 2. It's a bit involved to make the errno variable thread-safe on
  3759. // all three operating systems (Linux, Windows, and Mac OS).
  3760. // 3. To interpret the meaning of errno in a thread-safe way,
  3761. // we need the strerror_r() function, which is not available on
  3762. // Windows.
  3763. fprintf(stderr,
  3764. "Unable to open file \"%s\"\n",
  3765. output_file_.c_str());
  3766. fflush(stderr);
  3767. exit(EXIT_FAILURE);
  3768. }
  3769. PrintXmlUnitTest(xmlout, unit_test);
  3770. fclose(xmlout);
  3771. }
  3772. // Returns an XML-escaped copy of the input string str. If is_attribute
  3773. // is true, the text is meant to appear as an attribute value, and
  3774. // normalizable whitespace is preserved by replacing it with character
  3775. // references.
  3776. //
  3777. // Invalid XML characters in str, if any, are stripped from the output.
  3778. // It is expected that most, if not all, of the text processed by this
  3779. // module will consist of ordinary English text.
  3780. // If this module is ever modified to produce version 1.1 XML output,
  3781. // most invalid characters can be retained using character references.
  3782. // TODO(wan): It might be nice to have a minimally invasive, human-readable
  3783. // escaping scheme for invalid characters, rather than dropping them.
  3784. String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
  3785. Message m;
  3786. if (str != NULL) {
  3787. for (const char* src = str; *src; ++src) {
  3788. switch (*src) {
  3789. case '<':
  3790. m << "&lt;";
  3791. break;
  3792. case '>':
  3793. m << "&gt;";
  3794. break;
  3795. case '&':
  3796. m << "&amp;";
  3797. break;
  3798. case '\'':
  3799. if (is_attribute)
  3800. m << "&apos;";
  3801. else
  3802. m << '\'';
  3803. break;
  3804. case '"':
  3805. if (is_attribute)
  3806. m << "&quot;";
  3807. else
  3808. m << '"';
  3809. break;
  3810. default:
  3811. if (IsValidXmlCharacter(*src)) {
  3812. if (is_attribute && IsNormalizableWhitespace(*src))
  3813. m << String::Format("&#x%02X;", unsigned(*src));
  3814. else
  3815. m << *src;
  3816. }
  3817. break;
  3818. }
  3819. }
  3820. }
  3821. return m.GetString();
  3822. }
  3823. // Returns the given string with all characters invalid in XML removed.
  3824. // Currently invalid characters are dropped from the string. An
  3825. // alternative is to replace them with certain characters such as . or ?.
  3826. string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) {
  3827. string output;
  3828. output.reserve(str.size());
  3829. for (string::const_iterator it = str.begin(); it != str.end(); ++it)
  3830. if (IsValidXmlCharacter(*it))
  3831. output.push_back(*it);
  3832. return output;
  3833. }
  3834. // The following routines generate an XML representation of a UnitTest
  3835. // object.
  3836. //
  3837. // This is how Google Test concepts map to the DTD:
  3838. //
  3839. // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
  3840. // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
  3841. // <testcase name="test-name"> <-- corresponds to a TestInfo object
  3842. // <failure message="...">...</failure>
  3843. // <failure message="...">...</failure>
  3844. // <failure message="...">...</failure>
  3845. // <-- individual assertion failures
  3846. // </testcase>
  3847. // </testsuite>
  3848. // </testsuites>
  3849. // Formats the given time in milliseconds as seconds.
  3850. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
  3851. ::std::stringstream ss;
  3852. ss << ms/1000.0;
  3853. return ss.str();
  3854. }
  3855. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  3856. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
  3857. const char* data) {
  3858. const char* segment = data;
  3859. *stream << "<![CDATA[";
  3860. for (;;) {
  3861. const char* const next_segment = strstr(segment, "]]>");
  3862. if (next_segment != NULL) {
  3863. stream->write(
  3864. segment, static_cast<std::streamsize>(next_segment - segment));
  3865. *stream << "]]>]]&gt;<![CDATA[";
  3866. segment = next_segment + strlen("]]>");
  3867. } else {
  3868. *stream << segment;
  3869. break;
  3870. }
  3871. }
  3872. *stream << "]]>";
  3873. }
  3874. // Prints an XML representation of a TestInfo object.
  3875. // TODO(wan): There is also value in printing properties with the plain printer.
  3876. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
  3877. const char* test_case_name,
  3878. const TestInfo& test_info) {
  3879. const TestResult& result = *test_info.result();
  3880. *stream << " <testcase name=\""
  3881. << EscapeXmlAttribute(test_info.name()).c_str() << "\"";
  3882. if (test_info.value_param() != NULL) {
  3883. *stream << " value_param=\"" << EscapeXmlAttribute(test_info.value_param())
  3884. << "\"";
  3885. }
  3886. if (test_info.type_param() != NULL) {
  3887. *stream << " type_param=\"" << EscapeXmlAttribute(test_info.type_param())
  3888. << "\"";
  3889. }
  3890. *stream << " status=\""
  3891. << (test_info.should_run() ? "run" : "notrun")
  3892. << "\" time=\""
  3893. << FormatTimeInMillisAsSeconds(result.elapsed_time())
  3894. << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
  3895. << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
  3896. int failures = 0;
  3897. for (int i = 0; i < result.total_part_count(); ++i) {
  3898. const TestPartResult& part = result.GetTestPartResult(i);
  3899. if (part.failed()) {
  3900. if (++failures == 1)
  3901. *stream << ">\n";
  3902. *stream << " <failure message=\""
  3903. << EscapeXmlAttribute(part.summary()).c_str()
  3904. << "\" type=\"\">";
  3905. const string location = internal::FormatCompilerIndependentFileLocation(
  3906. part.file_name(), part.line_number());
  3907. const string message = location + "\n" + part.message();
  3908. OutputXmlCDataSection(stream,
  3909. RemoveInvalidXmlCharacters(message).c_str());
  3910. *stream << "</failure>\n";
  3911. }
  3912. }
  3913. if (failures == 0)
  3914. *stream << " />\n";
  3915. else
  3916. *stream << " </testcase>\n";
  3917. }
  3918. // Prints an XML representation of a TestCase object
  3919. void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
  3920. const TestCase& test_case) {
  3921. fprintf(out,
  3922. " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
  3923. "disabled=\"%d\" ",
  3924. EscapeXmlAttribute(test_case.name()).c_str(),
  3925. test_case.total_test_count(),
  3926. test_case.failed_test_count(),
  3927. test_case.disabled_test_count());
  3928. fprintf(out,
  3929. "errors=\"0\" time=\"%s\">\n",
  3930. FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
  3931. for (int i = 0; i < test_case.total_test_count(); ++i) {
  3932. ::std::stringstream stream;
  3933. OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
  3934. fprintf(out, "%s", StringStreamToString(&stream).c_str());
  3935. }
  3936. fprintf(out, " </testsuite>\n");
  3937. }
  3938. // Prints an XML summary of unit_test to output stream out.
  3939. void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
  3940. const UnitTest& unit_test) {
  3941. fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  3942. fprintf(out,
  3943. "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
  3944. "errors=\"0\" time=\"%s\" ",
  3945. unit_test.total_test_count(),
  3946. unit_test.failed_test_count(),
  3947. unit_test.disabled_test_count(),
  3948. FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
  3949. if (GTEST_FLAG(shuffle)) {
  3950. fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
  3951. }
  3952. fprintf(out, "name=\"AllTests\">\n");
  3953. for (int i = 0; i < unit_test.total_test_case_count(); ++i)
  3954. PrintXmlTestCase(out, *unit_test.GetTestCase(i));
  3955. fprintf(out, "</testsuites>\n");
  3956. }
  3957. // Produces a string representing the test properties in a result as space
  3958. // delimited XML attributes based on the property key="value" pairs.
  3959. String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
  3960. const TestResult& result) {
  3961. Message attributes;
  3962. for (int i = 0; i < result.test_property_count(); ++i) {
  3963. const TestProperty& property = result.GetTestProperty(i);
  3964. attributes << " " << property.key() << "="
  3965. << "\"" << EscapeXmlAttribute(property.value()) << "\"";
  3966. }
  3967. return attributes.GetString();
  3968. }
  3969. // End XmlUnitTestResultPrinter
  3970. #if GTEST_CAN_STREAM_RESULTS_
  3971. // Streams test results to the given port on the given host machine.
  3972. class StreamingListener : public EmptyTestEventListener {
  3973. public:
  3974. // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
  3975. static string UrlEncode(const char* str);
  3976. StreamingListener(const string& host, const string& port)
  3977. : sockfd_(-1), host_name_(host), port_num_(port) {
  3978. MakeConnection();
  3979. Send("gtest_streaming_protocol_version=1.0\n");
  3980. }
  3981. virtual ~StreamingListener() {
  3982. if (sockfd_ != -1)
  3983. CloseConnection();
  3984. }
  3985. void OnTestProgramStart(const UnitTest& /* unit_test */) {
  3986. Send("event=TestProgramStart\n");
  3987. }
  3988. void OnTestProgramEnd(const UnitTest& unit_test) {
  3989. // Note that Google Test current only report elapsed time for each
  3990. // test iteration, not for the entire test program.
  3991. Send(String::Format("event=TestProgramEnd&passed=%d\n",
  3992. unit_test.Passed()));
  3993. // Notify the streaming server to stop.
  3994. CloseConnection();
  3995. }
  3996. void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
  3997. Send(String::Format("event=TestIterationStart&iteration=%d\n",
  3998. iteration));
  3999. }
  4000. void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
  4001. Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n",
  4002. unit_test.Passed(),
  4003. StreamableToString(unit_test.elapsed_time()).c_str()));
  4004. }
  4005. void OnTestCaseStart(const TestCase& test_case) {
  4006. Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name()));
  4007. }
  4008. void OnTestCaseEnd(const TestCase& test_case) {
  4009. Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n",
  4010. test_case.Passed(),
  4011. StreamableToString(test_case.elapsed_time()).c_str()));
  4012. }
  4013. void OnTestStart(const TestInfo& test_info) {
  4014. Send(String::Format("event=TestStart&name=%s\n", test_info.name()));
  4015. }
  4016. void OnTestEnd(const TestInfo& test_info) {
  4017. Send(String::Format(
  4018. "event=TestEnd&passed=%d&elapsed_time=%sms\n",
  4019. (test_info.result())->Passed(),
  4020. StreamableToString((test_info.result())->elapsed_time()).c_str()));
  4021. }
  4022. void OnTestPartResult(const TestPartResult& test_part_result) {
  4023. const char* file_name = test_part_result.file_name();
  4024. if (file_name == NULL)
  4025. file_name = "";
  4026. Send(String::Format("event=TestPartResult&file=%s&line=%d&message=",
  4027. UrlEncode(file_name).c_str(),
  4028. test_part_result.line_number()));
  4029. Send(UrlEncode(test_part_result.message()) + "\n");
  4030. }
  4031. private:
  4032. // Creates a client socket and connects to the server.
  4033. void MakeConnection();
  4034. // Closes the socket.
  4035. void CloseConnection() {
  4036. GTEST_CHECK_(sockfd_ != -1)
  4037. << "CloseConnection() can be called only when there is a connection.";
  4038. close(sockfd_);
  4039. sockfd_ = -1;
  4040. }
  4041. // Sends a string to the socket.
  4042. void Send(const string& message) {
  4043. GTEST_CHECK_(sockfd_ != -1)
  4044. << "Send() can be called only when there is a connection.";
  4045. const int len = static_cast<int>(message.length());
  4046. if (write(sockfd_, message.c_str(), len) != len) {
  4047. GTEST_LOG_(WARNING)
  4048. << "stream_result_to: failed to stream to "
  4049. << host_name_ << ":" << port_num_;
  4050. }
  4051. }
  4052. int sockfd_; // socket file descriptor
  4053. const string host_name_;
  4054. const string port_num_;
  4055. GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
  4056. }; // class StreamingListener
  4057. // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
  4058. // replaces them by "%xx" where xx is their hexadecimal value. For
  4059. // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
  4060. // in both time and space -- important as the input str may contain an
  4061. // arbitrarily long test failure message and stack trace.
  4062. string StreamingListener::UrlEncode(const char* str) {
  4063. string result;
  4064. result.reserve(strlen(str) + 1);
  4065. for (char ch = *str; ch != '\0'; ch = *++str) {
  4066. switch (ch) {
  4067. case '%':
  4068. case '=':
  4069. case '&':
  4070. case '\n':
  4071. result.append(String::Format("%%%02x", static_cast<unsigned char>(ch)));
  4072. break;
  4073. default:
  4074. result.push_back(ch);
  4075. break;
  4076. }
  4077. }
  4078. return result;
  4079. }
  4080. void StreamingListener::MakeConnection() {
  4081. GTEST_CHECK_(sockfd_ == -1)
  4082. << "MakeConnection() can't be called when there is already a connection.";
  4083. addrinfo hints;
  4084. memset(&hints, 0, sizeof(hints));
  4085. hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
  4086. hints.ai_socktype = SOCK_STREAM;
  4087. addrinfo* servinfo = NULL;
  4088. // Use the getaddrinfo() to get a linked list of IP addresses for
  4089. // the given host name.
  4090. const int error_num = getaddrinfo(
  4091. host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
  4092. if (error_num != 0) {
  4093. GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
  4094. << gai_strerror(error_num);
  4095. }
  4096. // Loop through all the results and connect to the first we can.
  4097. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
  4098. cur_addr = cur_addr->ai_next) {
  4099. sockfd_ = socket(
  4100. cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
  4101. if (sockfd_ != -1) {
  4102. // Connect the client socket to the server socket.
  4103. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
  4104. close(sockfd_);
  4105. sockfd_ = -1;
  4106. }
  4107. }
  4108. }
  4109. freeaddrinfo(servinfo); // all done with this structure
  4110. if (sockfd_ == -1) {
  4111. GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
  4112. << host_name_ << ":" << port_num_;
  4113. }
  4114. }
  4115. // End of class Streaming Listener
  4116. #endif // GTEST_CAN_STREAM_RESULTS__
  4117. // Class ScopedTrace
  4118. // Pushes the given source file location and message onto a per-thread
  4119. // trace stack maintained by Google Test.
  4120. // L < UnitTest::mutex_
  4121. ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
  4122. TraceInfo trace;
  4123. trace.file = file;
  4124. trace.line = line;
  4125. trace.message = message.GetString();
  4126. UnitTest::GetInstance()->PushGTestTrace(trace);
  4127. }
  4128. // Pops the info pushed by the c'tor.
  4129. // L < UnitTest::mutex_
  4130. ScopedTrace::~ScopedTrace() {
  4131. UnitTest::GetInstance()->PopGTestTrace();
  4132. }
  4133. // class OsStackTraceGetter
  4134. // Returns the current OS stack trace as a String. Parameters:
  4135. //
  4136. // max_depth - the maximum number of stack frames to be included
  4137. // in the trace.
  4138. // skip_count - the number of top frames to be skipped; doesn't count
  4139. // against max_depth.
  4140. //
  4141. // L < mutex_
  4142. // We use "L < mutex_" to denote that the function may acquire mutex_.
  4143. String OsStackTraceGetter::CurrentStackTrace(int, int) {
  4144. return String("");
  4145. }
  4146. // L < mutex_
  4147. void OsStackTraceGetter::UponLeavingGTest() {
  4148. }
  4149. const char* const
  4150. OsStackTraceGetter::kElidedFramesMarker =
  4151. "... " GTEST_NAME_ " internal frames ...";
  4152. } // namespace internal
  4153. // class TestEventListeners
  4154. TestEventListeners::TestEventListeners()
  4155. : repeater_(new internal::TestEventRepeater()),
  4156. default_result_printer_(NULL),
  4157. default_xml_generator_(NULL) {
  4158. }
  4159. TestEventListeners::~TestEventListeners() { delete repeater_; }
  4160. // Returns the standard listener responsible for the default console
  4161. // output. Can be removed from the listeners list to shut down default
  4162. // console output. Note that removing this object from the listener list
  4163. // with Release transfers its ownership to the user.
  4164. void TestEventListeners::Append(TestEventListener* listener) {
  4165. repeater_->Append(listener);
  4166. }
  4167. // Removes the given event listener from the list and returns it. It then
  4168. // becomes the caller's responsibility to delete the listener. Returns
  4169. // NULL if the listener is not found in the list.
  4170. TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
  4171. if (listener == default_result_printer_)
  4172. default_result_printer_ = NULL;
  4173. else if (listener == default_xml_generator_)
  4174. default_xml_generator_ = NULL;
  4175. return repeater_->Release(listener);
  4176. }
  4177. // Returns repeater that broadcasts the TestEventListener events to all
  4178. // subscribers.
  4179. TestEventListener* TestEventListeners::repeater() { return repeater_; }
  4180. // Sets the default_result_printer attribute to the provided listener.
  4181. // The listener is also added to the listener list and previous
  4182. // default_result_printer is removed from it and deleted. The listener can
  4183. // also be NULL in which case it will not be added to the list. Does
  4184. // nothing if the previous and the current listener objects are the same.
  4185. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
  4186. if (default_result_printer_ != listener) {
  4187. // It is an error to pass this method a listener that is already in the
  4188. // list.
  4189. delete Release(default_result_printer_);
  4190. default_result_printer_ = listener;
  4191. if (listener != NULL)
  4192. Append(listener);
  4193. }
  4194. }
  4195. // Sets the default_xml_generator attribute to the provided listener. The
  4196. // listener is also added to the listener list and previous
  4197. // default_xml_generator is removed from it and deleted. The listener can
  4198. // also be NULL in which case it will not be added to the list. Does
  4199. // nothing if the previous and the current listener objects are the same.
  4200. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
  4201. if (default_xml_generator_ != listener) {
  4202. // It is an error to pass this method a listener that is already in the
  4203. // list.
  4204. delete Release(default_xml_generator_);
  4205. default_xml_generator_ = listener;
  4206. if (listener != NULL)
  4207. Append(listener);
  4208. }
  4209. }
  4210. // Controls whether events will be forwarded by the repeater to the
  4211. // listeners in the list.
  4212. bool TestEventListeners::EventForwardingEnabled() const {
  4213. return repeater_->forwarding_enabled();
  4214. }
  4215. void TestEventListeners::SuppressEventForwarding() {
  4216. repeater_->set_forwarding_enabled(false);
  4217. }
  4218. // class UnitTest
  4219. // Gets the singleton UnitTest object. The first time this method is
  4220. // called, a UnitTest object is constructed and returned. Consecutive
  4221. // calls will return the same object.
  4222. //
  4223. // We don't protect this under mutex_ as a user is not supposed to
  4224. // call this before main() starts, from which point on the return
  4225. // value will never change.
  4226. UnitTest * UnitTest::GetInstance() {
  4227. // When compiled with MSVC 7.1 in optimized mode, destroying the
  4228. // UnitTest object upon exiting the program messes up the exit code,
  4229. // causing successful tests to appear failed. We have to use a
  4230. // different implementation in this case to bypass the compiler bug.
  4231. // This implementation makes the compiler happy, at the cost of
  4232. // leaking the UnitTest object.
  4233. // CodeGear C++Builder insists on a public destructor for the
  4234. // default implementation. Use this implementation to keep good OO
  4235. // design with private destructor.
  4236. #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  4237. static UnitTest* const instance = new UnitTest;
  4238. return instance;
  4239. #else
  4240. static UnitTest instance;
  4241. return &instance;
  4242. #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  4243. }
  4244. // Gets the number of successful test cases.
  4245. int UnitTest::successful_test_case_count() const {
  4246. return impl()->successful_test_case_count();
  4247. }
  4248. // Gets the number of failed test cases.
  4249. int UnitTest::failed_test_case_count() const {
  4250. return impl()->failed_test_case_count();
  4251. }
  4252. // Gets the number of all test cases.
  4253. int UnitTest::total_test_case_count() const {
  4254. return impl()->total_test_case_count();
  4255. }
  4256. // Gets the number of all test cases that contain at least one test
  4257. // that should run.
  4258. int UnitTest::test_case_to_run_count() const {
  4259. return impl()->test_case_to_run_count();
  4260. }
  4261. // Gets the number of successful tests.
  4262. int UnitTest::successful_test_count() const {
  4263. return impl()->successful_test_count();
  4264. }
  4265. // Gets the number of failed tests.
  4266. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
  4267. // Gets the number of disabled tests.
  4268. int UnitTest::disabled_test_count() const {
  4269. return impl()->disabled_test_count();
  4270. }
  4271. // Gets the number of all tests.
  4272. int UnitTest::total_test_count() const { return impl()->total_test_count(); }
  4273. // Gets the number of tests that should run.
  4274. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
  4275. // Gets the elapsed time, in milliseconds.
  4276. internal::TimeInMillis UnitTest::elapsed_time() const {
  4277. return impl()->elapsed_time();
  4278. }
  4279. // Returns true iff the unit test passed (i.e. all test cases passed).
  4280. bool UnitTest::Passed() const { return impl()->Passed(); }
  4281. // Returns true iff the unit test failed (i.e. some test case failed
  4282. // or something outside of all tests failed).
  4283. bool UnitTest::Failed() const { return impl()->Failed(); }
  4284. // Gets the i-th test case among all the test cases. i can range from 0 to
  4285. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  4286. const TestCase* UnitTest::GetTestCase(int i) const {
  4287. return impl()->GetTestCase(i);
  4288. }
  4289. // Gets the i-th test case among all the test cases. i can range from 0 to
  4290. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  4291. TestCase* UnitTest::GetMutableTestCase(int i) {
  4292. return impl()->GetMutableTestCase(i);
  4293. }
  4294. // Returns the list of event listeners that can be used to track events
  4295. // inside Google Test.
  4296. TestEventListeners& UnitTest::listeners() {
  4297. return *impl()->listeners();
  4298. }
  4299. // Registers and returns a global test environment. When a test
  4300. // program is run, all global test environments will be set-up in the
  4301. // order they were registered. After all tests in the program have
  4302. // finished, all global test environments will be torn-down in the
  4303. // *reverse* order they were registered.
  4304. //
  4305. // The UnitTest object takes ownership of the given environment.
  4306. //
  4307. // We don't protect this under mutex_, as we only support calling it
  4308. // from the main thread.
  4309. Environment* UnitTest::AddEnvironment(Environment* env) {
  4310. if (env == NULL) {
  4311. return NULL;
  4312. }
  4313. impl_->environments().push_back(env);
  4314. return env;
  4315. }
  4316. // Adds a TestPartResult to the current TestResult object. All Google Test
  4317. // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
  4318. // this to report their results. The user code should use the
  4319. // assertion macros instead of calling this directly.
  4320. // L < mutex_
  4321. void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
  4322. const char* file_name,
  4323. int line_number,
  4324. const internal::String& message,
  4325. const internal::String& os_stack_trace) {
  4326. Message msg;
  4327. msg << message;
  4328. internal::MutexLock lock(&mutex_);
  4329. if (impl_->gtest_trace_stack().size() > 0) {
  4330. msg << "\n" << GTEST_NAME_ << " trace:";
  4331. for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
  4332. i > 0; --i) {
  4333. const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
  4334. msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
  4335. << " " << trace.message;
  4336. }
  4337. }
  4338. if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
  4339. msg << internal::kStackTraceMarker << os_stack_trace;
  4340. }
  4341. const TestPartResult result =
  4342. TestPartResult(result_type, file_name, line_number,
  4343. msg.GetString().c_str());
  4344. impl_->GetTestPartResultReporterForCurrentThread()->
  4345. ReportTestPartResult(result);
  4346. if (result_type != TestPartResult::kSuccess) {
  4347. // gtest_break_on_failure takes precedence over
  4348. // gtest_throw_on_failure. This allows a user to set the latter
  4349. // in the code (perhaps in order to use Google Test assertions
  4350. // with another testing framework) and specify the former on the
  4351. // command line for debugging.
  4352. if (GTEST_FLAG(break_on_failure)) {
  4353. #if GTEST_OS_WINDOWS
  4354. // Using DebugBreak on Windows allows gtest to still break into a debugger
  4355. // when a failure happens and both the --gtest_break_on_failure and
  4356. // the --gtest_catch_exceptions flags are specified.
  4357. DebugBreak();
  4358. #else
  4359. // Dereference NULL through a volatile pointer to prevent the compiler
  4360. // from removing. We use this rather than abort() or __builtin_trap() for
  4361. // portability: Symbian doesn't implement abort() well, and some debuggers
  4362. // don't correctly trap abort().
  4363. *static_cast<volatile int*>(NULL) = 1;
  4364. #endif // GTEST_OS_WINDOWS
  4365. } else if (GTEST_FLAG(throw_on_failure)) {
  4366. #if GTEST_HAS_EXCEPTIONS
  4367. throw GoogleTestFailureException(result);
  4368. #else
  4369. // We cannot call abort() as it generates a pop-up in debug mode
  4370. // that cannot be suppressed in VC 7.1 or below.
  4371. exit(1);
  4372. #endif
  4373. }
  4374. }
  4375. }
  4376. // Creates and adds a property to the current TestResult. If a property matching
  4377. // the supplied value already exists, updates its value instead.
  4378. void UnitTest::RecordPropertyForCurrentTest(const char* key,
  4379. const char* value) {
  4380. const TestProperty test_property(key, value);
  4381. impl_->current_test_result()->RecordProperty(test_property);
  4382. }
  4383. // Runs all tests in this UnitTest object and prints the result.
  4384. // Returns 0 if successful, or 1 otherwise.
  4385. //
  4386. // We don't protect this under mutex_, as we only support calling it
  4387. // from the main thread.
  4388. int UnitTest::Run() {
  4389. // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
  4390. // used for the duration of the program.
  4391. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
  4392. #if GTEST_HAS_SEH
  4393. const bool in_death_test_child_process =
  4394. internal::GTEST_FLAG(internal_run_death_test).length() > 0;
  4395. // Either the user wants Google Test to catch exceptions thrown by the
  4396. // tests or this is executing in the context of death test child
  4397. // process. In either case the user does not want to see pop-up dialogs
  4398. // about crashes - they are expected.
  4399. if (impl()->catch_exceptions() || in_death_test_child_process) {
  4400. # if !GTEST_OS_WINDOWS_MOBILE
  4401. // SetErrorMode doesn't exist on CE.
  4402. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
  4403. SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
  4404. # endif // !GTEST_OS_WINDOWS_MOBILE
  4405. # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
  4406. // Death test children can be terminated with _abort(). On Windows,
  4407. // _abort() can show a dialog with a warning message. This forces the
  4408. // abort message to go to stderr instead.
  4409. _set_error_mode(_OUT_TO_STDERR);
  4410. # endif
  4411. # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
  4412. // In the debug version, Visual Studio pops up a separate dialog
  4413. // offering a choice to debug the aborted program. We need to suppress
  4414. // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
  4415. // executed. Google Test will notify the user of any unexpected
  4416. // failure via stderr.
  4417. //
  4418. // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
  4419. // Users of prior VC versions shall suffer the agony and pain of
  4420. // clicking through the countless debug dialogs.
  4421. // TODO([email protected]): find a way to suppress the abort dialog() in the
  4422. // debug mode when compiled with VC 7.1 or lower.
  4423. if (!GTEST_FLAG(break_on_failure))
  4424. _set_abort_behavior(
  4425. 0x0, // Clear the following flags:
  4426. _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
  4427. # endif
  4428. }
  4429. #endif // GTEST_HAS_SEH
  4430. return internal::HandleExceptionsInMethodIfSupported(
  4431. impl(),
  4432. &internal::UnitTestImpl::RunAllTests,
  4433. "auxiliary test code (environments or event listeners)") ? 0 : 1;
  4434. }
  4435. // Returns the working directory when the first TEST() or TEST_F() was
  4436. // executed.
  4437. const char* UnitTest::original_working_dir() const {
  4438. return impl_->original_working_dir_.c_str();
  4439. }
  4440. // Returns the TestCase object for the test that's currently running,
  4441. // or NULL if no test is running.
  4442. // L < mutex_
  4443. const TestCase* UnitTest::current_test_case() const {
  4444. internal::MutexLock lock(&mutex_);
  4445. return impl_->current_test_case();
  4446. }
  4447. // Returns the TestInfo object for the test that's currently running,
  4448. // or NULL if no test is running.
  4449. // L < mutex_
  4450. const TestInfo* UnitTest::current_test_info() const {
  4451. internal::MutexLock lock(&mutex_);
  4452. return impl_->current_test_info();
  4453. }
  4454. // Returns the random seed used at the start of the current test run.
  4455. int UnitTest::random_seed() const { return impl_->random_seed(); }
  4456. #if GTEST_HAS_PARAM_TEST
  4457. // Returns ParameterizedTestCaseRegistry object used to keep track of
  4458. // value-parameterized tests and instantiate and register them.
  4459. // L < mutex_
  4460. internal::ParameterizedTestCaseRegistry&
  4461. UnitTest::parameterized_test_registry() {
  4462. return impl_->parameterized_test_registry();
  4463. }
  4464. #endif // GTEST_HAS_PARAM_TEST
  4465. // Creates an empty UnitTest.
  4466. UnitTest::UnitTest() {
  4467. impl_ = new internal::UnitTestImpl(this);
  4468. }
  4469. // Destructor of UnitTest.
  4470. UnitTest::~UnitTest() {
  4471. delete impl_;
  4472. }
  4473. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  4474. // Google Test trace stack.
  4475. // L < mutex_
  4476. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
  4477. internal::MutexLock lock(&mutex_);
  4478. impl_->gtest_trace_stack().push_back(trace);
  4479. }
  4480. // Pops a trace from the per-thread Google Test trace stack.
  4481. // L < mutex_
  4482. void UnitTest::PopGTestTrace() {
  4483. internal::MutexLock lock(&mutex_);
  4484. impl_->gtest_trace_stack().pop_back();
  4485. }
  4486. namespace internal {
  4487. UnitTestImpl::UnitTestImpl(UnitTest* parent)
  4488. : parent_(parent),
  4489. #ifdef _MSC_VER
  4490. # pragma warning(push) // Saves the current warning state.
  4491. # pragma warning(disable:4355) // Temporarily disables warning 4355
  4492. // (using this in initializer).
  4493. default_global_test_part_result_reporter_(this),
  4494. default_per_thread_test_part_result_reporter_(this),
  4495. # pragma warning(pop) // Restores the warning state again.
  4496. #else
  4497. default_global_test_part_result_reporter_(this),
  4498. default_per_thread_test_part_result_reporter_(this),
  4499. #endif // _MSC_VER
  4500. global_test_part_result_repoter_(
  4501. &default_global_test_part_result_reporter_),
  4502. per_thread_test_part_result_reporter_(
  4503. &default_per_thread_test_part_result_reporter_),
  4504. #if GTEST_HAS_PARAM_TEST
  4505. parameterized_test_registry_(),
  4506. parameterized_tests_registered_(false),
  4507. #endif // GTEST_HAS_PARAM_TEST
  4508. last_death_test_case_(-1),
  4509. current_test_case_(NULL),
  4510. current_test_info_(NULL),
  4511. ad_hoc_test_result_(),
  4512. os_stack_trace_getter_(NULL),
  4513. post_flag_parse_init_performed_(false),
  4514. random_seed_(0), // Will be overridden by the flag before first use.
  4515. random_(0), // Will be reseeded before first use.
  4516. elapsed_time_(0),
  4517. #if GTEST_HAS_DEATH_TEST
  4518. internal_run_death_test_flag_(NULL),
  4519. death_test_factory_(new DefaultDeathTestFactory),
  4520. #endif
  4521. // Will be overridden by the flag before first use.
  4522. catch_exceptions_(false) {
  4523. listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
  4524. }
  4525. UnitTestImpl::~UnitTestImpl() {
  4526. // Deletes every TestCase.
  4527. ForEach(test_cases_, internal::Delete<TestCase>);
  4528. // Deletes every Environment.
  4529. ForEach(environments_, internal::Delete<Environment>);
  4530. delete os_stack_trace_getter_;
  4531. }
  4532. #if GTEST_HAS_DEATH_TEST
  4533. // Disables event forwarding if the control is currently in a death test
  4534. // subprocess. Must not be called before InitGoogleTest.
  4535. void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
  4536. if (internal_run_death_test_flag_.get() != NULL)
  4537. listeners()->SuppressEventForwarding();
  4538. }
  4539. #endif // GTEST_HAS_DEATH_TEST
  4540. // Initializes event listeners performing XML output as specified by
  4541. // UnitTestOptions. Must not be called before InitGoogleTest.
  4542. void UnitTestImpl::ConfigureXmlOutput() {
  4543. const String& output_format = UnitTestOptions::GetOutputFormat();
  4544. if (output_format == "xml") {
  4545. listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
  4546. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  4547. } else if (output_format != "") {
  4548. printf("WARNING: unrecognized output format \"%s\" ignored.\n",
  4549. output_format.c_str());
  4550. fflush(stdout);
  4551. }
  4552. }
  4553. #if GTEST_CAN_STREAM_RESULTS_
  4554. // Initializes event listeners for streaming test results in String form.
  4555. // Must not be called before InitGoogleTest.
  4556. void UnitTestImpl::ConfigureStreamingOutput() {
  4557. const string& target = GTEST_FLAG(stream_result_to);
  4558. if (!target.empty()) {
  4559. const size_t pos = target.find(':');
  4560. if (pos != string::npos) {
  4561. listeners()->Append(new StreamingListener(target.substr(0, pos),
  4562. target.substr(pos+1)));
  4563. } else {
  4564. printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
  4565. target.c_str());
  4566. fflush(stdout);
  4567. }
  4568. }
  4569. }
  4570. #endif // GTEST_CAN_STREAM_RESULTS_
  4571. // Performs initialization dependent upon flag values obtained in
  4572. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  4573. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  4574. // this function is also called from RunAllTests. Since this function can be
  4575. // called more than once, it has to be idempotent.
  4576. void UnitTestImpl::PostFlagParsingInit() {
  4577. // Ensures that this function does not execute more than once.
  4578. if (!post_flag_parse_init_performed_) {
  4579. post_flag_parse_init_performed_ = true;
  4580. #if GTEST_HAS_DEATH_TEST
  4581. InitDeathTestSubprocessControlInfo();
  4582. SuppressTestEventsIfInSubprocess();
  4583. #endif // GTEST_HAS_DEATH_TEST
  4584. // Registers parameterized tests. This makes parameterized tests
  4585. // available to the UnitTest reflection API without running
  4586. // RUN_ALL_TESTS.
  4587. RegisterParameterizedTests();
  4588. // Configures listeners for XML output. This makes it possible for users
  4589. // to shut down the default XML output before invoking RUN_ALL_TESTS.
  4590. ConfigureXmlOutput();
  4591. #if GTEST_CAN_STREAM_RESULTS_
  4592. // Configures listeners for streaming test results to the specified server.
  4593. ConfigureStreamingOutput();
  4594. #endif // GTEST_CAN_STREAM_RESULTS_
  4595. }
  4596. }
  4597. // A predicate that checks the name of a TestCase against a known
  4598. // value.
  4599. //
  4600. // This is used for implementation of the UnitTest class only. We put
  4601. // it in the anonymous namespace to prevent polluting the outer
  4602. // namespace.
  4603. //
  4604. // TestCaseNameIs is copyable.
  4605. class TestCaseNameIs {
  4606. public:
  4607. // Constructor.
  4608. explicit TestCaseNameIs(const String& name)
  4609. : name_(name) {}
  4610. // Returns true iff the name of test_case matches name_.
  4611. bool operator()(const TestCase* test_case) const {
  4612. return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
  4613. }
  4614. private:
  4615. String name_;
  4616. };
  4617. // Finds and returns a TestCase with the given name. If one doesn't
  4618. // exist, creates one and returns it. It's the CALLER'S
  4619. // RESPONSIBILITY to ensure that this function is only called WHEN THE
  4620. // TESTS ARE NOT SHUFFLED.
  4621. //
  4622. // Arguments:
  4623. //
  4624. // test_case_name: name of the test case
  4625. // type_param: the name of the test case's type parameter, or NULL if
  4626. // this is not a typed or a type-parameterized test case.
  4627. // set_up_tc: pointer to the function that sets up the test case
  4628. // tear_down_tc: pointer to the function that tears down the test case
  4629. TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
  4630. const char* type_param,
  4631. Test::SetUpTestCaseFunc set_up_tc,
  4632. Test::TearDownTestCaseFunc tear_down_tc) {
  4633. // Can we find a TestCase with the given name?
  4634. const std::vector<TestCase*>::const_iterator test_case =
  4635. std::find_if(test_cases_.begin(), test_cases_.end(),
  4636. TestCaseNameIs(test_case_name));
  4637. if (test_case != test_cases_.end())
  4638. return *test_case;
  4639. // No. Let's create one.
  4640. TestCase* const new_test_case =
  4641. new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
  4642. // Is this a death test case?
  4643. if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
  4644. kDeathTestCaseFilter)) {
  4645. // Yes. Inserts the test case after the last death test case
  4646. // defined so far. This only works when the test cases haven't
  4647. // been shuffled. Otherwise we may end up running a death test
  4648. // after a non-death test.
  4649. ++last_death_test_case_;
  4650. test_cases_.insert(test_cases_.begin() + last_death_test_case_,
  4651. new_test_case);
  4652. } else {
  4653. // No. Appends to the end of the list.
  4654. test_cases_.push_back(new_test_case);
  4655. }
  4656. test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
  4657. return new_test_case;
  4658. }
  4659. // Helpers for setting up / tearing down the given environment. They
  4660. // are for use in the ForEach() function.
  4661. static void SetUpEnvironment(Environment* env) { env->SetUp(); }
  4662. static void TearDownEnvironment(Environment* env) { env->TearDown(); }
  4663. // Runs all tests in this UnitTest object, prints the result, and
  4664. // returns true if all tests are successful. If any exception is
  4665. // thrown during a test, the test is considered to be failed, but the
  4666. // rest of the tests will still be run.
  4667. //
  4668. // When parameterized tests are enabled, it expands and registers
  4669. // parameterized tests first in RegisterParameterizedTests().
  4670. // All other functions called from RunAllTests() may safely assume that
  4671. // parameterized tests are ready to be counted and run.
  4672. bool UnitTestImpl::RunAllTests() {
  4673. // Makes sure InitGoogleTest() was called.
  4674. if (!GTestIsInitialized()) {
  4675. printf("%s",
  4676. "\nThis test program did NOT call ::testing::InitGoogleTest "
  4677. "before calling RUN_ALL_TESTS(). Please fix it.\n");
  4678. return false;
  4679. }
  4680. // Do not run any test if the --help flag was specified.
  4681. if (g_help_flag)
  4682. return true;
  4683. // Repeats the call to the post-flag parsing initialization in case the
  4684. // user didn't call InitGoogleTest.
  4685. PostFlagParsingInit();
  4686. // Even if sharding is not on, test runners may want to use the
  4687. // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
  4688. // protocol.
  4689. internal::WriteToShardStatusFileIfNeeded();
  4690. // True iff we are in a subprocess for running a thread-safe-style
  4691. // death test.
  4692. bool in_subprocess_for_death_test = false;
  4693. #if GTEST_HAS_DEATH_TEST
  4694. in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
  4695. #endif // GTEST_HAS_DEATH_TEST
  4696. const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
  4697. in_subprocess_for_death_test);
  4698. // Compares the full test names with the filter to decide which
  4699. // tests to run.
  4700. const bool has_tests_to_run = FilterTests(should_shard
  4701. ? HONOR_SHARDING_PROTOCOL
  4702. : IGNORE_SHARDING_PROTOCOL) > 0;
  4703. // Lists the tests and exits if the --gtest_list_tests flag was specified.
  4704. if (GTEST_FLAG(list_tests)) {
  4705. // This must be called *after* FilterTests() has been called.
  4706. ListTestsMatchingFilter();
  4707. return true;
  4708. }
  4709. random_seed_ = GTEST_FLAG(shuffle) ?
  4710. GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
  4711. // True iff at least one test has failed.
  4712. bool failed = false;
  4713. TestEventListener* repeater = listeners()->repeater();
  4714. repeater->OnTestProgramStart(*parent_);
  4715. // How many times to repeat the tests? We don't want to repeat them
  4716. // when we are inside the subprocess of a death test.
  4717. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
  4718. // Repeats forever if the repeat count is negative.
  4719. const bool forever = repeat < 0;
  4720. for (int i = 0; forever || i != repeat; i++) {
  4721. // We want to preserve failures generated by ad-hoc test
  4722. // assertions executed before RUN_ALL_TESTS().
  4723. ClearNonAdHocTestResult();
  4724. const TimeInMillis start = GetTimeInMillis();
  4725. // Shuffles test cases and tests if requested.
  4726. if (has_tests_to_run && GTEST_FLAG(shuffle)) {
  4727. random()->Reseed(random_seed_);
  4728. // This should be done before calling OnTestIterationStart(),
  4729. // such that a test event listener can see the actual test order
  4730. // in the event.
  4731. ShuffleTests();
  4732. }
  4733. // Tells the unit test event listeners that the tests are about to start.
  4734. repeater->OnTestIterationStart(*parent_, i);
  4735. // Runs each test case if there is at least one test to run.
  4736. if (has_tests_to_run) {
  4737. // Sets up all environments beforehand.
  4738. repeater->OnEnvironmentsSetUpStart(*parent_);
  4739. ForEach(environments_, SetUpEnvironment);
  4740. repeater->OnEnvironmentsSetUpEnd(*parent_);
  4741. // Runs the tests only if there was no fatal failure during global
  4742. // set-up.
  4743. if (!Test::HasFatalFailure()) {
  4744. for (int test_index = 0; test_index < total_test_case_count();
  4745. test_index++) {
  4746. GetMutableTestCase(test_index)->Run();
  4747. }
  4748. }
  4749. // Tears down all environments in reverse order afterwards.
  4750. repeater->OnEnvironmentsTearDownStart(*parent_);
  4751. std::for_each(environments_.rbegin(), environments_.rend(),
  4752. TearDownEnvironment);
  4753. repeater->OnEnvironmentsTearDownEnd(*parent_);
  4754. }
  4755. elapsed_time_ = GetTimeInMillis() - start;
  4756. // Tells the unit test event listener that the tests have just finished.
  4757. repeater->OnTestIterationEnd(*parent_, i);
  4758. // Gets the result and clears it.
  4759. if (!Passed()) {
  4760. failed = true;
  4761. }
  4762. // Restores the original test order after the iteration. This
  4763. // allows the user to quickly repro a failure that happens in the
  4764. // N-th iteration without repeating the first (N - 1) iterations.
  4765. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
  4766. // case the user somehow changes the value of the flag somewhere
  4767. // (it's always safe to unshuffle the tests).
  4768. UnshuffleTests();
  4769. if (GTEST_FLAG(shuffle)) {
  4770. // Picks a new random seed for each iteration.
  4771. random_seed_ = GetNextRandomSeed(random_seed_);
  4772. }
  4773. }
  4774. repeater->OnTestProgramEnd(*parent_);
  4775. return !failed;
  4776. }
  4777. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  4778. // if the variable is present. If a file already exists at this location, this
  4779. // function will write over it. If the variable is present, but the file cannot
  4780. // be created, prints an error and exits.
  4781. void WriteToShardStatusFileIfNeeded() {
  4782. const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
  4783. if (test_shard_file != NULL) {
  4784. FILE* const file = posix::FOpen(test_shard_file, "w");
  4785. if (file == NULL) {
  4786. ColoredPrintf(COLOR_RED,
  4787. "Could not write to the test shard status file \"%s\" "
  4788. "specified by the %s environment variable.\n",
  4789. test_shard_file, kTestShardStatusFile);
  4790. fflush(stdout);
  4791. exit(EXIT_FAILURE);
  4792. }
  4793. fclose(file);
  4794. }
  4795. }
  4796. // Checks whether sharding is enabled by examining the relevant
  4797. // environment variable values. If the variables are present,
  4798. // but inconsistent (i.e., shard_index >= total_shards), prints
  4799. // an error and exits. If in_subprocess_for_death_test, sharding is
  4800. // disabled because it must only be applied to the original test
  4801. // process. Otherwise, we could filter out death tests we intended to execute.
  4802. bool ShouldShard(const char* total_shards_env,
  4803. const char* shard_index_env,
  4804. bool in_subprocess_for_death_test) {
  4805. if (in_subprocess_for_death_test) {
  4806. return false;
  4807. }
  4808. const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
  4809. const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
  4810. if (total_shards == -1 && shard_index == -1) {
  4811. return false;
  4812. } else if (total_shards == -1 && shard_index != -1) {
  4813. const Message msg = Message()
  4814. << "Invalid environment variables: you have "
  4815. << kTestShardIndex << " = " << shard_index
  4816. << ", but have left " << kTestTotalShards << " unset.\n";
  4817. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  4818. fflush(stdout);
  4819. exit(EXIT_FAILURE);
  4820. } else if (total_shards != -1 && shard_index == -1) {
  4821. const Message msg = Message()
  4822. << "Invalid environment variables: you have "
  4823. << kTestTotalShards << " = " << total_shards
  4824. << ", but have left " << kTestShardIndex << " unset.\n";
  4825. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  4826. fflush(stdout);
  4827. exit(EXIT_FAILURE);
  4828. } else if (shard_index < 0 || shard_index >= total_shards) {
  4829. const Message msg = Message()
  4830. << "Invalid environment variables: we require 0 <= "
  4831. << kTestShardIndex << " < " << kTestTotalShards
  4832. << ", but you have " << kTestShardIndex << "=" << shard_index
  4833. << ", " << kTestTotalShards << "=" << total_shards << ".\n";
  4834. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  4835. fflush(stdout);
  4836. exit(EXIT_FAILURE);
  4837. }
  4838. return total_shards > 1;
  4839. }
  4840. // Parses the environment variable var as an Int32. If it is unset,
  4841. // returns default_val. If it is not an Int32, prints an error
  4842. // and aborts.
  4843. Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
  4844. const char* str_val = posix::GetEnv(var);
  4845. if (str_val == NULL) {
  4846. return default_val;
  4847. }
  4848. Int32 result;
  4849. if (!ParseInt32(Message() << "The value of environment variable " << var,
  4850. str_val, &result)) {
  4851. exit(EXIT_FAILURE);
  4852. }
  4853. return result;
  4854. }
  4855. // Given the total number of shards, the shard index, and the test id,
  4856. // returns true iff the test should be run on this shard. The test id is
  4857. // some arbitrary but unique non-negative integer assigned to each test
  4858. // method. Assumes that 0 <= shard_index < total_shards.
  4859. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
  4860. return (test_id % total_shards) == shard_index;
  4861. }
  4862. // Compares the name of each test with the user-specified filter to
  4863. // decide whether the test should be run, then records the result in
  4864. // each TestCase and TestInfo object.
  4865. // If shard_tests == true, further filters tests based on sharding
  4866. // variables in the environment - see
  4867. // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
  4868. // Returns the number of tests that should run.
  4869. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
  4870. const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
  4871. Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
  4872. const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
  4873. Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
  4874. // num_runnable_tests are the number of tests that will
  4875. // run across all shards (i.e., match filter and are not disabled).
  4876. // num_selected_tests are the number of tests to be run on
  4877. // this shard.
  4878. int num_runnable_tests = 0;
  4879. int num_selected_tests = 0;
  4880. for (size_t i = 0; i < test_cases_.size(); i++) {
  4881. TestCase* const test_case = test_cases_[i];
  4882. const String &test_case_name = test_case->name();
  4883. test_case->set_should_run(false);
  4884. for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  4885. TestInfo* const test_info = test_case->test_info_list()[j];
  4886. const String test_name(test_info->name());
  4887. // A test is disabled if test case name or test name matches
  4888. // kDisableTestFilter.
  4889. const bool is_disabled =
  4890. internal::UnitTestOptions::MatchesFilter(test_case_name,
  4891. kDisableTestFilter) ||
  4892. internal::UnitTestOptions::MatchesFilter(test_name,
  4893. kDisableTestFilter);
  4894. test_info->is_disabled_ = is_disabled;
  4895. const bool matches_filter =
  4896. internal::UnitTestOptions::FilterMatchesTest(test_case_name,
  4897. test_name);
  4898. test_info->matches_filter_ = matches_filter;
  4899. const bool is_runnable =
  4900. (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
  4901. matches_filter;
  4902. const bool is_selected = is_runnable &&
  4903. (shard_tests == IGNORE_SHARDING_PROTOCOL ||
  4904. ShouldRunTestOnShard(total_shards, shard_index,
  4905. num_runnable_tests));
  4906. num_runnable_tests += is_runnable;
  4907. num_selected_tests += is_selected;
  4908. test_info->should_run_ = is_selected;
  4909. test_case->set_should_run(test_case->should_run() || is_selected);
  4910. }
  4911. }
  4912. return num_selected_tests;
  4913. }
  4914. // Prints the names of the tests matching the user-specified filter flag.
  4915. void UnitTestImpl::ListTestsMatchingFilter() {
  4916. for (size_t i = 0; i < test_cases_.size(); i++) {
  4917. const TestCase* const test_case = test_cases_[i];
  4918. bool printed_test_case_name = false;
  4919. for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  4920. const TestInfo* const test_info =
  4921. test_case->test_info_list()[j];
  4922. if (test_info->matches_filter_) {
  4923. if (!printed_test_case_name) {
  4924. printed_test_case_name = true;
  4925. printf("%s.\n", test_case->name());
  4926. }
  4927. printf(" %s\n", test_info->name());
  4928. }
  4929. }
  4930. }
  4931. fflush(stdout);
  4932. }
  4933. // Sets the OS stack trace getter.
  4934. //
  4935. // Does nothing if the input and the current OS stack trace getter are
  4936. // the same; otherwise, deletes the old getter and makes the input the
  4937. // current getter.
  4938. void UnitTestImpl::set_os_stack_trace_getter(
  4939. OsStackTraceGetterInterface* getter) {
  4940. if (os_stack_trace_getter_ != getter) {
  4941. delete os_stack_trace_getter_;
  4942. os_stack_trace_getter_ = getter;
  4943. }
  4944. }
  4945. // Returns the current OS stack trace getter if it is not NULL;
  4946. // otherwise, creates an OsStackTraceGetter, makes it the current
  4947. // getter, and returns it.
  4948. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
  4949. if (os_stack_trace_getter_ == NULL) {
  4950. os_stack_trace_getter_ = new OsStackTraceGetter;
  4951. }
  4952. return os_stack_trace_getter_;
  4953. }
  4954. // Returns the TestResult for the test that's currently running, or
  4955. // the TestResult for the ad hoc test if no test is running.
  4956. TestResult* UnitTestImpl::current_test_result() {
  4957. return current_test_info_ ?
  4958. &(current_test_info_->result_) : &ad_hoc_test_result_;
  4959. }
  4960. // Shuffles all test cases, and the tests within each test case,
  4961. // making sure that death tests are still run first.
  4962. void UnitTestImpl::ShuffleTests() {
  4963. // Shuffles the death test cases.
  4964. ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
  4965. // Shuffles the non-death test cases.
  4966. ShuffleRange(random(), last_death_test_case_ + 1,
  4967. static_cast<int>(test_cases_.size()), &test_case_indices_);
  4968. // Shuffles the tests inside each test case.
  4969. for (size_t i = 0; i < test_cases_.size(); i++) {
  4970. test_cases_[i]->ShuffleTests(random());
  4971. }
  4972. }
  4973. // Restores the test cases and tests to their order before the first shuffle.
  4974. void UnitTestImpl::UnshuffleTests() {
  4975. for (size_t i = 0; i < test_cases_.size(); i++) {
  4976. // Unshuffles the tests in each test case.
  4977. test_cases_[i]->UnshuffleTests();
  4978. // Resets the index of each test case.
  4979. test_case_indices_[i] = static_cast<int>(i);
  4980. }
  4981. }
  4982. // Returns the current OS stack trace as a String.
  4983. //
  4984. // The maximum number of stack frames to be included is specified by
  4985. // the gtest_stack_trace_depth flag. The skip_count parameter
  4986. // specifies the number of top frames to be skipped, which doesn't
  4987. // count against the number of frames to be included.
  4988. //
  4989. // For example, if Foo() calls Bar(), which in turn calls
  4990. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  4991. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  4992. String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
  4993. int skip_count) {
  4994. // We pass skip_count + 1 to skip this wrapper function in addition
  4995. // to what the user really wants to skip.
  4996. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
  4997. }
  4998. // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
  4999. // suppress unreachable code warnings.
  5000. namespace {
  5001. class ClassUniqueToAlwaysTrue {};
  5002. }
  5003. bool IsTrue(bool condition) { return condition; }
  5004. bool AlwaysTrue() {
  5005. #if GTEST_HAS_EXCEPTIONS
  5006. // This condition is always false so AlwaysTrue() never actually throws,
  5007. // but it makes the compiler think that it may throw.
  5008. if (IsTrue(false))
  5009. throw ClassUniqueToAlwaysTrue();
  5010. #endif // GTEST_HAS_EXCEPTIONS
  5011. return true;
  5012. }
  5013. // If *pstr starts with the given prefix, modifies *pstr to be right
  5014. // past the prefix and returns true; otherwise leaves *pstr unchanged
  5015. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  5016. bool SkipPrefix(const char* prefix, const char** pstr) {
  5017. const size_t prefix_len = strlen(prefix);
  5018. if (strncmp(*pstr, prefix, prefix_len) == 0) {
  5019. *pstr += prefix_len;
  5020. return true;
  5021. }
  5022. return false;
  5023. }
  5024. // Parses a string as a command line flag. The string should have
  5025. // the format "--flag=value". When def_optional is true, the "=value"
  5026. // part can be omitted.
  5027. //
  5028. // Returns the value of the flag, or NULL if the parsing failed.
  5029. const char* ParseFlagValue(const char* str,
  5030. const char* flag,
  5031. bool def_optional) {
  5032. // str and flag must not be NULL.
  5033. if (str == NULL || flag == NULL) return NULL;
  5034. // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
  5035. const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
  5036. const size_t flag_len = flag_str.length();
  5037. if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
  5038. // Skips the flag name.
  5039. const char* flag_end = str + flag_len;
  5040. // When def_optional is true, it's OK to not have a "=value" part.
  5041. if (def_optional && (flag_end[0] == '\0')) {
  5042. return flag_end;
  5043. }
  5044. // If def_optional is true and there are more characters after the
  5045. // flag name, or if def_optional is false, there must be a '=' after
  5046. // the flag name.
  5047. if (flag_end[0] != '=') return NULL;
  5048. // Returns the string after "=".
  5049. return flag_end + 1;
  5050. }
  5051. // Parses a string for a bool flag, in the form of either
  5052. // "--flag=value" or "--flag".
  5053. //
  5054. // In the former case, the value is taken as true as long as it does
  5055. // not start with '0', 'f', or 'F'.
  5056. //
  5057. // In the latter case, the value is taken as true.
  5058. //
  5059. // On success, stores the value of the flag in *value, and returns
  5060. // true. On failure, returns false without changing *value.
  5061. bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
  5062. // Gets the value of the flag as a string.
  5063. const char* const value_str = ParseFlagValue(str, flag, true);
  5064. // Aborts if the parsing failed.
  5065. if (value_str == NULL) return false;
  5066. // Converts the string value to a bool.
  5067. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  5068. return true;
  5069. }
  5070. // Parses a string for an Int32 flag, in the form of
  5071. // "--flag=value".
  5072. //
  5073. // On success, stores the value of the flag in *value, and returns
  5074. // true. On failure, returns false without changing *value.
  5075. bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
  5076. // Gets the value of the flag as a string.
  5077. const char* const value_str = ParseFlagValue(str, flag, false);
  5078. // Aborts if the parsing failed.
  5079. if (value_str == NULL) return false;
  5080. // Sets *value to the value of the flag.
  5081. return ParseInt32(Message() << "The value of flag --" << flag,
  5082. value_str, value);
  5083. }
  5084. // Parses a string for a string flag, in the form of
  5085. // "--flag=value".
  5086. //
  5087. // On success, stores the value of the flag in *value, and returns
  5088. // true. On failure, returns false without changing *value.
  5089. bool ParseStringFlag(const char* str, const char* flag, String* value) {
  5090. // Gets the value of the flag as a string.
  5091. const char* const value_str = ParseFlagValue(str, flag, false);
  5092. // Aborts if the parsing failed.
  5093. if (value_str == NULL) return false;
  5094. // Sets *value to the value of the flag.
  5095. *value = value_str;
  5096. return true;
  5097. }
  5098. // Determines whether a string has a prefix that Google Test uses for its
  5099. // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
  5100. // If Google Test detects that a command line flag has its prefix but is not
  5101. // recognized, it will print its help message. Flags starting with
  5102. // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
  5103. // internal flags and do not trigger the help message.
  5104. static bool HasGoogleTestFlagPrefix(const char* str) {
  5105. return (SkipPrefix("--", &str) ||
  5106. SkipPrefix("-", &str) ||
  5107. SkipPrefix("/", &str)) &&
  5108. !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
  5109. (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
  5110. SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
  5111. }
  5112. // Prints a string containing code-encoded text. The following escape
  5113. // sequences can be used in the string to control the text color:
  5114. //
  5115. // @@ prints a single '@' character.
  5116. // @R changes the color to red.
  5117. // @G changes the color to green.
  5118. // @Y changes the color to yellow.
  5119. // @D changes to the default terminal text color.
  5120. //
  5121. // TODO([email protected]): Write tests for this once we add stdout
  5122. // capturing to Google Test.
  5123. static void PrintColorEncoded(const char* str) {
  5124. GTestColor color = COLOR_DEFAULT; // The current color.
  5125. // Conceptually, we split the string into segments divided by escape
  5126. // sequences. Then we print one segment at a time. At the end of
  5127. // each iteration, the str pointer advances to the beginning of the
  5128. // next segment.
  5129. for (;;) {
  5130. const char* p = strchr(str, '@');
  5131. if (p == NULL) {
  5132. ColoredPrintf(color, "%s", str);
  5133. return;
  5134. }
  5135. ColoredPrintf(color, "%s", String(str, p - str).c_str());
  5136. const char ch = p[1];
  5137. str = p + 2;
  5138. if (ch == '@') {
  5139. ColoredPrintf(color, "@");
  5140. } else if (ch == 'D') {
  5141. color = COLOR_DEFAULT;
  5142. } else if (ch == 'R') {
  5143. color = COLOR_RED;
  5144. } else if (ch == 'G') {
  5145. color = COLOR_GREEN;
  5146. } else if (ch == 'Y') {
  5147. color = COLOR_YELLOW;
  5148. } else {
  5149. --str;
  5150. }
  5151. }
  5152. }
  5153. static const char kColorEncodedHelpMessage[] =
  5154. "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
  5155. "following command line flags to control its behavior:\n"
  5156. "\n"
  5157. "Test Selection:\n"
  5158. " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
  5159. " List the names of all tests instead of running them. The name of\n"
  5160. " TEST(Foo, Bar) is \"Foo.Bar\".\n"
  5161. " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
  5162. "[@G-@YNEGATIVE_PATTERNS]@D\n"
  5163. " Run only the tests whose name matches one of the positive patterns but\n"
  5164. " none of the negative patterns. '?' matches any single character; '*'\n"
  5165. " matches any substring; ':' separates two patterns.\n"
  5166. " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
  5167. " Run all disabled tests too.\n"
  5168. "\n"
  5169. "Test Execution:\n"
  5170. " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
  5171. " Run the tests repeatedly; use a negative count to repeat forever.\n"
  5172. " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
  5173. " Randomize tests' orders on every iteration.\n"
  5174. " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
  5175. " Random number seed to use for shuffling test orders (between 1 and\n"
  5176. " 99999, or 0 to use a seed based on the current time).\n"
  5177. "\n"
  5178. "Test Output:\n"
  5179. " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
  5180. " Enable/disable colored output. The default is @Gauto@D.\n"
  5181. " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
  5182. " Don't print the elapsed time of each test.\n"
  5183. " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
  5184. GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
  5185. " Generate an XML report in the given directory or with the given file\n"
  5186. " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
  5187. #if GTEST_CAN_STREAM_RESULTS_
  5188. " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
  5189. " Stream test results to the given server.\n"
  5190. #endif // GTEST_CAN_STREAM_RESULTS_
  5191. "\n"
  5192. "Assertion Behavior:\n"
  5193. #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  5194. " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
  5195. " Set the default death test style.\n"
  5196. #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  5197. " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
  5198. " Turn assertion failures into debugger break-points.\n"
  5199. " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
  5200. " Turn assertion failures into C++ exceptions.\n"
  5201. " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
  5202. " Do not report exceptions as test failures. Instead, allow them\n"
  5203. " to crash the program or throw a pop-up (on Windows).\n"
  5204. "\n"
  5205. "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
  5206. "the corresponding\n"
  5207. "environment variable of a flag (all letters in upper-case). For example, to\n"
  5208. "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
  5209. "color=no@D or set\n"
  5210. "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
  5211. "\n"
  5212. "For more information, please read the " GTEST_NAME_ " documentation at\n"
  5213. "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
  5214. "(not one in your own code or tests), please report it to\n"
  5215. "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
  5216. // Parses the command line for Google Test flags, without initializing
  5217. // other parts of Google Test. The type parameter CharType can be
  5218. // instantiated to either char or wchar_t.
  5219. template <typename CharType>
  5220. void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
  5221. for (int i = 1; i < *argc; i++) {
  5222. const String arg_string = StreamableToString(argv[i]);
  5223. const char* const arg = arg_string.c_str();
  5224. using internal::ParseBoolFlag;
  5225. using internal::ParseInt32Flag;
  5226. using internal::ParseStringFlag;
  5227. // Do we see a Google Test flag?
  5228. if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
  5229. &GTEST_FLAG(also_run_disabled_tests)) ||
  5230. ParseBoolFlag(arg, kBreakOnFailureFlag,
  5231. &GTEST_FLAG(break_on_failure)) ||
  5232. ParseBoolFlag(arg, kCatchExceptionsFlag,
  5233. &GTEST_FLAG(catch_exceptions)) ||
  5234. ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
  5235. ParseStringFlag(arg, kDeathTestStyleFlag,
  5236. &GTEST_FLAG(death_test_style)) ||
  5237. ParseBoolFlag(arg, kDeathTestUseFork,
  5238. &GTEST_FLAG(death_test_use_fork)) ||
  5239. ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
  5240. ParseStringFlag(arg, kInternalRunDeathTestFlag,
  5241. &GTEST_FLAG(internal_run_death_test)) ||
  5242. ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
  5243. ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
  5244. ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
  5245. ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
  5246. ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
  5247. ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
  5248. ParseInt32Flag(arg, kStackTraceDepthFlag,
  5249. &GTEST_FLAG(stack_trace_depth)) ||
  5250. ParseStringFlag(arg, kStreamResultToFlag,
  5251. &GTEST_FLAG(stream_result_to)) ||
  5252. ParseBoolFlag(arg, kThrowOnFailureFlag,
  5253. &GTEST_FLAG(throw_on_failure))
  5254. ) {
  5255. // Yes. Shift the remainder of the argv list left by one. Note
  5256. // that argv has (*argc + 1) elements, the last one always being
  5257. // NULL. The following loop moves the trailing NULL element as
  5258. // well.
  5259. for (int j = i; j != *argc; j++) {
  5260. argv[j] = argv[j + 1];
  5261. }
  5262. // Decrements the argument count.
  5263. (*argc)--;
  5264. // We also need to decrement the iterator as we just removed
  5265. // an element.
  5266. i--;
  5267. } else if (arg_string == "--help" || arg_string == "-h" ||
  5268. arg_string == "-?" || arg_string == "/?" ||
  5269. HasGoogleTestFlagPrefix(arg)) {
  5270. // Both help flag and unrecognized Google Test flags (excluding
  5271. // internal ones) trigger help display.
  5272. g_help_flag = true;
  5273. }
  5274. }
  5275. if (g_help_flag) {
  5276. // We print the help here instead of in RUN_ALL_TESTS(), as the
  5277. // latter may not be called at all if the user is using Google
  5278. // Test with another testing framework.
  5279. PrintColorEncoded(kColorEncodedHelpMessage);
  5280. }
  5281. }
  5282. // Parses the command line for Google Test flags, without initializing
  5283. // other parts of Google Test.
  5284. void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
  5285. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  5286. }
  5287. void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
  5288. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  5289. }
  5290. // The internal implementation of InitGoogleTest().
  5291. //
  5292. // The type parameter CharType can be instantiated to either char or
  5293. // wchar_t.
  5294. template <typename CharType>
  5295. void InitGoogleTestImpl(int* argc, CharType** argv) {
  5296. g_init_gtest_count++;
  5297. // We don't want to run the initialization code twice.
  5298. if (g_init_gtest_count != 1) return;
  5299. if (*argc <= 0) return;
  5300. internal::g_executable_path = internal::StreamableToString(argv[0]);
  5301. #if GTEST_HAS_DEATH_TEST
  5302. g_argvs.clear();
  5303. for (int i = 0; i != *argc; i++) {
  5304. g_argvs.push_back(StreamableToString(argv[i]));
  5305. }
  5306. #endif // GTEST_HAS_DEATH_TEST
  5307. ParseGoogleTestFlagsOnly(argc, argv);
  5308. GetUnitTestImpl()->PostFlagParsingInit();
  5309. }
  5310. } // namespace internal
  5311. // Initializes Google Test. This must be called before calling
  5312. // RUN_ALL_TESTS(). In particular, it parses a command line for the
  5313. // flags that Google Test recognizes. Whenever a Google Test flag is
  5314. // seen, it is removed from argv, and *argc is decremented.
  5315. //
  5316. // No value is returned. Instead, the Google Test flag variables are
  5317. // updated.
  5318. //
  5319. // Calling the function for the second time has no user-visible effect.
  5320. void InitGoogleTest(int* argc, char** argv) {
  5321. internal::InitGoogleTestImpl(argc, argv);
  5322. }
  5323. // This overloaded version can be used in Windows programs compiled in
  5324. // UNICODE mode.
  5325. void InitGoogleTest(int* argc, wchar_t** argv) {
  5326. internal::InitGoogleTestImpl(argc, argv);
  5327. }
  5328. } // namespace testing
  5329. // Copyright 2005, Google Inc.
  5330. // All rights reserved.
  5331. //
  5332. // Redistribution and use in source and binary forms, with or without
  5333. // modification, are permitted provided that the following conditions are
  5334. // met:
  5335. //
  5336. // * Redistributions of source code must retain the above copyright
  5337. // notice, this list of conditions and the following disclaimer.
  5338. // * Redistributions in binary form must reproduce the above
  5339. // copyright notice, this list of conditions and the following disclaimer
  5340. // in the documentation and/or other materials provided with the
  5341. // distribution.
  5342. // * Neither the name of Google Inc. nor the names of its
  5343. // contributors may be used to endorse or promote products derived from
  5344. // this software without specific prior written permission.
  5345. //
  5346. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  5347. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5348. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  5349. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  5350. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  5351. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5352. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  5353. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  5354. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  5355. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  5356. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5357. //
  5358. // Author: [email protected] (Zhanyong Wan), [email protected] (Vlad Losev)
  5359. //
  5360. // This file implements death tests.
  5361. #if GTEST_HAS_DEATH_TEST
  5362. # if GTEST_OS_MAC
  5363. # include <crt_externs.h>
  5364. # endif // GTEST_OS_MAC
  5365. # include <errno.h>
  5366. # include <fcntl.h>
  5367. # include <limits.h>
  5368. # include <stdarg.h>
  5369. # if GTEST_OS_WINDOWS
  5370. # include <windows.h>
  5371. # else
  5372. # include <sys/mman.h>
  5373. # include <sys/wait.h>
  5374. # endif // GTEST_OS_WINDOWS
  5375. #endif // GTEST_HAS_DEATH_TEST
  5376. // Indicates that this translation unit is part of Google Test's
  5377. // implementation. It must come before gtest-internal-inl.h is
  5378. // included, or there will be a compiler error. This trick is to
  5379. // prevent a user from accidentally including gtest-internal-inl.h in
  5380. // his code.
  5381. #define GTEST_IMPLEMENTATION_ 1
  5382. #undef GTEST_IMPLEMENTATION_
  5383. namespace testing {
  5384. // Constants.
  5385. // The default death test style.
  5386. static const char kDefaultDeathTestStyle[] = "fast";
  5387. GTEST_DEFINE_string_(
  5388. death_test_style,
  5389. internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
  5390. "Indicates how to run a death test in a forked child process: "
  5391. "\"threadsafe\" (child process re-executes the test binary "
  5392. "from the beginning, running only the specific death test) or "
  5393. "\"fast\" (child process runs the death test immediately "
  5394. "after forking).");
  5395. GTEST_DEFINE_bool_(
  5396. death_test_use_fork,
  5397. internal::BoolFromGTestEnv("death_test_use_fork", false),
  5398. "Instructs to use fork()/_exit() instead of clone() in death tests. "
  5399. "Ignored and always uses fork() on POSIX systems where clone() is not "
  5400. "implemented. Useful when running under valgrind or similar tools if "
  5401. "those do not support clone(). Valgrind 3.3.1 will just fail if "
  5402. "it sees an unsupported combination of clone() flags. "
  5403. "It is not recommended to use this flag w/o valgrind though it will "
  5404. "work in 99% of the cases. Once valgrind is fixed, this flag will "
  5405. "most likely be removed.");
  5406. namespace internal {
  5407. GTEST_DEFINE_string_(
  5408. internal_run_death_test, "",
  5409. "Indicates the file, line number, temporal index of "
  5410. "the single death test to run, and a file descriptor to "
  5411. "which a success code may be sent, all separated by "
  5412. "colons. This flag is specified if and only if the current "
  5413. "process is a sub-process launched for running a thread-safe "
  5414. "death test. FOR INTERNAL USE ONLY.");
  5415. } // namespace internal
  5416. #if GTEST_HAS_DEATH_TEST
  5417. // ExitedWithCode constructor.
  5418. ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
  5419. }
  5420. // ExitedWithCode function-call operator.
  5421. bool ExitedWithCode::operator()(int exit_status) const {
  5422. # if GTEST_OS_WINDOWS
  5423. return exit_status == exit_code_;
  5424. # else
  5425. return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
  5426. # endif // GTEST_OS_WINDOWS
  5427. }
  5428. # if !GTEST_OS_WINDOWS
  5429. // KilledBySignal constructor.
  5430. KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
  5431. }
  5432. // KilledBySignal function-call operator.
  5433. bool KilledBySignal::operator()(int exit_status) const {
  5434. return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
  5435. }
  5436. # endif // !GTEST_OS_WINDOWS
  5437. namespace internal {
  5438. // Utilities needed for death tests.
  5439. // Generates a textual description of a given exit code, in the format
  5440. // specified by wait(2).
  5441. static String ExitSummary(int exit_code) {
  5442. Message m;
  5443. # if GTEST_OS_WINDOWS
  5444. m << "Exited with exit status " << exit_code;
  5445. # else
  5446. if (WIFEXITED(exit_code)) {
  5447. m << "Exited with exit status " << WEXITSTATUS(exit_code);
  5448. } else if (WIFSIGNALED(exit_code)) {
  5449. m << "Terminated by signal " << WTERMSIG(exit_code);
  5450. }
  5451. # ifdef WCOREDUMP
  5452. if (WCOREDUMP(exit_code)) {
  5453. m << " (core dumped)";
  5454. }
  5455. # endif
  5456. # endif // GTEST_OS_WINDOWS
  5457. return m.GetString();
  5458. }
  5459. // Returns true if exit_status describes a process that was terminated
  5460. // by a signal, or exited normally with a nonzero exit code.
  5461. bool ExitedUnsuccessfully(int exit_status) {
  5462. return !ExitedWithCode(0)(exit_status);
  5463. }
  5464. # if !GTEST_OS_WINDOWS
  5465. // Generates a textual failure message when a death test finds more than
  5466. // one thread running, or cannot determine the number of threads, prior
  5467. // to executing the given statement. It is the responsibility of the
  5468. // caller not to pass a thread_count of 1.
  5469. static String DeathTestThreadWarning(size_t thread_count) {
  5470. Message msg;
  5471. msg << "Death tests use fork(), which is unsafe particularly"
  5472. << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
  5473. if (thread_count == 0)
  5474. msg << "couldn't detect the number of threads.";
  5475. else
  5476. msg << "detected " << thread_count << " threads.";
  5477. return msg.GetString();
  5478. }
  5479. # endif // !GTEST_OS_WINDOWS
  5480. // Flag characters for reporting a death test that did not die.
  5481. static const char kDeathTestLived = 'L';
  5482. static const char kDeathTestReturned = 'R';
  5483. static const char kDeathTestThrew = 'T';
  5484. static const char kDeathTestInternalError = 'I';
  5485. // An enumeration describing all of the possible ways that a death test can
  5486. // conclude. DIED means that the process died while executing the test
  5487. // code; LIVED means that process lived beyond the end of the test code;
  5488. // RETURNED means that the test statement attempted to execute a return
  5489. // statement, which is not allowed; THREW means that the test statement
  5490. // returned control by throwing an exception. IN_PROGRESS means the test
  5491. // has not yet concluded.
  5492. // TODO([email protected]): Unify names and possibly values for
  5493. // AbortReason, DeathTestOutcome, and flag characters above.
  5494. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
  5495. // Routine for aborting the program which is safe to call from an
  5496. // exec-style death test child process, in which case the error
  5497. // message is propagated back to the parent process. Otherwise, the
  5498. // message is simply printed to stderr. In either case, the program
  5499. // then exits with status 1.
  5500. void DeathTestAbort(const String& message) {
  5501. // On a POSIX system, this function may be called from a threadsafe-style
  5502. // death test child process, which operates on a very small stack. Use
  5503. // the heap for any additional non-minuscule memory requirements.
  5504. const InternalRunDeathTestFlag* const flag =
  5505. GetUnitTestImpl()->internal_run_death_test_flag();
  5506. if (flag != NULL) {
  5507. FILE* parent = posix::FDOpen(flag->write_fd(), "w");
  5508. fputc(kDeathTestInternalError, parent);
  5509. fprintf(parent, "%s", message.c_str());
  5510. fflush(parent);
  5511. _exit(1);
  5512. } else {
  5513. fprintf(stderr, "%s", message.c_str());
  5514. fflush(stderr);
  5515. posix::Abort();
  5516. }
  5517. }
  5518. // A replacement for CHECK that calls DeathTestAbort if the assertion
  5519. // fails.
  5520. # define GTEST_DEATH_TEST_CHECK_(expression) \
  5521. do { \
  5522. if (!::testing::internal::IsTrue(expression)) { \
  5523. DeathTestAbort(::testing::internal::String::Format( \
  5524. "CHECK failed: File %s, line %d: %s", \
  5525. __FILE__, __LINE__, #expression)); \
  5526. } \
  5527. } while (::testing::internal::AlwaysFalse())
  5528. // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
  5529. // evaluating any system call that fulfills two conditions: it must return
  5530. // -1 on failure, and set errno to EINTR when it is interrupted and
  5531. // should be tried again. The macro expands to a loop that repeatedly
  5532. // evaluates the expression as long as it evaluates to -1 and sets
  5533. // errno to EINTR. If the expression evaluates to -1 but errno is
  5534. // something other than EINTR, DeathTestAbort is called.
  5535. # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
  5536. do { \
  5537. int gtest_retval; \
  5538. do { \
  5539. gtest_retval = (expression); \
  5540. } while (gtest_retval == -1 && errno == EINTR); \
  5541. if (gtest_retval == -1) { \
  5542. DeathTestAbort(::testing::internal::String::Format( \
  5543. "CHECK failed: File %s, line %d: %s != -1", \
  5544. __FILE__, __LINE__, #expression)); \
  5545. } \
  5546. } while (::testing::internal::AlwaysFalse())
  5547. // Returns the message describing the last system error in errno.
  5548. String GetLastErrnoDescription() {
  5549. return String(errno == 0 ? "" : posix::StrError(errno));
  5550. }
  5551. // This is called from a death test parent process to read a failure
  5552. // message from the death test child process and log it with the FATAL
  5553. // severity. On Windows, the message is read from a pipe handle. On other
  5554. // platforms, it is read from a file descriptor.
  5555. static void FailFromInternalError(int fd) {
  5556. Message error;
  5557. char buffer[256];
  5558. int num_read;
  5559. do {
  5560. while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
  5561. buffer[num_read] = '\0';
  5562. error << buffer;
  5563. }
  5564. } while (num_read == -1 && errno == EINTR);
  5565. if (num_read == 0) {
  5566. GTEST_LOG_(FATAL) << error.GetString();
  5567. } else {
  5568. const int last_error = errno;
  5569. GTEST_LOG_(FATAL) << "Error while reading death test internal: "
  5570. << GetLastErrnoDescription() << " [" << last_error << "]";
  5571. }
  5572. }
  5573. // Death test constructor. Increments the running death test count
  5574. // for the current test.
  5575. DeathTest::DeathTest() {
  5576. TestInfo* const info = GetUnitTestImpl()->current_test_info();
  5577. if (info == NULL) {
  5578. DeathTestAbort("Cannot run a death test outside of a TEST or "
  5579. "TEST_F construct");
  5580. }
  5581. }
  5582. // Creates and returns a death test by dispatching to the current
  5583. // death test factory.
  5584. bool DeathTest::Create(const char* statement, const RE* regex,
  5585. const char* file, int line, DeathTest** test) {
  5586. return GetUnitTestImpl()->death_test_factory()->Create(
  5587. statement, regex, file, line, test);
  5588. }
  5589. const char* DeathTest::LastMessage() {
  5590. return last_death_test_message_.c_str();
  5591. }
  5592. void DeathTest::set_last_death_test_message(const String& message) {
  5593. last_death_test_message_ = message;
  5594. }
  5595. String DeathTest::last_death_test_message_;
  5596. // Provides cross platform implementation for some death functionality.
  5597. class DeathTestImpl : public DeathTest {
  5598. protected:
  5599. DeathTestImpl(const char* a_statement, const RE* a_regex)
  5600. : statement_(a_statement),
  5601. regex_(a_regex),
  5602. spawned_(false),
  5603. status_(-1),
  5604. outcome_(IN_PROGRESS),
  5605. read_fd_(-1),
  5606. write_fd_(-1) {}
  5607. // read_fd_ is expected to be closed and cleared by a derived class.
  5608. ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
  5609. void Abort(AbortReason reason);
  5610. virtual bool Passed(bool status_ok);
  5611. const char* statement() const { return statement_; }
  5612. const RE* regex() const { return regex_; }
  5613. bool spawned() const { return spawned_; }
  5614. void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
  5615. int status() const { return status_; }
  5616. void set_status(int a_status) { status_ = a_status; }
  5617. DeathTestOutcome outcome() const { return outcome_; }
  5618. void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
  5619. int read_fd() const { return read_fd_; }
  5620. void set_read_fd(int fd) { read_fd_ = fd; }
  5621. int write_fd() const { return write_fd_; }
  5622. void set_write_fd(int fd) { write_fd_ = fd; }
  5623. // Called in the parent process only. Reads the result code of the death
  5624. // test child process via a pipe, interprets it to set the outcome_
  5625. // member, and closes read_fd_. Outputs diagnostics and terminates in
  5626. // case of unexpected codes.
  5627. void ReadAndInterpretStatusByte();
  5628. private:
  5629. // The textual content of the code this object is testing. This class
  5630. // doesn't own this string and should not attempt to delete it.
  5631. const char* const statement_;
  5632. // The regular expression which test output must match. DeathTestImpl
  5633. // doesn't own this object and should not attempt to delete it.
  5634. const RE* const regex_;
  5635. // True if the death test child process has been successfully spawned.
  5636. bool spawned_;
  5637. // The exit status of the child process.
  5638. int status_;
  5639. // How the death test concluded.
  5640. DeathTestOutcome outcome_;
  5641. // Descriptor to the read end of the pipe to the child process. It is
  5642. // always -1 in the child process. The child keeps its write end of the
  5643. // pipe in write_fd_.
  5644. int read_fd_;
  5645. // Descriptor to the child's write end of the pipe to the parent process.
  5646. // It is always -1 in the parent process. The parent keeps its end of the
  5647. // pipe in read_fd_.
  5648. int write_fd_;
  5649. };
  5650. // Called in the parent process only. Reads the result code of the death
  5651. // test child process via a pipe, interprets it to set the outcome_
  5652. // member, and closes read_fd_. Outputs diagnostics and terminates in
  5653. // case of unexpected codes.
  5654. void DeathTestImpl::ReadAndInterpretStatusByte() {
  5655. char flag;
  5656. int bytes_read;
  5657. // The read() here blocks until data is available (signifying the
  5658. // failure of the death test) or until the pipe is closed (signifying
  5659. // its success), so it's okay to call this in the parent before
  5660. // the child process has exited.
  5661. do {
  5662. bytes_read = posix::Read(read_fd(), &flag, 1);
  5663. } while (bytes_read == -1 && errno == EINTR);
  5664. if (bytes_read == 0) {
  5665. set_outcome(DIED);
  5666. } else if (bytes_read == 1) {
  5667. switch (flag) {
  5668. case kDeathTestReturned:
  5669. set_outcome(RETURNED);
  5670. break;
  5671. case kDeathTestThrew:
  5672. set_outcome(THREW);
  5673. break;
  5674. case kDeathTestLived:
  5675. set_outcome(LIVED);
  5676. break;
  5677. case kDeathTestInternalError:
  5678. FailFromInternalError(read_fd()); // Does not return.
  5679. break;
  5680. default:
  5681. GTEST_LOG_(FATAL) << "Death test child process reported "
  5682. << "unexpected status byte ("
  5683. << static_cast<unsigned int>(flag) << ")";
  5684. }
  5685. } else {
  5686. GTEST_LOG_(FATAL) << "Read from death test child process failed: "
  5687. << GetLastErrnoDescription();
  5688. }
  5689. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
  5690. set_read_fd(-1);
  5691. }
  5692. // Signals that the death test code which should have exited, didn't.
  5693. // Should be called only in a death test child process.
  5694. // Writes a status byte to the child's status file descriptor, then
  5695. // calls _exit(1).
  5696. void DeathTestImpl::Abort(AbortReason reason) {
  5697. // The parent process considers the death test to be a failure if
  5698. // it finds any data in our pipe. So, here we write a single flag byte
  5699. // to the pipe, then exit.
  5700. const char status_ch =
  5701. reason == TEST_DID_NOT_DIE ? kDeathTestLived :
  5702. reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
  5703. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
  5704. // We are leaking the descriptor here because on some platforms (i.e.,
  5705. // when built as Windows DLL), destructors of global objects will still
  5706. // run after calling _exit(). On such systems, write_fd_ will be
  5707. // indirectly closed from the destructor of UnitTestImpl, causing double
  5708. // close if it is also closed here. On debug configurations, double close
  5709. // may assert. As there are no in-process buffers to flush here, we are
  5710. // relying on the OS to close the descriptor after the process terminates
  5711. // when the destructors are not run.
  5712. _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
  5713. }
  5714. // Returns an indented copy of stderr output for a death test.
  5715. // This makes distinguishing death test output lines from regular log lines
  5716. // much easier.
  5717. static ::std::string FormatDeathTestOutput(const ::std::string& output) {
  5718. ::std::string ret;
  5719. for (size_t at = 0; ; ) {
  5720. const size_t line_end = output.find('\n', at);
  5721. ret += "[ DEATH ] ";
  5722. if (line_end == ::std::string::npos) {
  5723. ret += output.substr(at);
  5724. break;
  5725. }
  5726. ret += output.substr(at, line_end + 1 - at);
  5727. at = line_end + 1;
  5728. }
  5729. return ret;
  5730. }
  5731. // Assesses the success or failure of a death test, using both private
  5732. // members which have previously been set, and one argument:
  5733. //
  5734. // Private data members:
  5735. // outcome: An enumeration describing how the death test
  5736. // concluded: DIED, LIVED, THREW, or RETURNED. The death test
  5737. // fails in the latter three cases.
  5738. // status: The exit status of the child process. On *nix, it is in the
  5739. // in the format specified by wait(2). On Windows, this is the
  5740. // value supplied to the ExitProcess() API or a numeric code
  5741. // of the exception that terminated the program.
  5742. // regex: A regular expression object to be applied to
  5743. // the test's captured standard error output; the death test
  5744. // fails if it does not match.
  5745. //
  5746. // Argument:
  5747. // status_ok: true if exit_status is acceptable in the context of
  5748. // this particular death test, which fails if it is false
  5749. //
  5750. // Returns true iff all of the above conditions are met. Otherwise, the
  5751. // first failing condition, in the order given above, is the one that is
  5752. // reported. Also sets the last death test message string.
  5753. bool DeathTestImpl::Passed(bool status_ok) {
  5754. if (!spawned())
  5755. return false;
  5756. const String error_message = GetCapturedStderr();
  5757. bool success = false;
  5758. Message buffer;
  5759. buffer << "Death test: " << statement() << "\n";
  5760. switch (outcome()) {
  5761. case LIVED:
  5762. buffer << " Result: failed to die.\n"
  5763. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  5764. break;
  5765. case THREW:
  5766. buffer << " Result: threw an exception.\n"
  5767. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  5768. break;
  5769. case RETURNED:
  5770. buffer << " Result: illegal return in test statement.\n"
  5771. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  5772. break;
  5773. case DIED:
  5774. if (status_ok) {
  5775. const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
  5776. if (matched) {
  5777. success = true;
  5778. } else {
  5779. buffer << " Result: died but not with expected error.\n"
  5780. << " Expected: " << regex()->pattern() << "\n"
  5781. << "Actual msg:\n" << FormatDeathTestOutput(error_message);
  5782. }
  5783. } else {
  5784. buffer << " Result: died but not with expected exit code:\n"
  5785. << " " << ExitSummary(status()) << "\n"
  5786. << "Actual msg:\n" << FormatDeathTestOutput(error_message);
  5787. }
  5788. break;
  5789. case IN_PROGRESS:
  5790. default:
  5791. GTEST_LOG_(FATAL)
  5792. << "DeathTest::Passed somehow called before conclusion of test";
  5793. }
  5794. DeathTest::set_last_death_test_message(buffer.GetString());
  5795. return success;
  5796. }
  5797. # if GTEST_OS_WINDOWS
  5798. // WindowsDeathTest implements death tests on Windows. Due to the
  5799. // specifics of starting new processes on Windows, death tests there are
  5800. // always threadsafe, and Google Test considers the
  5801. // --gtest_death_test_style=fast setting to be equivalent to
  5802. // --gtest_death_test_style=threadsafe there.
  5803. //
  5804. // A few implementation notes: Like the Linux version, the Windows
  5805. // implementation uses pipes for child-to-parent communication. But due to
  5806. // the specifics of pipes on Windows, some extra steps are required:
  5807. //
  5808. // 1. The parent creates a communication pipe and stores handles to both
  5809. // ends of it.
  5810. // 2. The parent starts the child and provides it with the information
  5811. // necessary to acquire the handle to the write end of the pipe.
  5812. // 3. The child acquires the write end of the pipe and signals the parent
  5813. // using a Windows event.
  5814. // 4. Now the parent can release the write end of the pipe on its side. If
  5815. // this is done before step 3, the object's reference count goes down to
  5816. // 0 and it is destroyed, preventing the child from acquiring it. The
  5817. // parent now has to release it, or read operations on the read end of
  5818. // the pipe will not return when the child terminates.
  5819. // 5. The parent reads child's output through the pipe (outcome code and
  5820. // any possible error messages) from the pipe, and its stderr and then
  5821. // determines whether to fail the test.
  5822. //
  5823. // Note: to distinguish Win32 API calls from the local method and function
  5824. // calls, the former are explicitly resolved in the global namespace.
  5825. //
  5826. class WindowsDeathTest : public DeathTestImpl {
  5827. public:
  5828. WindowsDeathTest(const char* a_statement,
  5829. const RE* a_regex,
  5830. const char* file,
  5831. int line)
  5832. : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
  5833. // All of these virtual functions are inherited from DeathTest.
  5834. virtual int Wait();
  5835. virtual TestRole AssumeRole();
  5836. private:
  5837. // The name of the file in which the death test is located.
  5838. const char* const file_;
  5839. // The line number on which the death test is located.
  5840. const int line_;
  5841. // Handle to the write end of the pipe to the child process.
  5842. AutoHandle write_handle_;
  5843. // Child process handle.
  5844. AutoHandle child_handle_;
  5845. // Event the child process uses to signal the parent that it has
  5846. // acquired the handle to the write end of the pipe. After seeing this
  5847. // event the parent can release its own handles to make sure its
  5848. // ReadFile() calls return when the child terminates.
  5849. AutoHandle event_handle_;
  5850. };
  5851. // Waits for the child in a death test to exit, returning its exit
  5852. // status, or 0 if no child process exists. As a side effect, sets the
  5853. // outcome data member.
  5854. int WindowsDeathTest::Wait() {
  5855. if (!spawned())
  5856. return 0;
  5857. // Wait until the child either signals that it has acquired the write end
  5858. // of the pipe or it dies.
  5859. const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
  5860. switch (::WaitForMultipleObjects(2,
  5861. wait_handles,
  5862. FALSE, // Waits for any of the handles.
  5863. INFINITE)) {
  5864. case WAIT_OBJECT_0:
  5865. case WAIT_OBJECT_0 + 1:
  5866. break;
  5867. default:
  5868. GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
  5869. }
  5870. // The child has acquired the write end of the pipe or exited.
  5871. // We release the handle on our side and continue.
  5872. write_handle_.Reset();
  5873. event_handle_.Reset();
  5874. ReadAndInterpretStatusByte();
  5875. // Waits for the child process to exit if it haven't already. This
  5876. // returns immediately if the child has already exited, regardless of
  5877. // whether previous calls to WaitForMultipleObjects synchronized on this
  5878. // handle or not.
  5879. GTEST_DEATH_TEST_CHECK_(
  5880. WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
  5881. INFINITE));
  5882. DWORD status_code;
  5883. GTEST_DEATH_TEST_CHECK_(
  5884. ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
  5885. child_handle_.Reset();
  5886. set_status(static_cast<int>(status_code));
  5887. return status();
  5888. }
  5889. // The AssumeRole process for a Windows death test. It creates a child
  5890. // process with the same executable as the current process to run the
  5891. // death test. The child process is given the --gtest_filter and
  5892. // --gtest_internal_run_death_test flags such that it knows to run the
  5893. // current death test only.
  5894. DeathTest::TestRole WindowsDeathTest::AssumeRole() {
  5895. const UnitTestImpl* const impl = GetUnitTestImpl();
  5896. const InternalRunDeathTestFlag* const flag =
  5897. impl->internal_run_death_test_flag();
  5898. const TestInfo* const info = impl->current_test_info();
  5899. const int death_test_index = info->result()->death_test_count();
  5900. if (flag != NULL) {
  5901. // ParseInternalRunDeathTestFlag() has performed all the necessary
  5902. // processing.
  5903. set_write_fd(flag->write_fd());
  5904. return EXECUTE_TEST;
  5905. }
  5906. // WindowsDeathTest uses an anonymous pipe to communicate results of
  5907. // a death test.
  5908. SECURITY_ATTRIBUTES handles_are_inheritable = {
  5909. sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
  5910. HANDLE read_handle, write_handle;
  5911. GTEST_DEATH_TEST_CHECK_(
  5912. ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
  5913. 0) // Default buffer size.
  5914. != FALSE);
  5915. set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
  5916. O_RDONLY));
  5917. write_handle_.Reset(write_handle);
  5918. event_handle_.Reset(::CreateEvent(
  5919. &handles_are_inheritable,
  5920. TRUE, // The event will automatically reset to non-signaled state.
  5921. FALSE, // The initial state is non-signalled.
  5922. NULL)); // The even is unnamed.
  5923. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
  5924. const String filter_flag = String::Format("--%s%s=%s.%s",
  5925. GTEST_FLAG_PREFIX_, kFilterFlag,
  5926. info->test_case_name(),
  5927. info->name());
  5928. const String internal_flag = String::Format(
  5929. "--%s%s=%s|%d|%d|%u|%Iu|%Iu",
  5930. GTEST_FLAG_PREFIX_,
  5931. kInternalRunDeathTestFlag,
  5932. file_, line_,
  5933. death_test_index,
  5934. static_cast<unsigned int>(::GetCurrentProcessId()),
  5935. // size_t has the same with as pointers on both 32-bit and 64-bit
  5936. // Windows platforms.
  5937. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
  5938. reinterpret_cast<size_t>(write_handle),
  5939. reinterpret_cast<size_t>(event_handle_.Get()));
  5940. char executable_path[_MAX_PATH + 1]; // NOLINT
  5941. GTEST_DEATH_TEST_CHECK_(
  5942. _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
  5943. executable_path,
  5944. _MAX_PATH));
  5945. String command_line = String::Format("%s %s \"%s\"",
  5946. ::GetCommandLineA(),
  5947. filter_flag.c_str(),
  5948. internal_flag.c_str());
  5949. DeathTest::set_last_death_test_message("");
  5950. CaptureStderr();
  5951. // Flush the log buffers since the log streams are shared with the child.
  5952. FlushInfoLog();
  5953. // The child process will share the standard handles with the parent.
  5954. STARTUPINFOA startup_info;
  5955. memset(&startup_info, 0, sizeof(STARTUPINFO));
  5956. startup_info.dwFlags = STARTF_USESTDHANDLES;
  5957. startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
  5958. startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
  5959. startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
  5960. PROCESS_INFORMATION process_info;
  5961. GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
  5962. executable_path,
  5963. const_cast<char*>(command_line.c_str()),
  5964. NULL, // Retuned process handle is not inheritable.
  5965. NULL, // Retuned thread handle is not inheritable.
  5966. TRUE, // Child inherits all inheritable handles (for write_handle_).
  5967. 0x0, // Default creation flags.
  5968. NULL, // Inherit the parent's environment.
  5969. UnitTest::GetInstance()->original_working_dir(),
  5970. &startup_info,
  5971. &process_info) != FALSE);
  5972. child_handle_.Reset(process_info.hProcess);
  5973. ::CloseHandle(process_info.hThread);
  5974. set_spawned(true);
  5975. return OVERSEE_TEST;
  5976. }
  5977. # else // We are not on Windows.
  5978. // ForkingDeathTest provides implementations for most of the abstract
  5979. // methods of the DeathTest interface. Only the AssumeRole method is
  5980. // left undefined.
  5981. class ForkingDeathTest : public DeathTestImpl {
  5982. public:
  5983. ForkingDeathTest(const char* statement, const RE* regex);
  5984. // All of these virtual functions are inherited from DeathTest.
  5985. virtual int Wait();
  5986. protected:
  5987. void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
  5988. private:
  5989. // PID of child process during death test; 0 in the child process itself.
  5990. pid_t child_pid_;
  5991. };
  5992. // Constructs a ForkingDeathTest.
  5993. ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
  5994. : DeathTestImpl(a_statement, a_regex),
  5995. child_pid_(-1) {}
  5996. // Waits for the child in a death test to exit, returning its exit
  5997. // status, or 0 if no child process exists. As a side effect, sets the
  5998. // outcome data member.
  5999. int ForkingDeathTest::Wait() {
  6000. if (!spawned())
  6001. return 0;
  6002. ReadAndInterpretStatusByte();
  6003. int status_value;
  6004. GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
  6005. set_status(status_value);
  6006. return status_value;
  6007. }
  6008. // A concrete death test class that forks, then immediately runs the test
  6009. // in the child process.
  6010. class NoExecDeathTest : public ForkingDeathTest {
  6011. public:
  6012. NoExecDeathTest(const char* a_statement, const RE* a_regex) :
  6013. ForkingDeathTest(a_statement, a_regex) { }
  6014. virtual TestRole AssumeRole();
  6015. };
  6016. // The AssumeRole process for a fork-and-run death test. It implements a
  6017. // straightforward fork, with a simple pipe to transmit the status byte.
  6018. DeathTest::TestRole NoExecDeathTest::AssumeRole() {
  6019. const size_t thread_count = GetThreadCount();
  6020. if (thread_count != 1) {
  6021. GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
  6022. }
  6023. int pipe_fd[2];
  6024. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  6025. DeathTest::set_last_death_test_message("");
  6026. CaptureStderr();
  6027. // When we fork the process below, the log file buffers are copied, but the
  6028. // file descriptors are shared. We flush all log files here so that closing
  6029. // the file descriptors in the child process doesn't throw off the
  6030. // synchronization between descriptors and buffers in the parent process.
  6031. // This is as close to the fork as possible to avoid a race condition in case
  6032. // there are multiple threads running before the death test, and another
  6033. // thread writes to the log file.
  6034. FlushInfoLog();
  6035. const pid_t child_pid = fork();
  6036. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  6037. set_child_pid(child_pid);
  6038. if (child_pid == 0) {
  6039. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
  6040. set_write_fd(pipe_fd[1]);
  6041. // Redirects all logging to stderr in the child process to prevent
  6042. // concurrent writes to the log files. We capture stderr in the parent
  6043. // process and append the child process' output to a log.
  6044. LogToStderr();
  6045. // Event forwarding to the listeners of event listener API mush be shut
  6046. // down in death test subprocesses.
  6047. GetUnitTestImpl()->listeners()->SuppressEventForwarding();
  6048. return EXECUTE_TEST;
  6049. } else {
  6050. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  6051. set_read_fd(pipe_fd[0]);
  6052. set_spawned(true);
  6053. return OVERSEE_TEST;
  6054. }
  6055. }
  6056. // A concrete death test class that forks and re-executes the main
  6057. // program from the beginning, with command-line flags set that cause
  6058. // only this specific death test to be run.
  6059. class ExecDeathTest : public ForkingDeathTest {
  6060. public:
  6061. ExecDeathTest(const char* a_statement, const RE* a_regex,
  6062. const char* file, int line) :
  6063. ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
  6064. virtual TestRole AssumeRole();
  6065. private:
  6066. // The name of the file in which the death test is located.
  6067. const char* const file_;
  6068. // The line number on which the death test is located.
  6069. const int line_;
  6070. };
  6071. // Utility class for accumulating command-line arguments.
  6072. class Arguments {
  6073. public:
  6074. Arguments() {
  6075. args_.push_back(NULL);
  6076. }
  6077. ~Arguments() {
  6078. for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
  6079. ++i) {
  6080. free(*i);
  6081. }
  6082. }
  6083. void AddArgument(const char* argument) {
  6084. args_.insert(args_.end() - 1, posix::StrDup(argument));
  6085. }
  6086. template <typename Str>
  6087. void AddArguments(const ::std::vector<Str>& arguments) {
  6088. for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
  6089. i != arguments.end();
  6090. ++i) {
  6091. args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
  6092. }
  6093. }
  6094. char* const* Argv() {
  6095. return &args_[0];
  6096. }
  6097. private:
  6098. std::vector<char*> args_;
  6099. };
  6100. // A struct that encompasses the arguments to the child process of a
  6101. // threadsafe-style death test process.
  6102. struct ExecDeathTestArgs {
  6103. char* const* argv; // Command-line arguments for the child's call to exec
  6104. int close_fd; // File descriptor to close; the read end of a pipe
  6105. };
  6106. # if GTEST_OS_MAC
  6107. inline char** GetEnviron() {
  6108. // When Google Test is built as a framework on MacOS X, the environ variable
  6109. // is unavailable. Apple's documentation (man environ) recommends using
  6110. // _NSGetEnviron() instead.
  6111. return *_NSGetEnviron();
  6112. }
  6113. # else
  6114. // Some POSIX platforms expect you to declare environ. extern "C" makes
  6115. // it reside in the global namespace.
  6116. extern "C" char** environ;
  6117. inline char** GetEnviron() { return environ; }
  6118. # endif // GTEST_OS_MAC
  6119. // The main function for a threadsafe-style death test child process.
  6120. // This function is called in a clone()-ed process and thus must avoid
  6121. // any potentially unsafe operations like malloc or libc functions.
  6122. static int ExecDeathTestChildMain(void* child_arg) {
  6123. ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
  6124. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
  6125. // We need to execute the test program in the same environment where
  6126. // it was originally invoked. Therefore we change to the original
  6127. // working directory first.
  6128. const char* const original_dir =
  6129. UnitTest::GetInstance()->original_working_dir();
  6130. // We can safely call chdir() as it's a direct system call.
  6131. if (chdir(original_dir) != 0) {
  6132. DeathTestAbort(String::Format("chdir(\"%s\") failed: %s",
  6133. original_dir,
  6134. GetLastErrnoDescription().c_str()));
  6135. return EXIT_FAILURE;
  6136. }
  6137. // We can safely call execve() as it's a direct system call. We
  6138. // cannot use execvp() as it's a libc function and thus potentially
  6139. // unsafe. Since execve() doesn't search the PATH, the user must
  6140. // invoke the test program via a valid path that contains at least
  6141. // one path separator.
  6142. execve(args->argv[0], args->argv, GetEnviron());
  6143. DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s",
  6144. args->argv[0],
  6145. original_dir,
  6146. GetLastErrnoDescription().c_str()));
  6147. return EXIT_FAILURE;
  6148. }
  6149. // Two utility routines that together determine the direction the stack
  6150. // grows.
  6151. // This could be accomplished more elegantly by a single recursive
  6152. // function, but we want to guard against the unlikely possibility of
  6153. // a smart compiler optimizing the recursion away.
  6154. //
  6155. // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
  6156. // StackLowerThanAddress into StackGrowsDown, which then doesn't give
  6157. // correct answer.
  6158. bool StackLowerThanAddress(const void* ptr) GTEST_NO_INLINE_;
  6159. bool StackLowerThanAddress(const void* ptr) {
  6160. int dummy;
  6161. return &dummy < ptr;
  6162. }
  6163. bool StackGrowsDown() {
  6164. int dummy;
  6165. return StackLowerThanAddress(&dummy);
  6166. }
  6167. // A threadsafe implementation of fork(2) for threadsafe-style death tests
  6168. // that uses clone(2). It dies with an error message if anything goes
  6169. // wrong.
  6170. static pid_t ExecDeathTestFork(char* const* argv, int close_fd) {
  6171. ExecDeathTestArgs args = { argv, close_fd };
  6172. pid_t child_pid = -1;
  6173. # if GTEST_HAS_CLONE
  6174. const bool use_fork = GTEST_FLAG(death_test_use_fork);
  6175. if (!use_fork) {
  6176. static const bool stack_grows_down = StackGrowsDown();
  6177. const size_t stack_size = getpagesize();
  6178. // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
  6179. void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
  6180. MAP_ANON | MAP_PRIVATE, -1, 0);
  6181. GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
  6182. void* const stack_top =
  6183. static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0);
  6184. child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
  6185. GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
  6186. }
  6187. # else
  6188. const bool use_fork = true;
  6189. # endif // GTEST_HAS_CLONE
  6190. if (use_fork && (child_pid = fork()) == 0) {
  6191. ExecDeathTestChildMain(&args);
  6192. _exit(0);
  6193. }
  6194. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  6195. return child_pid;
  6196. }
  6197. // The AssumeRole process for a fork-and-exec death test. It re-executes the
  6198. // main program from the beginning, setting the --gtest_filter
  6199. // and --gtest_internal_run_death_test flags to cause only the current
  6200. // death test to be re-run.
  6201. DeathTest::TestRole ExecDeathTest::AssumeRole() {
  6202. const UnitTestImpl* const impl = GetUnitTestImpl();
  6203. const InternalRunDeathTestFlag* const flag =
  6204. impl->internal_run_death_test_flag();
  6205. const TestInfo* const info = impl->current_test_info();
  6206. const int death_test_index = info->result()->death_test_count();
  6207. if (flag != NULL) {
  6208. set_write_fd(flag->write_fd());
  6209. return EXECUTE_TEST;
  6210. }
  6211. int pipe_fd[2];
  6212. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  6213. // Clear the close-on-exec flag on the write end of the pipe, lest
  6214. // it be closed when the child process does an exec:
  6215. GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
  6216. const String filter_flag =
  6217. String::Format("--%s%s=%s.%s",
  6218. GTEST_FLAG_PREFIX_, kFilterFlag,
  6219. info->test_case_name(), info->name());
  6220. const String internal_flag =
  6221. String::Format("--%s%s=%s|%d|%d|%d",
  6222. GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag,
  6223. file_, line_, death_test_index, pipe_fd[1]);
  6224. Arguments args;
  6225. args.AddArguments(GetArgvs());
  6226. args.AddArgument(filter_flag.c_str());
  6227. args.AddArgument(internal_flag.c_str());
  6228. DeathTest::set_last_death_test_message("");
  6229. CaptureStderr();
  6230. // See the comment in NoExecDeathTest::AssumeRole for why the next line
  6231. // is necessary.
  6232. FlushInfoLog();
  6233. const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]);
  6234. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  6235. set_child_pid(child_pid);
  6236. set_read_fd(pipe_fd[0]);
  6237. set_spawned(true);
  6238. return OVERSEE_TEST;
  6239. }
  6240. # endif // !GTEST_OS_WINDOWS
  6241. // Creates a concrete DeathTest-derived class that depends on the
  6242. // --gtest_death_test_style flag, and sets the pointer pointed to
  6243. // by the "test" argument to its address. If the test should be
  6244. // skipped, sets that pointer to NULL. Returns true, unless the
  6245. // flag is set to an invalid value.
  6246. bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
  6247. const char* file, int line,
  6248. DeathTest** test) {
  6249. UnitTestImpl* const impl = GetUnitTestImpl();
  6250. const InternalRunDeathTestFlag* const flag =
  6251. impl->internal_run_death_test_flag();
  6252. const int death_test_index = impl->current_test_info()
  6253. ->increment_death_test_count();
  6254. if (flag != NULL) {
  6255. if (death_test_index > flag->index()) {
  6256. DeathTest::set_last_death_test_message(String::Format(
  6257. "Death test count (%d) somehow exceeded expected maximum (%d)",
  6258. death_test_index, flag->index()));
  6259. return false;
  6260. }
  6261. if (!(flag->file() == file && flag->line() == line &&
  6262. flag->index() == death_test_index)) {
  6263. *test = NULL;
  6264. return true;
  6265. }
  6266. }
  6267. # if GTEST_OS_WINDOWS
  6268. if (GTEST_FLAG(death_test_style) == "threadsafe" ||
  6269. GTEST_FLAG(death_test_style) == "fast") {
  6270. *test = new WindowsDeathTest(statement, regex, file, line);
  6271. }
  6272. # else
  6273. if (GTEST_FLAG(death_test_style) == "threadsafe") {
  6274. *test = new ExecDeathTest(statement, regex, file, line);
  6275. } else if (GTEST_FLAG(death_test_style) == "fast") {
  6276. *test = new NoExecDeathTest(statement, regex);
  6277. }
  6278. # endif // GTEST_OS_WINDOWS
  6279. else { // NOLINT - this is more readable than unbalanced brackets inside #if.
  6280. DeathTest::set_last_death_test_message(String::Format(
  6281. "Unknown death test style \"%s\" encountered",
  6282. GTEST_FLAG(death_test_style).c_str()));
  6283. return false;
  6284. }
  6285. return true;
  6286. }
  6287. // Splits a given string on a given delimiter, populating a given
  6288. // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
  6289. // ::std::string, so we can use it here.
  6290. static void SplitString(const ::std::string& str, char delimiter,
  6291. ::std::vector< ::std::string>* dest) {
  6292. ::std::vector< ::std::string> parsed;
  6293. ::std::string::size_type pos = 0;
  6294. while (::testing::internal::AlwaysTrue()) {
  6295. const ::std::string::size_type colon = str.find(delimiter, pos);
  6296. if (colon == ::std::string::npos) {
  6297. parsed.push_back(str.substr(pos));
  6298. break;
  6299. } else {
  6300. parsed.push_back(str.substr(pos, colon - pos));
  6301. pos = colon + 1;
  6302. }
  6303. }
  6304. dest->swap(parsed);
  6305. }
  6306. # if GTEST_OS_WINDOWS
  6307. // Recreates the pipe and event handles from the provided parameters,
  6308. // signals the event, and returns a file descriptor wrapped around the pipe
  6309. // handle. This function is called in the child process only.
  6310. int GetStatusFileDescriptor(unsigned int parent_process_id,
  6311. size_t write_handle_as_size_t,
  6312. size_t event_handle_as_size_t) {
  6313. AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
  6314. FALSE, // Non-inheritable.
  6315. parent_process_id));
  6316. if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
  6317. DeathTestAbort(String::Format("Unable to open parent process %u",
  6318. parent_process_id));
  6319. }
  6320. // TODO([email protected]): Replace the following check with a
  6321. // compile-time assertion when available.
  6322. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
  6323. const HANDLE write_handle =
  6324. reinterpret_cast<HANDLE>(write_handle_as_size_t);
  6325. HANDLE dup_write_handle;
  6326. // The newly initialized handle is accessible only in in the parent
  6327. // process. To obtain one accessible within the child, we need to use
  6328. // DuplicateHandle.
  6329. if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
  6330. ::GetCurrentProcess(), &dup_write_handle,
  6331. 0x0, // Requested privileges ignored since
  6332. // DUPLICATE_SAME_ACCESS is used.
  6333. FALSE, // Request non-inheritable handler.
  6334. DUPLICATE_SAME_ACCESS)) {
  6335. DeathTestAbort(String::Format(
  6336. "Unable to duplicate the pipe handle %Iu from the parent process %u",
  6337. write_handle_as_size_t, parent_process_id));
  6338. }
  6339. const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
  6340. HANDLE dup_event_handle;
  6341. if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
  6342. ::GetCurrentProcess(), &dup_event_handle,
  6343. 0x0,
  6344. FALSE,
  6345. DUPLICATE_SAME_ACCESS)) {
  6346. DeathTestAbort(String::Format(
  6347. "Unable to duplicate the event handle %Iu from the parent process %u",
  6348. event_handle_as_size_t, parent_process_id));
  6349. }
  6350. const int write_fd =
  6351. ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
  6352. if (write_fd == -1) {
  6353. DeathTestAbort(String::Format(
  6354. "Unable to convert pipe handle %Iu to a file descriptor",
  6355. write_handle_as_size_t));
  6356. }
  6357. // Signals the parent that the write end of the pipe has been acquired
  6358. // so the parent can release its own write end.
  6359. ::SetEvent(dup_event_handle);
  6360. return write_fd;
  6361. }
  6362. # endif // GTEST_OS_WINDOWS
  6363. // Returns a newly created InternalRunDeathTestFlag object with fields
  6364. // initialized from the GTEST_FLAG(internal_run_death_test) flag if
  6365. // the flag is specified; otherwise returns NULL.
  6366. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
  6367. if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
  6368. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
  6369. // can use it here.
  6370. int line = -1;
  6371. int index = -1;
  6372. ::std::vector< ::std::string> fields;
  6373. SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
  6374. int write_fd = -1;
  6375. # if GTEST_OS_WINDOWS
  6376. unsigned int parent_process_id = 0;
  6377. size_t write_handle_as_size_t = 0;
  6378. size_t event_handle_as_size_t = 0;
  6379. if (fields.size() != 6
  6380. || !ParseNaturalNumber(fields[1], &line)
  6381. || !ParseNaturalNumber(fields[2], &index)
  6382. || !ParseNaturalNumber(fields[3], &parent_process_id)
  6383. || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
  6384. || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
  6385. DeathTestAbort(String::Format(
  6386. "Bad --gtest_internal_run_death_test flag: %s",
  6387. GTEST_FLAG(internal_run_death_test).c_str()));
  6388. }
  6389. write_fd = GetStatusFileDescriptor(parent_process_id,
  6390. write_handle_as_size_t,
  6391. event_handle_as_size_t);
  6392. # else
  6393. if (fields.size() != 4
  6394. || !ParseNaturalNumber(fields[1], &line)
  6395. || !ParseNaturalNumber(fields[2], &index)
  6396. || !ParseNaturalNumber(fields[3], &write_fd)) {
  6397. DeathTestAbort(String::Format(
  6398. "Bad --gtest_internal_run_death_test flag: %s",
  6399. GTEST_FLAG(internal_run_death_test).c_str()));
  6400. }
  6401. # endif // GTEST_OS_WINDOWS
  6402. return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
  6403. }
  6404. } // namespace internal
  6405. #endif // GTEST_HAS_DEATH_TEST
  6406. } // namespace testing
  6407. // Copyright 2008, Google Inc.
  6408. // All rights reserved.
  6409. //
  6410. // Redistribution and use in source and binary forms, with or without
  6411. // modification, are permitted provided that the following conditions are
  6412. // met:
  6413. //
  6414. // * Redistributions of source code must retain the above copyright
  6415. // notice, this list of conditions and the following disclaimer.
  6416. // * Redistributions in binary form must reproduce the above
  6417. // copyright notice, this list of conditions and the following disclaimer
  6418. // in the documentation and/or other materials provided with the
  6419. // distribution.
  6420. // * Neither the name of Google Inc. nor the names of its
  6421. // contributors may be used to endorse or promote products derived from
  6422. // this software without specific prior written permission.
  6423. //
  6424. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6425. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6426. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6427. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6428. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6429. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6430. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6431. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6432. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6433. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6434. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6435. //
  6436. // Authors: [email protected] (Keith Ray)
  6437. #include <stdlib.h>
  6438. #if GTEST_OS_WINDOWS_MOBILE
  6439. # include <windows.h>
  6440. #elif GTEST_OS_WINDOWS
  6441. # include <direct.h>
  6442. # include <io.h>
  6443. #elif GTEST_OS_SYMBIAN || GTEST_OS_NACL
  6444. // Symbian OpenC and NaCl have PATH_MAX in sys/syslimits.h
  6445. # include <sys/syslimits.h>
  6446. #else
  6447. # include <limits.h>
  6448. # include <climits> // Some Linux distributions define PATH_MAX here.
  6449. #endif // GTEST_OS_WINDOWS_MOBILE
  6450. #if GTEST_OS_WINDOWS
  6451. # define GTEST_PATH_MAX_ _MAX_PATH
  6452. #elif defined(PATH_MAX)
  6453. # define GTEST_PATH_MAX_ PATH_MAX
  6454. #elif defined(_XOPEN_PATH_MAX)
  6455. # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
  6456. #else
  6457. # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
  6458. #endif // GTEST_OS_WINDOWS
  6459. namespace testing {
  6460. namespace internal {
  6461. #if GTEST_OS_WINDOWS
  6462. // On Windows, '\\' is the standard path separator, but many tools and the
  6463. // Windows API also accept '/' as an alternate path separator. Unless otherwise
  6464. // noted, a file path can contain either kind of path separators, or a mixture
  6465. // of them.
  6466. const char kPathSeparator = '\\';
  6467. const char kAlternatePathSeparator = '/';
  6468. // const char kPathSeparatorString[] = "\\";
  6469. const char kAlternatePathSeparatorString[] = "/";
  6470. # if GTEST_OS_WINDOWS_MOBILE
  6471. // Windows CE doesn't have a current directory. You should not use
  6472. // the current directory in tests on Windows CE, but this at least
  6473. // provides a reasonable fallback.
  6474. const char kCurrentDirectoryString[] = "\\";
  6475. // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
  6476. const DWORD kInvalidFileAttributes = 0xffffffff;
  6477. # else
  6478. const char kCurrentDirectoryString[] = ".\\";
  6479. # endif // GTEST_OS_WINDOWS_MOBILE
  6480. #else
  6481. const char kPathSeparator = '/';
  6482. // const char kPathSeparatorString[] = "/";
  6483. const char kCurrentDirectoryString[] = "./";
  6484. #endif // GTEST_OS_WINDOWS
  6485. // Returns whether the given character is a valid path separator.
  6486. static bool IsPathSeparator(char c) {
  6487. #if GTEST_HAS_ALT_PATH_SEP_
  6488. return (c == kPathSeparator) || (c == kAlternatePathSeparator);
  6489. #else
  6490. return c == kPathSeparator;
  6491. #endif
  6492. }
  6493. // Returns the current working directory, or "" if unsuccessful.
  6494. FilePath FilePath::GetCurrentDir() {
  6495. #if GTEST_OS_WINDOWS_MOBILE
  6496. // Windows CE doesn't have a current directory, so we just return
  6497. // something reasonable.
  6498. return FilePath(kCurrentDirectoryString);
  6499. #elif GTEST_OS_WINDOWS
  6500. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  6501. return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
  6502. #else
  6503. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  6504. return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
  6505. #endif // GTEST_OS_WINDOWS_MOBILE
  6506. }
  6507. // Returns a copy of the FilePath with the case-insensitive extension removed.
  6508. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
  6509. // FilePath("dir/file"). If a case-insensitive extension is not
  6510. // found, returns a copy of the original FilePath.
  6511. FilePath FilePath::RemoveExtension(const char* extension) const {
  6512. String dot_extension(String::Format(".%s", extension));
  6513. if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) {
  6514. return FilePath(String(pathname_.c_str(), pathname_.length() - 4));
  6515. }
  6516. return *this;
  6517. }
  6518. // Returns a pointer to the last occurence of a valid path separator in
  6519. // the FilePath. On Windows, for example, both '/' and '\' are valid path
  6520. // separators. Returns NULL if no path separator was found.
  6521. const char* FilePath::FindLastPathSeparator() const {
  6522. const char* const last_sep = strrchr(c_str(), kPathSeparator);
  6523. #if GTEST_HAS_ALT_PATH_SEP_
  6524. const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
  6525. // Comparing two pointers of which only one is NULL is undefined.
  6526. if (last_alt_sep != NULL &&
  6527. (last_sep == NULL || last_alt_sep > last_sep)) {
  6528. return last_alt_sep;
  6529. }
  6530. #endif
  6531. return last_sep;
  6532. }
  6533. // Returns a copy of the FilePath with the directory part removed.
  6534. // Example: FilePath("path/to/file").RemoveDirectoryName() returns
  6535. // FilePath("file"). If there is no directory part ("just_a_file"), it returns
  6536. // the FilePath unmodified. If there is no file part ("just_a_dir/") it
  6537. // returns an empty FilePath ("").
  6538. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  6539. FilePath FilePath::RemoveDirectoryName() const {
  6540. const char* const last_sep = FindLastPathSeparator();
  6541. return last_sep ? FilePath(String(last_sep + 1)) : *this;
  6542. }
  6543. // RemoveFileName returns the directory path with the filename removed.
  6544. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
  6545. // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
  6546. // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
  6547. // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
  6548. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  6549. FilePath FilePath::RemoveFileName() const {
  6550. const char* const last_sep = FindLastPathSeparator();
  6551. String dir;
  6552. if (last_sep) {
  6553. dir = String(c_str(), last_sep + 1 - c_str());
  6554. } else {
  6555. dir = kCurrentDirectoryString;
  6556. }
  6557. return FilePath(dir);
  6558. }
  6559. // Helper functions for naming files in a directory for xml output.
  6560. // Given directory = "dir", base_name = "test", number = 0,
  6561. // extension = "xml", returns "dir/test.xml". If number is greater
  6562. // than zero (e.g., 12), returns "dir/test_12.xml".
  6563. // On Windows platform, uses \ as the separator rather than /.
  6564. FilePath FilePath::MakeFileName(const FilePath& directory,
  6565. const FilePath& base_name,
  6566. int number,
  6567. const char* extension) {
  6568. String file;
  6569. if (number == 0) {
  6570. file = String::Format("%s.%s", base_name.c_str(), extension);
  6571. } else {
  6572. file = String::Format("%s_%d.%s", base_name.c_str(), number, extension);
  6573. }
  6574. return ConcatPaths(directory, FilePath(file));
  6575. }
  6576. // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
  6577. // On Windows, uses \ as the separator rather than /.
  6578. FilePath FilePath::ConcatPaths(const FilePath& directory,
  6579. const FilePath& relative_path) {
  6580. if (directory.IsEmpty())
  6581. return relative_path;
  6582. const FilePath dir(directory.RemoveTrailingPathSeparator());
  6583. return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator,
  6584. relative_path.c_str()));
  6585. }
  6586. // Returns true if pathname describes something findable in the file-system,
  6587. // either a file, directory, or whatever.
  6588. bool FilePath::FileOrDirectoryExists() const {
  6589. #if GTEST_OS_WINDOWS_MOBILE
  6590. LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
  6591. const DWORD attributes = GetFileAttributes(unicode);
  6592. delete [] unicode;
  6593. return attributes != kInvalidFileAttributes;
  6594. #else
  6595. posix::StatStruct file_stat;
  6596. return posix::Stat(pathname_.c_str(), &file_stat) == 0;
  6597. #endif // GTEST_OS_WINDOWS_MOBILE
  6598. }
  6599. // Returns true if pathname describes a directory in the file-system
  6600. // that exists.
  6601. bool FilePath::DirectoryExists() const {
  6602. bool result = false;
  6603. #if GTEST_OS_WINDOWS
  6604. // Don't strip off trailing separator if path is a root directory on
  6605. // Windows (like "C:\\").
  6606. const FilePath& path(IsRootDirectory() ? *this :
  6607. RemoveTrailingPathSeparator());
  6608. #else
  6609. const FilePath& path(*this);
  6610. #endif
  6611. #if GTEST_OS_WINDOWS_MOBILE
  6612. LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
  6613. const DWORD attributes = GetFileAttributes(unicode);
  6614. delete [] unicode;
  6615. if ((attributes != kInvalidFileAttributes) &&
  6616. (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  6617. result = true;
  6618. }
  6619. #else
  6620. posix::StatStruct file_stat;
  6621. result = posix::Stat(path.c_str(), &file_stat) == 0 &&
  6622. posix::IsDir(file_stat);
  6623. #endif // GTEST_OS_WINDOWS_MOBILE
  6624. return result;
  6625. }
  6626. // Returns true if pathname describes a root directory. (Windows has one
  6627. // root directory per disk drive.)
  6628. bool FilePath::IsRootDirectory() const {
  6629. #if GTEST_OS_WINDOWS
  6630. // TODO([email protected]): on Windows a network share like
  6631. // \\server\share can be a root directory, although it cannot be the
  6632. // current directory. Handle this properly.
  6633. return pathname_.length() == 3 && IsAbsolutePath();
  6634. #else
  6635. return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
  6636. #endif
  6637. }
  6638. // Returns true if pathname describes an absolute path.
  6639. bool FilePath::IsAbsolutePath() const {
  6640. const char* const name = pathname_.c_str();
  6641. #if GTEST_OS_WINDOWS
  6642. return pathname_.length() >= 3 &&
  6643. ((name[0] >= 'a' && name[0] <= 'z') ||
  6644. (name[0] >= 'A' && name[0] <= 'Z')) &&
  6645. name[1] == ':' &&
  6646. IsPathSeparator(name[2]);
  6647. #else
  6648. return IsPathSeparator(name[0]);
  6649. #endif
  6650. }
  6651. // Returns a pathname for a file that does not currently exist. The pathname
  6652. // will be directory/base_name.extension or
  6653. // directory/base_name_<number>.extension if directory/base_name.extension
  6654. // already exists. The number will be incremented until a pathname is found
  6655. // that does not already exist.
  6656. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
  6657. // There could be a race condition if two or more processes are calling this
  6658. // function at the same time -- they could both pick the same filename.
  6659. FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
  6660. const FilePath& base_name,
  6661. const char* extension) {
  6662. FilePath full_pathname;
  6663. int number = 0;
  6664. do {
  6665. full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
  6666. } while (full_pathname.FileOrDirectoryExists());
  6667. return full_pathname;
  6668. }
  6669. // Returns true if FilePath ends with a path separator, which indicates that
  6670. // it is intended to represent a directory. Returns false otherwise.
  6671. // This does NOT check that a directory (or file) actually exists.
  6672. bool FilePath::IsDirectory() const {
  6673. return !pathname_.empty() &&
  6674. IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
  6675. }
  6676. // Create directories so that path exists. Returns true if successful or if
  6677. // the directories already exist; returns false if unable to create directories
  6678. // for any reason.
  6679. bool FilePath::CreateDirectoriesRecursively() const {
  6680. if (!this->IsDirectory()) {
  6681. return false;
  6682. }
  6683. if (pathname_.length() == 0 || this->DirectoryExists()) {
  6684. return true;
  6685. }
  6686. const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
  6687. return parent.CreateDirectoriesRecursively() && this->CreateFolder();
  6688. }
  6689. // Create the directory so that path exists. Returns true if successful or
  6690. // if the directory already exists; returns false if unable to create the
  6691. // directory for any reason, including if the parent directory does not
  6692. // exist. Not named "CreateDirectory" because that's a macro on Windows.
  6693. bool FilePath::CreateFolder() const {
  6694. #if GTEST_OS_WINDOWS_MOBILE
  6695. FilePath removed_sep(this->RemoveTrailingPathSeparator());
  6696. LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
  6697. int result = CreateDirectory(unicode, NULL) ? 0 : -1;
  6698. delete [] unicode;
  6699. #elif GTEST_OS_WINDOWS
  6700. int result = _mkdir(pathname_.c_str());
  6701. #else
  6702. int result = mkdir(pathname_.c_str(), 0777);
  6703. #endif // GTEST_OS_WINDOWS_MOBILE
  6704. if (result == -1) {
  6705. return this->DirectoryExists(); // An error is OK if the directory exists.
  6706. }
  6707. return true; // No error.
  6708. }
  6709. // If input name has a trailing separator character, remove it and return the
  6710. // name, otherwise return the name string unmodified.
  6711. // On Windows platform, uses \ as the separator, other platforms use /.
  6712. FilePath FilePath::RemoveTrailingPathSeparator() const {
  6713. return IsDirectory()
  6714. ? FilePath(String(pathname_.c_str(), pathname_.length() - 1))
  6715. : *this;
  6716. }
  6717. // Removes any redundant separators that might be in the pathname.
  6718. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
  6719. // redundancies that might be in a pathname involving "." or "..".
  6720. // TODO([email protected]): handle Windows network shares (e.g. \\server\share).
  6721. void FilePath::Normalize() {
  6722. if (pathname_.c_str() == NULL) {
  6723. pathname_ = "";
  6724. return;
  6725. }
  6726. const char* src = pathname_.c_str();
  6727. char* const dest = new char[pathname_.length() + 1];
  6728. char* dest_ptr = dest;
  6729. memset(dest_ptr, 0, pathname_.length() + 1);
  6730. while (*src != '\0') {
  6731. *dest_ptr = *src;
  6732. if (!IsPathSeparator(*src)) {
  6733. src++;
  6734. } else {
  6735. #if GTEST_HAS_ALT_PATH_SEP_
  6736. if (*dest_ptr == kAlternatePathSeparator) {
  6737. *dest_ptr = kPathSeparator;
  6738. }
  6739. #endif
  6740. while (IsPathSeparator(*src))
  6741. src++;
  6742. }
  6743. dest_ptr++;
  6744. }
  6745. *dest_ptr = '\0';
  6746. pathname_ = dest;
  6747. delete[] dest;
  6748. }
  6749. } // namespace internal
  6750. } // namespace testing
  6751. // Copyright 2008, Google Inc.
  6752. // All rights reserved.
  6753. //
  6754. // Redistribution and use in source and binary forms, with or without
  6755. // modification, are permitted provided that the following conditions are
  6756. // met:
  6757. //
  6758. // * Redistributions of source code must retain the above copyright
  6759. // notice, this list of conditions and the following disclaimer.
  6760. // * Redistributions in binary form must reproduce the above
  6761. // copyright notice, this list of conditions and the following disclaimer
  6762. // in the documentation and/or other materials provided with the
  6763. // distribution.
  6764. // * Neither the name of Google Inc. nor the names of its
  6765. // contributors may be used to endorse or promote products derived from
  6766. // this software without specific prior written permission.
  6767. //
  6768. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6769. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6770. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6771. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6772. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6773. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6774. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6775. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6776. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6777. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6778. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6779. //
  6780. // Author: [email protected] (Zhanyong Wan)
  6781. #include <limits.h>
  6782. #include <stdlib.h>
  6783. #include <stdio.h>
  6784. #include <string.h>
  6785. #if GTEST_OS_WINDOWS_MOBILE
  6786. # include <windows.h> // For TerminateProcess()
  6787. #elif GTEST_OS_WINDOWS
  6788. # include <io.h>
  6789. # include <sys/stat.h>
  6790. #else
  6791. # include <unistd.h>
  6792. #endif // GTEST_OS_WINDOWS_MOBILE
  6793. #if GTEST_OS_MAC
  6794. # include <mach/mach_init.h>
  6795. # include <mach/task.h>
  6796. # include <mach/vm_map.h>
  6797. #endif // GTEST_OS_MAC
  6798. // Indicates that this translation unit is part of Google Test's
  6799. // implementation. It must come before gtest-internal-inl.h is
  6800. // included, or there will be a compiler error. This trick is to
  6801. // prevent a user from accidentally including gtest-internal-inl.h in
  6802. // his code.
  6803. #define GTEST_IMPLEMENTATION_ 1
  6804. #undef GTEST_IMPLEMENTATION_
  6805. namespace testing {
  6806. namespace internal {
  6807. #if defined(_MSC_VER) || defined(__BORLANDC__)
  6808. // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
  6809. const int kStdOutFileno = 1;
  6810. const int kStdErrFileno = 2;
  6811. #else
  6812. const int kStdOutFileno = STDOUT_FILENO;
  6813. const int kStdErrFileno = STDERR_FILENO;
  6814. #endif // _MSC_VER
  6815. #if GTEST_OS_MAC
  6816. // Returns the number of threads running in the process, or 0 to indicate that
  6817. // we cannot detect it.
  6818. size_t GetThreadCount() {
  6819. const task_t task = mach_task_self();
  6820. mach_msg_type_number_t thread_count;
  6821. thread_act_array_t thread_list;
  6822. const kern_return_t status = task_threads(task, &thread_list, &thread_count);
  6823. if (status == KERN_SUCCESS) {
  6824. // task_threads allocates resources in thread_list and we need to free them
  6825. // to avoid leaks.
  6826. vm_deallocate(task,
  6827. reinterpret_cast<vm_address_t>(thread_list),
  6828. sizeof(thread_t) * thread_count);
  6829. return static_cast<size_t>(thread_count);
  6830. } else {
  6831. return 0;
  6832. }
  6833. }
  6834. #else
  6835. size_t GetThreadCount() {
  6836. // There's no portable way to detect the number of threads, so we just
  6837. // return 0 to indicate that we cannot detect it.
  6838. return 0;
  6839. }
  6840. #endif // GTEST_OS_MAC
  6841. #if GTEST_USES_POSIX_RE
  6842. // Implements RE. Currently only needed for death tests.
  6843. RE::~RE() {
  6844. if (is_valid_) {
  6845. // regfree'ing an invalid regex might crash because the content
  6846. // of the regex is undefined. Since the regex's are essentially
  6847. // the same, one cannot be valid (or invalid) without the other
  6848. // being so too.
  6849. regfree(&partial_regex_);
  6850. regfree(&full_regex_);
  6851. }
  6852. free(const_cast<char*>(pattern_));
  6853. }
  6854. // Returns true iff regular expression re matches the entire str.
  6855. bool RE::FullMatch(const char* str, const RE& re) {
  6856. if (!re.is_valid_) return false;
  6857. regmatch_t match;
  6858. return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
  6859. }
  6860. // Returns true iff regular expression re matches a substring of str
  6861. // (including str itself).
  6862. bool RE::PartialMatch(const char* str, const RE& re) {
  6863. if (!re.is_valid_) return false;
  6864. regmatch_t match;
  6865. return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
  6866. }
  6867. // Initializes an RE from its string representation.
  6868. void RE::Init(const char* regex) {
  6869. pattern_ = posix::StrDup(regex);
  6870. // Reserves enough bytes to hold the regular expression used for a
  6871. // full match.
  6872. const size_t full_regex_len = strlen(regex) + 10;
  6873. char* const full_pattern = new char[full_regex_len];
  6874. snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
  6875. is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
  6876. // We want to call regcomp(&partial_regex_, ...) even if the
  6877. // previous expression returns false. Otherwise partial_regex_ may
  6878. // not be properly initialized can may cause trouble when it's
  6879. // freed.
  6880. //
  6881. // Some implementation of POSIX regex (e.g. on at least some
  6882. // versions of Cygwin) doesn't accept the empty string as a valid
  6883. // regex. We change it to an equivalent form "()" to be safe.
  6884. if (is_valid_) {
  6885. const char* const partial_regex = (*regex == '\0') ? "()" : regex;
  6886. is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
  6887. }
  6888. EXPECT_TRUE(is_valid_)
  6889. << "Regular expression \"" << regex
  6890. << "\" is not a valid POSIX Extended regular expression.";
  6891. delete[] full_pattern;
  6892. }
  6893. #elif GTEST_USES_SIMPLE_RE
  6894. // Returns true iff ch appears anywhere in str (excluding the
  6895. // terminating '\0' character).
  6896. bool IsInSet(char ch, const char* str) {
  6897. return ch != '\0' && strchr(str, ch) != NULL;
  6898. }
  6899. // Returns true iff ch belongs to the given classification. Unlike
  6900. // similar functions in <ctype.h>, these aren't affected by the
  6901. // current locale.
  6902. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
  6903. bool IsAsciiPunct(char ch) {
  6904. return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
  6905. }
  6906. bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
  6907. bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
  6908. bool IsAsciiWordChar(char ch) {
  6909. return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
  6910. ('0' <= ch && ch <= '9') || ch == '_';
  6911. }
  6912. // Returns true iff "\\c" is a supported escape sequence.
  6913. bool IsValidEscape(char c) {
  6914. return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
  6915. }
  6916. // Returns true iff the given atom (specified by escaped and pattern)
  6917. // matches ch. The result is undefined if the atom is invalid.
  6918. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
  6919. if (escaped) { // "\\p" where p is pattern_char.
  6920. switch (pattern_char) {
  6921. case 'd': return IsAsciiDigit(ch);
  6922. case 'D': return !IsAsciiDigit(ch);
  6923. case 'f': return ch == '\f';
  6924. case 'n': return ch == '\n';
  6925. case 'r': return ch == '\r';
  6926. case 's': return IsAsciiWhiteSpace(ch);
  6927. case 'S': return !IsAsciiWhiteSpace(ch);
  6928. case 't': return ch == '\t';
  6929. case 'v': return ch == '\v';
  6930. case 'w': return IsAsciiWordChar(ch);
  6931. case 'W': return !IsAsciiWordChar(ch);
  6932. }
  6933. return IsAsciiPunct(pattern_char) && pattern_char == ch;
  6934. }
  6935. return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
  6936. }
  6937. // Helper function used by ValidateRegex() to format error messages.
  6938. String FormatRegexSyntaxError(const char* regex, int index) {
  6939. return (Message() << "Syntax error at index " << index
  6940. << " in simple regular expression \"" << regex << "\": ").GetString();
  6941. }
  6942. // Generates non-fatal failures and returns false if regex is invalid;
  6943. // otherwise returns true.
  6944. bool ValidateRegex(const char* regex) {
  6945. if (regex == NULL) {
  6946. // TODO([email protected]): fix the source file location in the
  6947. // assertion failures to match where the regex is used in user
  6948. // code.
  6949. ADD_FAILURE() << "NULL is not a valid simple regular expression.";
  6950. return false;
  6951. }
  6952. bool is_valid = true;
  6953. // True iff ?, *, or + can follow the previous atom.
  6954. bool prev_repeatable = false;
  6955. for (int i = 0; regex[i]; i++) {
  6956. if (regex[i] == '\\') { // An escape sequence
  6957. i++;
  6958. if (regex[i] == '\0') {
  6959. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  6960. << "'\\' cannot appear at the end.";
  6961. return false;
  6962. }
  6963. if (!IsValidEscape(regex[i])) {
  6964. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  6965. << "invalid escape sequence \"\\" << regex[i] << "\".";
  6966. is_valid = false;
  6967. }
  6968. prev_repeatable = true;
  6969. } else { // Not an escape sequence.
  6970. const char ch = regex[i];
  6971. if (ch == '^' && i > 0) {
  6972. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  6973. << "'^' can only appear at the beginning.";
  6974. is_valid = false;
  6975. } else if (ch == '$' && regex[i + 1] != '\0') {
  6976. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  6977. << "'$' can only appear at the end.";
  6978. is_valid = false;
  6979. } else if (IsInSet(ch, "()[]{}|")) {
  6980. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  6981. << "'" << ch << "' is unsupported.";
  6982. is_valid = false;
  6983. } else if (IsRepeat(ch) && !prev_repeatable) {
  6984. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  6985. << "'" << ch << "' can only follow a repeatable token.";
  6986. is_valid = false;
  6987. }
  6988. prev_repeatable = !IsInSet(ch, "^$?*+");
  6989. }
  6990. }
  6991. return is_valid;
  6992. }
  6993. // Matches a repeated regex atom followed by a valid simple regular
  6994. // expression. The regex atom is defined as c if escaped is false,
  6995. // or \c otherwise. repeat is the repetition meta character (?, *,
  6996. // or +). The behavior is undefined if str contains too many
  6997. // characters to be indexable by size_t, in which case the test will
  6998. // probably time out anyway. We are fine with this limitation as
  6999. // std::string has it too.
  7000. bool MatchRepetitionAndRegexAtHead(
  7001. bool escaped, char c, char repeat, const char* regex,
  7002. const char* str) {
  7003. const size_t min_count = (repeat == '+') ? 1 : 0;
  7004. const size_t max_count = (repeat == '?') ? 1 :
  7005. static_cast<size_t>(-1) - 1;
  7006. // We cannot call numeric_limits::max() as it conflicts with the
  7007. // max() macro on Windows.
  7008. for (size_t i = 0; i <= max_count; ++i) {
  7009. // We know that the atom matches each of the first i characters in str.
  7010. if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
  7011. // We have enough matches at the head, and the tail matches too.
  7012. // Since we only care about *whether* the pattern matches str
  7013. // (as opposed to *how* it matches), there is no need to find a
  7014. // greedy match.
  7015. return true;
  7016. }
  7017. if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
  7018. return false;
  7019. }
  7020. return false;
  7021. }
  7022. // Returns true iff regex matches a prefix of str. regex must be a
  7023. // valid simple regular expression and not start with "^", or the
  7024. // result is undefined.
  7025. bool MatchRegexAtHead(const char* regex, const char* str) {
  7026. if (*regex == '\0') // An empty regex matches a prefix of anything.
  7027. return true;
  7028. // "$" only matches the end of a string. Note that regex being
  7029. // valid guarantees that there's nothing after "$" in it.
  7030. if (*regex == '$')
  7031. return *str == '\0';
  7032. // Is the first thing in regex an escape sequence?
  7033. const bool escaped = *regex == '\\';
  7034. if (escaped)
  7035. ++regex;
  7036. if (IsRepeat(regex[1])) {
  7037. // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
  7038. // here's an indirect recursion. It terminates as the regex gets
  7039. // shorter in each recursion.
  7040. return MatchRepetitionAndRegexAtHead(
  7041. escaped, regex[0], regex[1], regex + 2, str);
  7042. } else {
  7043. // regex isn't empty, isn't "$", and doesn't start with a
  7044. // repetition. We match the first atom of regex with the first
  7045. // character of str and recurse.
  7046. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
  7047. MatchRegexAtHead(regex + 1, str + 1);
  7048. }
  7049. }
  7050. // Returns true iff regex matches any substring of str. regex must be
  7051. // a valid simple regular expression, or the result is undefined.
  7052. //
  7053. // The algorithm is recursive, but the recursion depth doesn't exceed
  7054. // the regex length, so we won't need to worry about running out of
  7055. // stack space normally. In rare cases the time complexity can be
  7056. // exponential with respect to the regex length + the string length,
  7057. // but usually it's must faster (often close to linear).
  7058. bool MatchRegexAnywhere(const char* regex, const char* str) {
  7059. if (regex == NULL || str == NULL)
  7060. return false;
  7061. if (*regex == '^')
  7062. return MatchRegexAtHead(regex + 1, str);
  7063. // A successful match can be anywhere in str.
  7064. do {
  7065. if (MatchRegexAtHead(regex, str))
  7066. return true;
  7067. } while (*str++ != '\0');
  7068. return false;
  7069. }
  7070. // Implements the RE class.
  7071. RE::~RE() {
  7072. free(const_cast<char*>(pattern_));
  7073. free(const_cast<char*>(full_pattern_));
  7074. }
  7075. // Returns true iff regular expression re matches the entire str.
  7076. bool RE::FullMatch(const char* str, const RE& re) {
  7077. return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
  7078. }
  7079. // Returns true iff regular expression re matches a substring of str
  7080. // (including str itself).
  7081. bool RE::PartialMatch(const char* str, const RE& re) {
  7082. return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
  7083. }
  7084. // Initializes an RE from its string representation.
  7085. void RE::Init(const char* regex) {
  7086. pattern_ = full_pattern_ = NULL;
  7087. if (regex != NULL) {
  7088. pattern_ = posix::StrDup(regex);
  7089. }
  7090. is_valid_ = ValidateRegex(regex);
  7091. if (!is_valid_) {
  7092. // No need to calculate the full pattern when the regex is invalid.
  7093. return;
  7094. }
  7095. const size_t len = strlen(regex);
  7096. // Reserves enough bytes to hold the regular expression used for a
  7097. // full match: we need space to prepend a '^', append a '$', and
  7098. // terminate the string with '\0'.
  7099. char* buffer = static_cast<char*>(malloc(len + 3));
  7100. full_pattern_ = buffer;
  7101. if (*regex != '^')
  7102. *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
  7103. // We don't use snprintf or strncpy, as they trigger a warning when
  7104. // compiled with VC++ 8.0.
  7105. memcpy(buffer, regex, len);
  7106. buffer += len;
  7107. if (len == 0 || regex[len - 1] != '$')
  7108. *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
  7109. *buffer = '\0';
  7110. }
  7111. #endif // GTEST_USES_POSIX_RE
  7112. const char kUnknownFile[] = "unknown file";
  7113. // Formats a source file path and a line number as they would appear
  7114. // in an error message from the compiler used to compile this code.
  7115. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
  7116. const char* const file_name = file == NULL ? kUnknownFile : file;
  7117. if (line < 0) {
  7118. return String::Format("%s:", file_name).c_str();
  7119. }
  7120. #ifdef _MSC_VER
  7121. return String::Format("%s(%d):", file_name, line).c_str();
  7122. #else
  7123. return String::Format("%s:%d:", file_name, line).c_str();
  7124. #endif // _MSC_VER
  7125. }
  7126. // Formats a file location for compiler-independent XML output.
  7127. // Although this function is not platform dependent, we put it next to
  7128. // FormatFileLocation in order to contrast the two functions.
  7129. // Note that FormatCompilerIndependentFileLocation() does NOT append colon
  7130. // to the file location it produces, unlike FormatFileLocation().
  7131. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
  7132. const char* file, int line) {
  7133. const char* const file_name = file == NULL ? kUnknownFile : file;
  7134. if (line < 0)
  7135. return file_name;
  7136. else
  7137. return String::Format("%s:%d", file_name, line).c_str();
  7138. }
  7139. GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
  7140. : severity_(severity) {
  7141. const char* const marker =
  7142. severity == GTEST_INFO ? "[ INFO ]" :
  7143. severity == GTEST_WARNING ? "[WARNING]" :
  7144. severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
  7145. GetStream() << ::std::endl << marker << " "
  7146. << FormatFileLocation(file, line).c_str() << ": ";
  7147. }
  7148. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  7149. GTestLog::~GTestLog() {
  7150. GetStream() << ::std::endl;
  7151. if (severity_ == GTEST_FATAL) {
  7152. fflush(stderr);
  7153. posix::Abort();
  7154. }
  7155. }
  7156. // Disable Microsoft deprecation warnings for POSIX functions called from
  7157. // this class (creat, dup, dup2, and close)
  7158. #ifdef _MSC_VER
  7159. # pragma warning(push)
  7160. # pragma warning(disable: 4996)
  7161. #endif // _MSC_VER
  7162. #if GTEST_HAS_STREAM_REDIRECTION
  7163. // Object that captures an output stream (stdout/stderr).
  7164. class CapturedStream {
  7165. public:
  7166. // The ctor redirects the stream to a temporary file.
  7167. CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
  7168. # if GTEST_OS_WINDOWS
  7169. char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  7170. char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  7171. ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
  7172. const UINT success = ::GetTempFileNameA(temp_dir_path,
  7173. "gtest_redir",
  7174. 0, // Generate unique file name.
  7175. temp_file_path);
  7176. GTEST_CHECK_(success != 0)
  7177. << "Unable to create a temporary file in " << temp_dir_path;
  7178. const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
  7179. GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
  7180. << temp_file_path;
  7181. filename_ = temp_file_path;
  7182. # else
  7183. // There's no guarantee that a test has write access to the
  7184. // current directory, so we create the temporary file in the /tmp
  7185. // directory instead.
  7186. char name_template[] = "/tmp/captured_stream.XXXXXX";
  7187. const int captured_fd = mkstemp(name_template);
  7188. filename_ = name_template;
  7189. # endif // GTEST_OS_WINDOWS
  7190. fflush(NULL);
  7191. dup2(captured_fd, fd_);
  7192. close(captured_fd);
  7193. }
  7194. ~CapturedStream() {
  7195. remove(filename_.c_str());
  7196. }
  7197. String GetCapturedString() {
  7198. if (uncaptured_fd_ != -1) {
  7199. // Restores the original stream.
  7200. fflush(NULL);
  7201. dup2(uncaptured_fd_, fd_);
  7202. close(uncaptured_fd_);
  7203. uncaptured_fd_ = -1;
  7204. }
  7205. FILE* const file = posix::FOpen(filename_.c_str(), "r");
  7206. const String content = ReadEntireFile(file);
  7207. posix::FClose(file);
  7208. return content;
  7209. }
  7210. private:
  7211. // Reads the entire content of a file as a String.
  7212. static String ReadEntireFile(FILE* file);
  7213. // Returns the size (in bytes) of a file.
  7214. static size_t GetFileSize(FILE* file);
  7215. const int fd_; // A stream to capture.
  7216. int uncaptured_fd_;
  7217. // Name of the temporary file holding the stderr output.
  7218. ::std::string filename_;
  7219. GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
  7220. };
  7221. // Returns the size (in bytes) of a file.
  7222. size_t CapturedStream::GetFileSize(FILE* file) {
  7223. fseek(file, 0, SEEK_END);
  7224. return static_cast<size_t>(ftell(file));
  7225. }
  7226. // Reads the entire content of a file as a string.
  7227. String CapturedStream::ReadEntireFile(FILE* file) {
  7228. const size_t file_size = GetFileSize(file);
  7229. char* const buffer = new char[file_size];
  7230. size_t bytes_last_read = 0; // # of bytes read in the last fread()
  7231. size_t bytes_read = 0; // # of bytes read so far
  7232. fseek(file, 0, SEEK_SET);
  7233. // Keeps reading the file until we cannot read further or the
  7234. // pre-determined file size is reached.
  7235. do {
  7236. bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
  7237. bytes_read += bytes_last_read;
  7238. } while (bytes_last_read > 0 && bytes_read < file_size);
  7239. const String content(buffer, bytes_read);
  7240. delete[] buffer;
  7241. return content;
  7242. }
  7243. # ifdef _MSC_VER
  7244. # pragma warning(pop)
  7245. # endif // _MSC_VER
  7246. static CapturedStream* g_captured_stderr = NULL;
  7247. static CapturedStream* g_captured_stdout = NULL;
  7248. // Starts capturing an output stream (stdout/stderr).
  7249. void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
  7250. if (*stream != NULL) {
  7251. GTEST_LOG_(FATAL) << "Only one " << stream_name
  7252. << " capturer can exist at a time.";
  7253. }
  7254. *stream = new CapturedStream(fd);
  7255. }
  7256. // Stops capturing the output stream and returns the captured string.
  7257. String GetCapturedStream(CapturedStream** captured_stream) {
  7258. const String content = (*captured_stream)->GetCapturedString();
  7259. delete *captured_stream;
  7260. *captured_stream = NULL;
  7261. return content;
  7262. }
  7263. // Starts capturing stdout.
  7264. void CaptureStdout() {
  7265. CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
  7266. }
  7267. // Starts capturing stderr.
  7268. void CaptureStderr() {
  7269. CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
  7270. }
  7271. // Stops capturing stdout and returns the captured string.
  7272. String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); }
  7273. // Stops capturing stderr and returns the captured string.
  7274. String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); }
  7275. #endif // GTEST_HAS_STREAM_REDIRECTION
  7276. #if GTEST_HAS_DEATH_TEST
  7277. // A copy of all command line arguments. Set by InitGoogleTest().
  7278. ::std::vector<String> g_argvs;
  7279. // Returns the command line as a vector of strings.
  7280. const ::std::vector<String>& GetArgvs() { return g_argvs; }
  7281. #endif // GTEST_HAS_DEATH_TEST
  7282. #if GTEST_OS_WINDOWS_MOBILE
  7283. namespace posix {
  7284. void Abort() {
  7285. DebugBreak();
  7286. TerminateProcess(GetCurrentProcess(), 1);
  7287. }
  7288. } // namespace posix
  7289. #endif // GTEST_OS_WINDOWS_MOBILE
  7290. // Returns the name of the environment variable corresponding to the
  7291. // given flag. For example, FlagToEnvVar("foo") will return
  7292. // "GTEST_FOO" in the open-source version.
  7293. static String FlagToEnvVar(const char* flag) {
  7294. const String full_flag =
  7295. (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
  7296. Message env_var;
  7297. for (size_t i = 0; i != full_flag.length(); i++) {
  7298. env_var << ToUpper(full_flag.c_str()[i]);
  7299. }
  7300. return env_var.GetString();
  7301. }
  7302. // Parses 'str' for a 32-bit signed integer. If successful, writes
  7303. // the result to *value and returns true; otherwise leaves *value
  7304. // unchanged and returns false.
  7305. bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
  7306. // Parses the environment variable as a decimal integer.
  7307. char* end = NULL;
  7308. const long long_value = strtol(str, &end, 10); // NOLINT
  7309. // Has strtol() consumed all characters in the string?
  7310. if (*end != '\0') {
  7311. // No - an invalid character was encountered.
  7312. Message msg;
  7313. msg << "WARNING: " << src_text
  7314. << " is expected to be a 32-bit integer, but actually"
  7315. << " has value \"" << str << "\".\n";
  7316. printf("%s", msg.GetString().c_str());
  7317. fflush(stdout);
  7318. return false;
  7319. }
  7320. // Is the parsed value in the range of an Int32?
  7321. const Int32 result = static_cast<Int32>(long_value);
  7322. if (long_value == LONG_MAX || long_value == LONG_MIN ||
  7323. // The parsed value overflows as a long. (strtol() returns
  7324. // LONG_MAX or LONG_MIN when the input overflows.)
  7325. result != long_value
  7326. // The parsed value overflows as an Int32.
  7327. ) {
  7328. Message msg;
  7329. msg << "WARNING: " << src_text
  7330. << " is expected to be a 32-bit integer, but actually"
  7331. << " has value " << str << ", which overflows.\n";
  7332. printf("%s", msg.GetString().c_str());
  7333. fflush(stdout);
  7334. return false;
  7335. }
  7336. *value = result;
  7337. return true;
  7338. }
  7339. // Reads and returns the Boolean environment variable corresponding to
  7340. // the given flag; if it's not set, returns default_value.
  7341. //
  7342. // The value is considered true iff it's not "0".
  7343. bool BoolFromGTestEnv(const char* flag, bool default_value) {
  7344. const String env_var = FlagToEnvVar(flag);
  7345. const char* const string_value = posix::GetEnv(env_var.c_str());
  7346. return string_value == NULL ?
  7347. default_value : strcmp(string_value, "0") != 0;
  7348. }
  7349. // Reads and returns a 32-bit integer stored in the environment
  7350. // variable corresponding to the given flag; if it isn't set or
  7351. // doesn't represent a valid 32-bit integer, returns default_value.
  7352. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
  7353. const String env_var = FlagToEnvVar(flag);
  7354. const char* const string_value = posix::GetEnv(env_var.c_str());
  7355. if (string_value == NULL) {
  7356. // The environment variable is not set.
  7357. return default_value;
  7358. }
  7359. Int32 result = default_value;
  7360. if (!ParseInt32(Message() << "Environment variable " << env_var,
  7361. string_value, &result)) {
  7362. printf("The default value %s is used.\n",
  7363. (Message() << default_value).GetString().c_str());
  7364. fflush(stdout);
  7365. return default_value;
  7366. }
  7367. return result;
  7368. }
  7369. // Reads and returns the string environment variable corresponding to
  7370. // the given flag; if it's not set, returns default_value.
  7371. const char* StringFromGTestEnv(const char* flag, const char* default_value) {
  7372. const String env_var = FlagToEnvVar(flag);
  7373. const char* const value = posix::GetEnv(env_var.c_str());
  7374. return value == NULL ? default_value : value;
  7375. }
  7376. } // namespace internal
  7377. } // namespace testing
  7378. // Copyright 2007, Google Inc.
  7379. // All rights reserved.
  7380. //
  7381. // Redistribution and use in source and binary forms, with or without
  7382. // modification, are permitted provided that the following conditions are
  7383. // met:
  7384. //
  7385. // * Redistributions of source code must retain the above copyright
  7386. // notice, this list of conditions and the following disclaimer.
  7387. // * Redistributions in binary form must reproduce the above
  7388. // copyright notice, this list of conditions and the following disclaimer
  7389. // in the documentation and/or other materials provided with the
  7390. // distribution.
  7391. // * Neither the name of Google Inc. nor the names of its
  7392. // contributors may be used to endorse or promote products derived from
  7393. // this software without specific prior written permission.
  7394. //
  7395. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7396. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7397. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7398. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7399. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7400. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7401. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7402. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7403. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7404. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7405. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7406. //
  7407. // Author: [email protected] (Zhanyong Wan)
  7408. // Google Test - The Google C++ Testing Framework
  7409. //
  7410. // This file implements a universal value printer that can print a
  7411. // value of any type T:
  7412. //
  7413. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  7414. //
  7415. // It uses the << operator when possible, and prints the bytes in the
  7416. // object otherwise. A user can override its behavior for a class
  7417. // type Foo by defining either operator<<(::std::ostream&, const Foo&)
  7418. // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
  7419. // defines Foo.
  7420. #include <ctype.h>
  7421. #include <stdio.h>
  7422. #include <ostream> // NOLINT
  7423. #include <string>
  7424. namespace testing {
  7425. namespace {
  7426. using ::std::ostream;
  7427. #if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s.
  7428. # define snprintf _snprintf
  7429. #elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf.
  7430. # define snprintf _snprintf_s
  7431. #elif _MSC_VER
  7432. # define snprintf _snprintf
  7433. #endif // GTEST_OS_WINDOWS_MOBILE
  7434. // Prints a segment of bytes in the given object.
  7435. void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
  7436. size_t count, ostream* os) {
  7437. char text[5] = "";
  7438. for (size_t i = 0; i != count; i++) {
  7439. const size_t j = start + i;
  7440. if (i != 0) {
  7441. // Organizes the bytes into groups of 2 for easy parsing by
  7442. // human.
  7443. if ((j % 2) == 0)
  7444. *os << ' ';
  7445. else
  7446. *os << '-';
  7447. }
  7448. snprintf(text, sizeof(text), "%02X", obj_bytes[j]);
  7449. *os << text;
  7450. }
  7451. }
  7452. // Prints the bytes in the given value to the given ostream.
  7453. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
  7454. ostream* os) {
  7455. // Tells the user how big the object is.
  7456. *os << count << "-byte object <";
  7457. const size_t kThreshold = 132;
  7458. const size_t kChunkSize = 64;
  7459. // If the object size is bigger than kThreshold, we'll have to omit
  7460. // some details by printing only the first and the last kChunkSize
  7461. // bytes.
  7462. // TODO(wan): let the user control the threshold using a flag.
  7463. if (count < kThreshold) {
  7464. PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
  7465. } else {
  7466. PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
  7467. *os << " ... ";
  7468. // Rounds up to 2-byte boundary.
  7469. const size_t resume_pos = (count - kChunkSize + 1)/2*2;
  7470. PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
  7471. }
  7472. *os << ">";
  7473. }
  7474. } // namespace
  7475. namespace internal2 {
  7476. // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
  7477. // given object. The delegation simplifies the implementation, which
  7478. // uses the << operator and thus is easier done outside of the
  7479. // ::testing::internal namespace, which contains a << operator that
  7480. // sometimes conflicts with the one in STL.
  7481. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
  7482. ostream* os) {
  7483. PrintBytesInObjectToImpl(obj_bytes, count, os);
  7484. }
  7485. } // namespace internal2
  7486. namespace internal {
  7487. // Depending on the value of a char (or wchar_t), we print it in one
  7488. // of three formats:
  7489. // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
  7490. // - as a hexidecimal escape sequence (e.g. '\x7F'), or
  7491. // - as a special escape sequence (e.g. '\r', '\n').
  7492. enum CharFormat {
  7493. kAsIs,
  7494. kHexEscape,
  7495. kSpecialEscape
  7496. };
  7497. // Returns true if c is a printable ASCII character. We test the
  7498. // value of c directly instead of calling isprint(), which is buggy on
  7499. // Windows Mobile.
  7500. inline bool IsPrintableAscii(wchar_t c) {
  7501. return 0x20 <= c && c <= 0x7E;
  7502. }
  7503. // Prints a wide or narrow char c as a character literal without the
  7504. // quotes, escaping it when necessary; returns how c was formatted.
  7505. // The template argument UnsignedChar is the unsigned version of Char,
  7506. // which is the type of c.
  7507. template <typename UnsignedChar, typename Char>
  7508. static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
  7509. switch (static_cast<wchar_t>(c)) {
  7510. case L'\0':
  7511. *os << "\\0";
  7512. break;
  7513. case L'\'':
  7514. *os << "\\'";
  7515. break;
  7516. case L'\\':
  7517. *os << "\\\\";
  7518. break;
  7519. case L'\a':
  7520. *os << "\\a";
  7521. break;
  7522. case L'\b':
  7523. *os << "\\b";
  7524. break;
  7525. case L'\f':
  7526. *os << "\\f";
  7527. break;
  7528. case L'\n':
  7529. *os << "\\n";
  7530. break;
  7531. case L'\r':
  7532. *os << "\\r";
  7533. break;
  7534. case L'\t':
  7535. *os << "\\t";
  7536. break;
  7537. case L'\v':
  7538. *os << "\\v";
  7539. break;
  7540. default:
  7541. if (IsPrintableAscii(c)) {
  7542. *os << static_cast<char>(c);
  7543. return kAsIs;
  7544. } else {
  7545. *os << String::Format("\\x%X", static_cast<UnsignedChar>(c));
  7546. return kHexEscape;
  7547. }
  7548. }
  7549. return kSpecialEscape;
  7550. }
  7551. // Prints a char c as if it's part of a string literal, escaping it when
  7552. // necessary; returns how c was formatted.
  7553. static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) {
  7554. switch (c) {
  7555. case L'\'':
  7556. *os << "'";
  7557. return kAsIs;
  7558. case L'"':
  7559. *os << "\\\"";
  7560. return kSpecialEscape;
  7561. default:
  7562. return PrintAsCharLiteralTo<wchar_t>(c, os);
  7563. }
  7564. }
  7565. // Prints a char c as if it's part of a string literal, escaping it when
  7566. // necessary; returns how c was formatted.
  7567. static CharFormat PrintAsNarrowStringLiteralTo(char c, ostream* os) {
  7568. return PrintAsWideStringLiteralTo(static_cast<unsigned char>(c), os);
  7569. }
  7570. // Prints a wide or narrow character c and its code. '\0' is printed
  7571. // as "'\\0'", other unprintable characters are also properly escaped
  7572. // using the standard C++ escape sequence. The template argument
  7573. // UnsignedChar is the unsigned version of Char, which is the type of c.
  7574. template <typename UnsignedChar, typename Char>
  7575. void PrintCharAndCodeTo(Char c, ostream* os) {
  7576. // First, print c as a literal in the most readable form we can find.
  7577. *os << ((sizeof(c) > 1) ? "L'" : "'");
  7578. const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
  7579. *os << "'";
  7580. // To aid user debugging, we also print c's code in decimal, unless
  7581. // it's 0 (in which case c was printed as '\\0', making the code
  7582. // obvious).
  7583. if (c == 0)
  7584. return;
  7585. *os << " (" << String::Format("%d", c).c_str();
  7586. // For more convenience, we print c's code again in hexidecimal,
  7587. // unless c was already printed in the form '\x##' or the code is in
  7588. // [1, 9].
  7589. if (format == kHexEscape || (1 <= c && c <= 9)) {
  7590. // Do nothing.
  7591. } else {
  7592. *os << String::Format(", 0x%X",
  7593. static_cast<UnsignedChar>(c)).c_str();
  7594. }
  7595. *os << ")";
  7596. }
  7597. void PrintTo(unsigned char c, ::std::ostream* os) {
  7598. PrintCharAndCodeTo<unsigned char>(c, os);
  7599. }
  7600. void PrintTo(signed char c, ::std::ostream* os) {
  7601. PrintCharAndCodeTo<unsigned char>(c, os);
  7602. }
  7603. // Prints a wchar_t as a symbol if it is printable or as its internal
  7604. // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
  7605. void PrintTo(wchar_t wc, ostream* os) {
  7606. PrintCharAndCodeTo<wchar_t>(wc, os);
  7607. }
  7608. // Prints the given array of characters to the ostream.
  7609. // The array starts at *begin, the length is len, it may include '\0' characters
  7610. // and may not be null-terminated.
  7611. static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) {
  7612. *os << "\"";
  7613. bool is_previous_hex = false;
  7614. for (size_t index = 0; index < len; ++index) {
  7615. const char cur = begin[index];
  7616. if (is_previous_hex && IsXDigit(cur)) {
  7617. // Previous character is of '\x..' form and this character can be
  7618. // interpreted as another hexadecimal digit in its number. Break string to
  7619. // disambiguate.
  7620. *os << "\" \"";
  7621. }
  7622. is_previous_hex = PrintAsNarrowStringLiteralTo(cur, os) == kHexEscape;
  7623. }
  7624. *os << "\"";
  7625. }
  7626. // Prints a (const) char array of 'len' elements, starting at address 'begin'.
  7627. void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
  7628. PrintCharsAsStringTo(begin, len, os);
  7629. }
  7630. // Prints the given array of wide characters to the ostream.
  7631. // The array starts at *begin, the length is len, it may include L'\0'
  7632. // characters and may not be null-terminated.
  7633. static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len,
  7634. ostream* os) {
  7635. *os << "L\"";
  7636. bool is_previous_hex = false;
  7637. for (size_t index = 0; index < len; ++index) {
  7638. const wchar_t cur = begin[index];
  7639. if (is_previous_hex && isascii(cur) && IsXDigit(static_cast<char>(cur))) {
  7640. // Previous character is of '\x..' form and this character can be
  7641. // interpreted as another hexadecimal digit in its number. Break string to
  7642. // disambiguate.
  7643. *os << "\" L\"";
  7644. }
  7645. is_previous_hex = PrintAsWideStringLiteralTo(cur, os) == kHexEscape;
  7646. }
  7647. *os << "\"";
  7648. }
  7649. // Prints the given C string to the ostream.
  7650. void PrintTo(const char* s, ostream* os) {
  7651. if (s == NULL) {
  7652. *os << "NULL";
  7653. } else {
  7654. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  7655. PrintCharsAsStringTo(s, strlen(s), os);
  7656. }
  7657. }
  7658. // MSVC compiler can be configured to define whar_t as a typedef
  7659. // of unsigned short. Defining an overload for const wchar_t* in that case
  7660. // would cause pointers to unsigned shorts be printed as wide strings,
  7661. // possibly accessing more memory than intended and causing invalid
  7662. // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
  7663. // wchar_t is implemented as a native type.
  7664. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  7665. // Prints the given wide C string to the ostream.
  7666. void PrintTo(const wchar_t* s, ostream* os) {
  7667. if (s == NULL) {
  7668. *os << "NULL";
  7669. } else {
  7670. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  7671. PrintWideCharsAsStringTo(s, wcslen(s), os);
  7672. }
  7673. }
  7674. #endif // wchar_t is native
  7675. // Prints a ::string object.
  7676. #if GTEST_HAS_GLOBAL_STRING
  7677. void PrintStringTo(const ::string& s, ostream* os) {
  7678. PrintCharsAsStringTo(s.data(), s.size(), os);
  7679. }
  7680. #endif // GTEST_HAS_GLOBAL_STRING
  7681. void PrintStringTo(const ::std::string& s, ostream* os) {
  7682. PrintCharsAsStringTo(s.data(), s.size(), os);
  7683. }
  7684. // Prints a ::wstring object.
  7685. #if GTEST_HAS_GLOBAL_WSTRING
  7686. void PrintWideStringTo(const ::wstring& s, ostream* os) {
  7687. PrintWideCharsAsStringTo(s.data(), s.size(), os);
  7688. }
  7689. #endif // GTEST_HAS_GLOBAL_WSTRING
  7690. #if GTEST_HAS_STD_WSTRING
  7691. void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
  7692. PrintWideCharsAsStringTo(s.data(), s.size(), os);
  7693. }
  7694. #endif // GTEST_HAS_STD_WSTRING
  7695. } // namespace internal
  7696. } // namespace testing
  7697. // Copyright 2008, Google Inc.
  7698. // All rights reserved.
  7699. //
  7700. // Redistribution and use in source and binary forms, with or without
  7701. // modification, are permitted provided that the following conditions are
  7702. // met:
  7703. //
  7704. // * Redistributions of source code must retain the above copyright
  7705. // notice, this list of conditions and the following disclaimer.
  7706. // * Redistributions in binary form must reproduce the above
  7707. // copyright notice, this list of conditions and the following disclaimer
  7708. // in the documentation and/or other materials provided with the
  7709. // distribution.
  7710. // * Neither the name of Google Inc. nor the names of its
  7711. // contributors may be used to endorse or promote products derived from
  7712. // this software without specific prior written permission.
  7713. //
  7714. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7715. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7716. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7717. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7718. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7719. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7720. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7721. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7722. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7723. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7724. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7725. //
  7726. // Author: [email protected] (Markus Heule)
  7727. //
  7728. // The Google C++ Testing Framework (Google Test)
  7729. // Indicates that this translation unit is part of Google Test's
  7730. // implementation. It must come before gtest-internal-inl.h is
  7731. // included, or there will be a compiler error. This trick is to
  7732. // prevent a user from accidentally including gtest-internal-inl.h in
  7733. // his code.
  7734. #define GTEST_IMPLEMENTATION_ 1
  7735. #undef GTEST_IMPLEMENTATION_
  7736. namespace testing {
  7737. using internal::GetUnitTestImpl;
  7738. // Gets the summary of the failure message by omitting the stack trace
  7739. // in it.
  7740. internal::String TestPartResult::ExtractSummary(const char* message) {
  7741. const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
  7742. return stack_trace == NULL ? internal::String(message) :
  7743. internal::String(message, stack_trace - message);
  7744. }
  7745. // Prints a TestPartResult object.
  7746. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
  7747. return os
  7748. << result.file_name() << ":" << result.line_number() << ": "
  7749. << (result.type() == TestPartResult::kSuccess ? "Success" :
  7750. result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
  7751. "Non-fatal failure") << ":\n"
  7752. << result.message() << std::endl;
  7753. }
  7754. // Appends a TestPartResult to the array.
  7755. void TestPartResultArray::Append(const TestPartResult& result) {
  7756. array_.push_back(result);
  7757. }
  7758. // Returns the TestPartResult at the given index (0-based).
  7759. const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
  7760. if (index < 0 || index >= size()) {
  7761. printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
  7762. internal::posix::Abort();
  7763. }
  7764. return array_[index];
  7765. }
  7766. // Returns the number of TestPartResult objects in the array.
  7767. int TestPartResultArray::size() const {
  7768. return static_cast<int>(array_.size());
  7769. }
  7770. namespace internal {
  7771. HasNewFatalFailureHelper::HasNewFatalFailureHelper()
  7772. : has_new_fatal_failure_(false),
  7773. original_reporter_(GetUnitTestImpl()->
  7774. GetTestPartResultReporterForCurrentThread()) {
  7775. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
  7776. }
  7777. HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
  7778. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
  7779. original_reporter_);
  7780. }
  7781. void HasNewFatalFailureHelper::ReportTestPartResult(
  7782. const TestPartResult& result) {
  7783. if (result.fatally_failed())
  7784. has_new_fatal_failure_ = true;
  7785. original_reporter_->ReportTestPartResult(result);
  7786. }
  7787. } // namespace internal
  7788. } // namespace testing
  7789. // Copyright 2008 Google Inc.
  7790. // All Rights Reserved.
  7791. //
  7792. // Redistribution and use in source and binary forms, with or without
  7793. // modification, are permitted provided that the following conditions are
  7794. // met:
  7795. //
  7796. // * Redistributions of source code must retain the above copyright
  7797. // notice, this list of conditions and the following disclaimer.
  7798. // * Redistributions in binary form must reproduce the above
  7799. // copyright notice, this list of conditions and the following disclaimer
  7800. // in the documentation and/or other materials provided with the
  7801. // distribution.
  7802. // * Neither the name of Google Inc. nor the names of its
  7803. // contributors may be used to endorse or promote products derived from
  7804. // this software without specific prior written permission.
  7805. //
  7806. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7807. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7808. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7809. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7810. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7811. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7812. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7813. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7814. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7815. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7816. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7817. //
  7818. // Author: [email protected] (Zhanyong Wan)
  7819. namespace testing {
  7820. namespace internal {
  7821. #if GTEST_HAS_TYPED_TEST_P
  7822. // Skips to the first non-space char in str. Returns an empty string if str
  7823. // contains only whitespace characters.
  7824. static const char* SkipSpaces(const char* str) {
  7825. while (IsSpace(*str))
  7826. str++;
  7827. return str;
  7828. }
  7829. // Verifies that registered_tests match the test names in
  7830. // defined_test_names_; returns registered_tests if successful, or
  7831. // aborts the program otherwise.
  7832. const char* TypedTestCasePState::VerifyRegisteredTestNames(
  7833. const char* file, int line, const char* registered_tests) {
  7834. typedef ::std::set<const char*>::const_iterator DefinedTestIter;
  7835. registered_ = true;
  7836. // Skip initial whitespace in registered_tests since some
  7837. // preprocessors prefix stringizied literals with whitespace.
  7838. registered_tests = SkipSpaces(registered_tests);
  7839. Message errors;
  7840. ::std::set<String> tests;
  7841. for (const char* names = registered_tests; names != NULL;
  7842. names = SkipComma(names)) {
  7843. const String name = GetPrefixUntilComma(names);
  7844. if (tests.count(name) != 0) {
  7845. errors << "Test " << name << " is listed more than once.\n";
  7846. continue;
  7847. }
  7848. bool found = false;
  7849. for (DefinedTestIter it = defined_test_names_.begin();
  7850. it != defined_test_names_.end();
  7851. ++it) {
  7852. if (name == *it) {
  7853. found = true;
  7854. break;
  7855. }
  7856. }
  7857. if (found) {
  7858. tests.insert(name);
  7859. } else {
  7860. errors << "No test named " << name
  7861. << " can be found in this test case.\n";
  7862. }
  7863. }
  7864. for (DefinedTestIter it = defined_test_names_.begin();
  7865. it != defined_test_names_.end();
  7866. ++it) {
  7867. if (tests.count(*it) == 0) {
  7868. errors << "You forgot to list test " << *it << ".\n";
  7869. }
  7870. }
  7871. const String& errors_str = errors.GetString();
  7872. if (errors_str != "") {
  7873. fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
  7874. errors_str.c_str());
  7875. fflush(stderr);
  7876. posix::Abort();
  7877. }
  7878. return registered_tests;
  7879. }
  7880. #endif // GTEST_HAS_TYPED_TEST_P
  7881. } // namespace internal
  7882. } // namespace testing
  7883. #if __clang__
  7884. #pragma clang diagnostic pop
  7885. #elif __GNUC__
  7886. #pragma GCC diagnostic pop
  7887. #endif