gtest-all.cc 346 KB

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