gtest-all.cc 346 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599
  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. // The line below is to avoid ICPC warning #177: this class constructor
  3194. // never used.
  3195. TestNameIs t("");
  3196. return test_info && test_info->name() == name_;
  3197. }
  3198. private:
  3199. std::string name_;
  3200. };
  3201. } // namespace
  3202. namespace internal {
  3203. // This method expands all parameterized tests registered with macros TEST_P
  3204. // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
  3205. // This will be done just once during the program runtime.
  3206. void UnitTestImpl::RegisterParameterizedTests() {
  3207. #if GTEST_HAS_PARAM_TEST
  3208. if (!parameterized_tests_registered_) {
  3209. parameterized_test_registry_.RegisterTests();
  3210. parameterized_tests_registered_ = true;
  3211. }
  3212. #endif
  3213. }
  3214. } // namespace internal
  3215. // Creates the test object, runs it, records its result, and then
  3216. // deletes it.
  3217. void TestInfo::Run() {
  3218. if (!should_run_) return;
  3219. // Tells UnitTest where to store test result.
  3220. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3221. impl->set_current_test_info(this);
  3222. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3223. // Notifies the unit test event listeners that a test is about to start.
  3224. repeater->OnTestStart(*this);
  3225. const TimeInMillis start = internal::GetTimeInMillis();
  3226. impl->os_stack_trace_getter()->UponLeavingGTest();
  3227. // Creates the test object.
  3228. Test* const test = internal::HandleExceptionsInMethodIfSupported(
  3229. factory_, &internal::TestFactoryBase::CreateTest,
  3230. "the test fixture's constructor");
  3231. // Runs the test only if the test object was created and its
  3232. // constructor didn't generate a fatal failure.
  3233. if ((test != NULL) && !Test::HasFatalFailure()) {
  3234. // This doesn't throw as all user code that can throw are wrapped into
  3235. // exception handling code.
  3236. test->Run();
  3237. }
  3238. // Deletes the test object.
  3239. impl->os_stack_trace_getter()->UponLeavingGTest();
  3240. internal::HandleExceptionsInMethodIfSupported(
  3241. test, &Test::DeleteSelf_, "the test fixture's destructor");
  3242. result_.set_elapsed_time(internal::GetTimeInMillis() - start);
  3243. // Notifies the unit test event listener that a test has just finished.
  3244. repeater->OnTestEnd(*this);
  3245. // Tells UnitTest to stop associating assertion results to this
  3246. // test.
  3247. impl->set_current_test_info(NULL);
  3248. }
  3249. // class TestCase
  3250. // Gets the number of successful tests in this test case.
  3251. int TestCase::successful_test_count() const {
  3252. return CountIf(test_info_list_, TestPassed);
  3253. }
  3254. // Gets the number of failed tests in this test case.
  3255. int TestCase::failed_test_count() const {
  3256. return CountIf(test_info_list_, TestFailed);
  3257. }
  3258. // Gets the number of disabled tests that will be reported in the XML report.
  3259. int TestCase::reportable_disabled_test_count() const {
  3260. return CountIf(test_info_list_, TestReportableDisabled);
  3261. }
  3262. // Gets the number of disabled tests in this test case.
  3263. int TestCase::disabled_test_count() const {
  3264. return CountIf(test_info_list_, TestDisabled);
  3265. }
  3266. // Gets the number of tests to be printed in the XML report.
  3267. int TestCase::reportable_test_count() const {
  3268. return CountIf(test_info_list_, TestReportable);
  3269. }
  3270. // Get the number of tests in this test case that should run.
  3271. int TestCase::test_to_run_count() const {
  3272. return CountIf(test_info_list_, ShouldRunTest);
  3273. }
  3274. // Gets the number of all tests.
  3275. int TestCase::total_test_count() const {
  3276. return static_cast<int>(test_info_list_.size());
  3277. }
  3278. // Creates a TestCase with the given name.
  3279. //
  3280. // Arguments:
  3281. //
  3282. // name: name of the test case
  3283. // a_type_param: the name of the test case's type parameter, or NULL if
  3284. // this is not a typed or a type-parameterized test case.
  3285. // set_up_tc: pointer to the function that sets up the test case
  3286. // tear_down_tc: pointer to the function that tears down the test case
  3287. TestCase::TestCase(const char* a_name, const char* a_type_param,
  3288. Test::SetUpTestCaseFunc set_up_tc,
  3289. Test::TearDownTestCaseFunc tear_down_tc)
  3290. : name_(a_name),
  3291. type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  3292. set_up_tc_(set_up_tc),
  3293. tear_down_tc_(tear_down_tc),
  3294. should_run_(false),
  3295. elapsed_time_(0) {
  3296. }
  3297. // Destructor of TestCase.
  3298. TestCase::~TestCase() {
  3299. // Deletes every Test in the collection.
  3300. ForEach(test_info_list_, internal::Delete<TestInfo>);
  3301. }
  3302. // Returns the i-th test among all the tests. i can range from 0 to
  3303. // total_test_count() - 1. If i is not in that range, returns NULL.
  3304. const TestInfo* TestCase::GetTestInfo(int i) const {
  3305. const int index = GetElementOr(test_indices_, i, -1);
  3306. return index < 0 ? NULL : test_info_list_[index];
  3307. }
  3308. // Returns the i-th test among all the tests. i can range from 0 to
  3309. // total_test_count() - 1. If i is not in that range, returns NULL.
  3310. TestInfo* TestCase::GetMutableTestInfo(int i) {
  3311. const int index = GetElementOr(test_indices_, i, -1);
  3312. return index < 0 ? NULL : test_info_list_[index];
  3313. }
  3314. // Adds a test to this test case. Will delete the test upon
  3315. // destruction of the TestCase object.
  3316. void TestCase::AddTestInfo(TestInfo * test_info) {
  3317. test_info_list_.push_back(test_info);
  3318. test_indices_.push_back(static_cast<int>(test_indices_.size()));
  3319. }
  3320. // Runs every test in this TestCase.
  3321. void TestCase::Run() {
  3322. if (!should_run_) return;
  3323. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3324. impl->set_current_test_case(this);
  3325. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3326. repeater->OnTestCaseStart(*this);
  3327. impl->os_stack_trace_getter()->UponLeavingGTest();
  3328. internal::HandleExceptionsInMethodIfSupported(
  3329. this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
  3330. const internal::TimeInMillis start = internal::GetTimeInMillis();
  3331. for (int i = 0; i < total_test_count(); i++) {
  3332. GetMutableTestInfo(i)->Run();
  3333. }
  3334. elapsed_time_ = internal::GetTimeInMillis() - start;
  3335. impl->os_stack_trace_getter()->UponLeavingGTest();
  3336. internal::HandleExceptionsInMethodIfSupported(
  3337. this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
  3338. repeater->OnTestCaseEnd(*this);
  3339. impl->set_current_test_case(NULL);
  3340. }
  3341. // Clears the results of all tests in this test case.
  3342. void TestCase::ClearResult() {
  3343. ad_hoc_test_result_.Clear();
  3344. ForEach(test_info_list_, TestInfo::ClearTestResult);
  3345. }
  3346. // Shuffles the tests in this test case.
  3347. void TestCase::ShuffleTests(internal::Random* random) {
  3348. Shuffle(random, &test_indices_);
  3349. }
  3350. // Restores the test order to before the first shuffle.
  3351. void TestCase::UnshuffleTests() {
  3352. for (size_t i = 0; i < test_indices_.size(); i++) {
  3353. test_indices_[i] = static_cast<int>(i);
  3354. }
  3355. }
  3356. // Formats a countable noun. Depending on its quantity, either the
  3357. // singular form or the plural form is used. e.g.
  3358. //
  3359. // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
  3360. // FormatCountableNoun(5, "book", "books") returns "5 books".
  3361. static std::string FormatCountableNoun(int count,
  3362. const char * singular_form,
  3363. const char * plural_form) {
  3364. return internal::StreamableToString(count) + " " +
  3365. (count == 1 ? singular_form : plural_form);
  3366. }
  3367. // Formats the count of tests.
  3368. static std::string FormatTestCount(int test_count) {
  3369. return FormatCountableNoun(test_count, "test", "tests");
  3370. }
  3371. // Formats the count of test cases.
  3372. static std::string FormatTestCaseCount(int test_case_count) {
  3373. return FormatCountableNoun(test_case_count, "test case", "test cases");
  3374. }
  3375. // Converts a TestPartResult::Type enum to human-friendly string
  3376. // representation. Both kNonFatalFailure and kFatalFailure are translated
  3377. // to "Failure", as the user usually doesn't care about the difference
  3378. // between the two when viewing the test result.
  3379. static const char * TestPartResultTypeToString(TestPartResult::Type type) {
  3380. switch (type) {
  3381. case TestPartResult::kSuccess:
  3382. return "Success";
  3383. case TestPartResult::kNonFatalFailure:
  3384. case TestPartResult::kFatalFailure:
  3385. #ifdef _MSC_VER
  3386. return "error: ";
  3387. #else
  3388. return "Failure\n";
  3389. #endif
  3390. default:
  3391. return "Unknown result type";
  3392. }
  3393. }
  3394. namespace internal {
  3395. // Prints a TestPartResult to an std::string.
  3396. static std::string PrintTestPartResultToString(
  3397. const TestPartResult& test_part_result) {
  3398. return (Message()
  3399. << internal::FormatFileLocation(test_part_result.file_name(),
  3400. test_part_result.line_number())
  3401. << " " << TestPartResultTypeToString(test_part_result.type())
  3402. << test_part_result.message()).GetString();
  3403. }
  3404. // Prints a TestPartResult.
  3405. static void PrintTestPartResult(const TestPartResult& test_part_result) {
  3406. const std::string& result =
  3407. PrintTestPartResultToString(test_part_result);
  3408. printf("%s\n", result.c_str());
  3409. fflush(stdout);
  3410. // If the test program runs in Visual Studio or a debugger, the
  3411. // following statements add the test part result message to the Output
  3412. // window such that the user can double-click on it to jump to the
  3413. // corresponding source code location; otherwise they do nothing.
  3414. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3415. // We don't call OutputDebugString*() on Windows Mobile, as printing
  3416. // to stdout is done by OutputDebugString() there already - we don't
  3417. // want the same message printed twice.
  3418. ::OutputDebugStringA(result.c_str());
  3419. ::OutputDebugStringA("\n");
  3420. #endif
  3421. }
  3422. // class PrettyUnitTestResultPrinter
  3423. enum GTestColor {
  3424. COLOR_DEFAULT,
  3425. COLOR_RED,
  3426. COLOR_GREEN,
  3427. COLOR_YELLOW
  3428. };
  3429. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3430. // Returns the character attribute for the given color.
  3431. WORD GetColorAttribute(GTestColor color) {
  3432. switch (color) {
  3433. case COLOR_RED: return FOREGROUND_RED;
  3434. case COLOR_GREEN: return FOREGROUND_GREEN;
  3435. case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
  3436. default: return 0;
  3437. }
  3438. }
  3439. #else
  3440. // Returns the ANSI color code for the given color. COLOR_DEFAULT is
  3441. // an invalid input.
  3442. const char* GetAnsiColorCode(GTestColor color) {
  3443. switch (color) {
  3444. case COLOR_RED: return "1";
  3445. case COLOR_GREEN: return "2";
  3446. case COLOR_YELLOW: return "3";
  3447. default: return NULL;
  3448. };
  3449. }
  3450. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3451. // Returns true iff Google Test should use colors in the output.
  3452. bool ShouldUseColor(bool stdout_is_tty) {
  3453. const char* const gtest_color = GTEST_FLAG(color).c_str();
  3454. if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
  3455. #if GTEST_OS_WINDOWS
  3456. // On Windows the TERM variable is usually not set, but the
  3457. // console there does support colors.
  3458. return stdout_is_tty;
  3459. #else
  3460. // On non-Windows platforms, we rely on the TERM variable.
  3461. const char* const term = posix::GetEnv("TERM");
  3462. const bool term_supports_color =
  3463. String::CStringEquals(term, "xterm") ||
  3464. String::CStringEquals(term, "xterm-color") ||
  3465. String::CStringEquals(term, "xterm-256color") ||
  3466. String::CStringEquals(term, "screen") ||
  3467. String::CStringEquals(term, "screen-256color") ||
  3468. String::CStringEquals(term, "linux") ||
  3469. String::CStringEquals(term, "cygwin");
  3470. return stdout_is_tty && term_supports_color;
  3471. #endif // GTEST_OS_WINDOWS
  3472. }
  3473. return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
  3474. String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
  3475. String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
  3476. String::CStringEquals(gtest_color, "1");
  3477. // We take "yes", "true", "t", and "1" as meaning "yes". If the
  3478. // value is neither one of these nor "auto", we treat it as "no" to
  3479. // be conservative.
  3480. }
  3481. // Helpers for printing colored strings to stdout. Note that on Windows, we
  3482. // cannot simply emit special characters and have the terminal change colors.
  3483. // This routine must actually emit the characters rather than return a string
  3484. // that would be colored when printed, as can be done on Linux.
  3485. void ColoredPrintf(GTestColor color, const char* fmt, ...) {
  3486. va_list args;
  3487. va_start(args, fmt);
  3488. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
  3489. const bool use_color = false;
  3490. #else
  3491. static const bool in_color_mode =
  3492. ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
  3493. const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
  3494. #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
  3495. // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
  3496. if (!use_color) {
  3497. vprintf(fmt, args);
  3498. va_end(args);
  3499. return;
  3500. }
  3501. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3502. const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  3503. // Gets the current text color.
  3504. CONSOLE_SCREEN_BUFFER_INFO buffer_info;
  3505. GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
  3506. const WORD old_color_attrs = buffer_info.wAttributes;
  3507. // We need to flush the stream buffers into the console before each
  3508. // SetConsoleTextAttribute call lest it affect the text that is already
  3509. // printed but has not yet reached the console.
  3510. fflush(stdout);
  3511. SetConsoleTextAttribute(stdout_handle,
  3512. GetColorAttribute(color) | FOREGROUND_INTENSITY);
  3513. vprintf(fmt, args);
  3514. fflush(stdout);
  3515. // Restores the text color.
  3516. SetConsoleTextAttribute(stdout_handle, old_color_attrs);
  3517. #else
  3518. printf("\033[0;3%sm", GetAnsiColorCode(color));
  3519. vprintf(fmt, args);
  3520. printf("\033[m"); // Resets the terminal to default.
  3521. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3522. va_end(args);
  3523. }
  3524. // Text printed in Google Test's text output and --gunit_list_tests
  3525. // output to label the type parameter and value parameter for a test.
  3526. static const char kTypeParamLabel[] = "TypeParam";
  3527. static const char kValueParamLabel[] = "GetParam()";
  3528. void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
  3529. const char* const type_param = test_info.type_param();
  3530. const char* const value_param = test_info.value_param();
  3531. if (type_param != NULL || value_param != NULL) {
  3532. printf(", where ");
  3533. if (type_param != NULL) {
  3534. printf("%s = %s", kTypeParamLabel, type_param);
  3535. if (value_param != NULL)
  3536. printf(" and ");
  3537. }
  3538. if (value_param != NULL) {
  3539. printf("%s = %s", kValueParamLabel, value_param);
  3540. }
  3541. }
  3542. }
  3543. // This class implements the TestEventListener interface.
  3544. //
  3545. // Class PrettyUnitTestResultPrinter is copyable.
  3546. class PrettyUnitTestResultPrinter : public TestEventListener {
  3547. public:
  3548. PrettyUnitTestResultPrinter() {}
  3549. static void PrintTestName(const char * test_case, const char * test) {
  3550. printf("%s.%s", test_case, test);
  3551. }
  3552. // The following methods override what's in the TestEventListener class.
  3553. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
  3554. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  3555. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  3556. virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
  3557. virtual void OnTestCaseStart(const TestCase& test_case);
  3558. virtual void OnTestStart(const TestInfo& test_info);
  3559. virtual void OnTestPartResult(const TestPartResult& result);
  3560. virtual void OnTestEnd(const TestInfo& test_info);
  3561. virtual void OnTestCaseEnd(const TestCase& test_case);
  3562. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  3563. virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
  3564. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3565. virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
  3566. private:
  3567. static void PrintFailedTests(const UnitTest& unit_test);
  3568. };
  3569. // Fired before each iteration of tests starts.
  3570. void PrettyUnitTestResultPrinter::OnTestIterationStart(
  3571. const UnitTest& unit_test, int iteration) {
  3572. if (GTEST_FLAG(repeat) != 1)
  3573. printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
  3574. const char* const filter = GTEST_FLAG(filter).c_str();
  3575. // Prints the filter if it's not *. This reminds the user that some
  3576. // tests may be skipped.
  3577. if (!String::CStringEquals(filter, kUniversalFilter)) {
  3578. ColoredPrintf(COLOR_YELLOW,
  3579. "Note: %s filter = %s\n", GTEST_NAME_, filter);
  3580. }
  3581. if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
  3582. const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
  3583. ColoredPrintf(COLOR_YELLOW,
  3584. "Note: This is test shard %d of %s.\n",
  3585. static_cast<int>(shard_index) + 1,
  3586. internal::posix::GetEnv(kTestTotalShards));
  3587. }
  3588. if (GTEST_FLAG(shuffle)) {
  3589. ColoredPrintf(COLOR_YELLOW,
  3590. "Note: Randomizing tests' orders with a seed of %d .\n",
  3591. unit_test.random_seed());
  3592. }
  3593. ColoredPrintf(COLOR_GREEN, "[==========] ");
  3594. printf("Running %s from %s.\n",
  3595. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  3596. FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  3597. fflush(stdout);
  3598. }
  3599. void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
  3600. const UnitTest& /*unit_test*/) {
  3601. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3602. printf("Global test environment set-up.\n");
  3603. fflush(stdout);
  3604. }
  3605. void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
  3606. const std::string counts =
  3607. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  3608. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3609. printf("%s from %s", counts.c_str(), test_case.name());
  3610. if (test_case.type_param() == NULL) {
  3611. printf("\n");
  3612. } else {
  3613. printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
  3614. }
  3615. fflush(stdout);
  3616. }
  3617. void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
  3618. ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
  3619. PrintTestName(test_info.test_case_name(), test_info.name());
  3620. printf("\n");
  3621. fflush(stdout);
  3622. }
  3623. // Called after an assertion failure.
  3624. void PrettyUnitTestResultPrinter::OnTestPartResult(
  3625. const TestPartResult& result) {
  3626. // If the test part succeeded, we don't need to do anything.
  3627. if (result.type() == TestPartResult::kSuccess)
  3628. return;
  3629. // Print failure message from the assertion (e.g. expected this and got that).
  3630. PrintTestPartResult(result);
  3631. fflush(stdout);
  3632. }
  3633. void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  3634. if (test_info.result()->Passed()) {
  3635. ColoredPrintf(COLOR_GREEN, "[ OK ] ");
  3636. } else {
  3637. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  3638. }
  3639. PrintTestName(test_info.test_case_name(), test_info.name());
  3640. if (test_info.result()->Failed())
  3641. PrintFullTestCommentIfPresent(test_info);
  3642. if (GTEST_FLAG(print_time)) {
  3643. printf(" (%s ms)\n", internal::StreamableToString(
  3644. test_info.result()->elapsed_time()).c_str());
  3645. } else {
  3646. printf("\n");
  3647. }
  3648. fflush(stdout);
  3649. }
  3650. void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
  3651. if (!GTEST_FLAG(print_time)) return;
  3652. const std::string counts =
  3653. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  3654. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3655. printf("%s from %s (%s ms total)\n\n",
  3656. counts.c_str(), test_case.name(),
  3657. internal::StreamableToString(test_case.elapsed_time()).c_str());
  3658. fflush(stdout);
  3659. }
  3660. void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
  3661. const UnitTest& /*unit_test*/) {
  3662. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3663. printf("Global test environment tear-down\n");
  3664. fflush(stdout);
  3665. }
  3666. // Internal helper for printing the list of failed tests.
  3667. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
  3668. const int failed_test_count = unit_test.failed_test_count();
  3669. if (failed_test_count == 0) {
  3670. return;
  3671. }
  3672. for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  3673. const TestCase& test_case = *unit_test.GetTestCase(i);
  3674. if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
  3675. continue;
  3676. }
  3677. for (int j = 0; j < test_case.total_test_count(); ++j) {
  3678. const TestInfo& test_info = *test_case.GetTestInfo(j);
  3679. if (!test_info.should_run() || test_info.result()->Passed()) {
  3680. continue;
  3681. }
  3682. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  3683. printf("%s.%s", test_case.name(), test_info.name());
  3684. PrintFullTestCommentIfPresent(test_info);
  3685. printf("\n");
  3686. }
  3687. }
  3688. }
  3689. void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  3690. int /*iteration*/) {
  3691. ColoredPrintf(COLOR_GREEN, "[==========] ");
  3692. printf("%s from %s ran.",
  3693. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  3694. FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  3695. if (GTEST_FLAG(print_time)) {
  3696. printf(" (%s ms total)",
  3697. internal::StreamableToString(unit_test.elapsed_time()).c_str());
  3698. }
  3699. printf("\n");
  3700. ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
  3701. printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  3702. int num_failures = unit_test.failed_test_count();
  3703. if (!unit_test.Passed()) {
  3704. const int failed_test_count = unit_test.failed_test_count();
  3705. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  3706. printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
  3707. PrintFailedTests(unit_test);
  3708. printf("\n%2d FAILED %s\n", num_failures,
  3709. num_failures == 1 ? "TEST" : "TESTS");
  3710. }
  3711. int num_disabled = unit_test.reportable_disabled_test_count();
  3712. if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
  3713. if (!num_failures) {
  3714. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
  3715. }
  3716. ColoredPrintf(COLOR_YELLOW,
  3717. " YOU HAVE %d DISABLED %s\n\n",
  3718. num_disabled,
  3719. num_disabled == 1 ? "TEST" : "TESTS");
  3720. }
  3721. // Ensure that Google Test output is printed before, e.g., heapchecker output.
  3722. fflush(stdout);
  3723. }
  3724. // End PrettyUnitTestResultPrinter
  3725. // class TestEventRepeater
  3726. //
  3727. // This class forwards events to other event listeners.
  3728. class TestEventRepeater : public TestEventListener {
  3729. public:
  3730. TestEventRepeater() : forwarding_enabled_(true) {}
  3731. virtual ~TestEventRepeater();
  3732. void Append(TestEventListener *listener);
  3733. TestEventListener* Release(TestEventListener* listener);
  3734. // Controls whether events will be forwarded to listeners_. Set to false
  3735. // in death test child processes.
  3736. bool forwarding_enabled() const { return forwarding_enabled_; }
  3737. void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
  3738. virtual void OnTestProgramStart(const UnitTest& unit_test);
  3739. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  3740. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  3741. virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
  3742. virtual void OnTestCaseStart(const TestCase& test_case);
  3743. virtual void OnTestStart(const TestInfo& test_info);
  3744. virtual void OnTestPartResult(const TestPartResult& result);
  3745. virtual void OnTestEnd(const TestInfo& test_info);
  3746. virtual void OnTestCaseEnd(const TestCase& test_case);
  3747. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  3748. virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
  3749. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3750. virtual void OnTestProgramEnd(const UnitTest& unit_test);
  3751. private:
  3752. // Controls whether events will be forwarded to listeners_. Set to false
  3753. // in death test child processes.
  3754. bool forwarding_enabled_;
  3755. // The list of listeners that receive events.
  3756. std::vector<TestEventListener*> listeners_;
  3757. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
  3758. };
  3759. TestEventRepeater::~TestEventRepeater() {
  3760. ForEach(listeners_, Delete<TestEventListener>);
  3761. }
  3762. void TestEventRepeater::Append(TestEventListener *listener) {
  3763. listeners_.push_back(listener);
  3764. }
  3765. // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
  3766. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
  3767. for (size_t i = 0; i < listeners_.size(); ++i) {
  3768. if (listeners_[i] == listener) {
  3769. listeners_.erase(listeners_.begin() + i);
  3770. return listener;
  3771. }
  3772. }
  3773. return NULL;
  3774. }
  3775. // Since most methods are very similar, use macros to reduce boilerplate.
  3776. // This defines a member that forwards the call to all listeners.
  3777. #define GTEST_REPEATER_METHOD_(Name, Type) \
  3778. void TestEventRepeater::Name(const Type& parameter) { \
  3779. if (forwarding_enabled_) { \
  3780. for (size_t i = 0; i < listeners_.size(); i++) { \
  3781. listeners_[i]->Name(parameter); \
  3782. } \
  3783. } \
  3784. }
  3785. // This defines a member that forwards the call to all listeners in reverse
  3786. // order.
  3787. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
  3788. void TestEventRepeater::Name(const Type& parameter) { \
  3789. if (forwarding_enabled_) { \
  3790. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
  3791. listeners_[i]->Name(parameter); \
  3792. } \
  3793. } \
  3794. }
  3795. GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
  3796. GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
  3797. GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
  3798. GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
  3799. GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
  3800. GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
  3801. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
  3802. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
  3803. GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
  3804. GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
  3805. GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
  3806. #undef GTEST_REPEATER_METHOD_
  3807. #undef GTEST_REVERSE_REPEATER_METHOD_
  3808. void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
  3809. int iteration) {
  3810. if (forwarding_enabled_) {
  3811. for (size_t i = 0; i < listeners_.size(); i++) {
  3812. listeners_[i]->OnTestIterationStart(unit_test, iteration);
  3813. }
  3814. }
  3815. }
  3816. void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
  3817. int iteration) {
  3818. if (forwarding_enabled_) {
  3819. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
  3820. listeners_[i]->OnTestIterationEnd(unit_test, iteration);
  3821. }
  3822. }
  3823. }
  3824. // End TestEventRepeater
  3825. // This class generates an XML output file.
  3826. class XmlUnitTestResultPrinter : public EmptyTestEventListener {
  3827. public:
  3828. explicit XmlUnitTestResultPrinter(const char* output_file);
  3829. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3830. private:
  3831. // Is c a whitespace character that is normalized to a space character
  3832. // when it appears in an XML attribute value?
  3833. static bool IsNormalizableWhitespace(char c) {
  3834. return c == 0x9 || c == 0xA || c == 0xD;
  3835. }
  3836. // May c appear in a well-formed XML document?
  3837. static bool IsValidXmlCharacter(char c) {
  3838. return IsNormalizableWhitespace(c) || c >= 0x20;
  3839. }
  3840. // Returns an XML-escaped copy of the input string str. If
  3841. // is_attribute is true, the text is meant to appear as an attribute
  3842. // value, and normalizable whitespace is preserved by replacing it
  3843. // with character references.
  3844. static std::string EscapeXml(const std::string& str, bool is_attribute);
  3845. // Returns the given string with all characters invalid in XML removed.
  3846. static std::string RemoveInvalidXmlCharacters(const std::string& str);
  3847. // Convenience wrapper around EscapeXml when str is an attribute value.
  3848. static std::string EscapeXmlAttribute(const std::string& str) {
  3849. return EscapeXml(str, true);
  3850. }
  3851. // Convenience wrapper around EscapeXml when str is not an attribute value.
  3852. static std::string EscapeXmlText(const char* str) {
  3853. return EscapeXml(str, false);
  3854. }
  3855. // Verifies that the given attribute belongs to the given element and
  3856. // streams the attribute as XML.
  3857. static void OutputXmlAttribute(std::ostream* stream,
  3858. const std::string& element_name,
  3859. const std::string& name,
  3860. const std::string& value);
  3861. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  3862. static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
  3863. // Streams an XML representation of a TestInfo object.
  3864. static void OutputXmlTestInfo(::std::ostream* stream,
  3865. const char* test_case_name,
  3866. const TestInfo& test_info);
  3867. // Prints an XML representation of a TestCase object
  3868. static void PrintXmlTestCase(::std::ostream* stream,
  3869. const TestCase& test_case);
  3870. // Prints an XML summary of unit_test to output stream out.
  3871. static void PrintXmlUnitTest(::std::ostream* stream,
  3872. const UnitTest& unit_test);
  3873. // Produces a string representing the test properties in a result as space
  3874. // delimited XML attributes based on the property key="value" pairs.
  3875. // When the std::string is not empty, it includes a space at the beginning,
  3876. // to delimit this attribute from prior attributes.
  3877. static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
  3878. // The output file.
  3879. const std::string output_file_;
  3880. GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
  3881. };
  3882. // Creates a new XmlUnitTestResultPrinter.
  3883. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
  3884. : output_file_(output_file) {
  3885. if (output_file_.c_str() == NULL || output_file_.empty()) {
  3886. fprintf(stderr, "XML output file may not be null\n");
  3887. fflush(stderr);
  3888. exit(EXIT_FAILURE);
  3889. }
  3890. }
  3891. // Called after the unit test ends.
  3892. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  3893. int /*iteration*/) {
  3894. FILE* xmlout = NULL;
  3895. FilePath output_file(output_file_);
  3896. FilePath output_dir(output_file.RemoveFileName());
  3897. if (output_dir.CreateDirectoriesRecursively()) {
  3898. xmlout = posix::FOpen(output_file_.c_str(), "w");
  3899. }
  3900. if (xmlout == NULL) {
  3901. // TODO(wan): report the reason of the failure.
  3902. //
  3903. // We don't do it for now as:
  3904. //
  3905. // 1. There is no urgent need for it.
  3906. // 2. It's a bit involved to make the errno variable thread-safe on
  3907. // all three operating systems (Linux, Windows, and Mac OS).
  3908. // 3. To interpret the meaning of errno in a thread-safe way,
  3909. // we need the strerror_r() function, which is not available on
  3910. // Windows.
  3911. fprintf(stderr,
  3912. "Unable to open file \"%s\"\n",
  3913. output_file_.c_str());
  3914. fflush(stderr);
  3915. exit(EXIT_FAILURE);
  3916. }
  3917. std::stringstream stream;
  3918. PrintXmlUnitTest(&stream, unit_test);
  3919. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  3920. fclose(xmlout);
  3921. }
  3922. // Returns an XML-escaped copy of the input string str. If is_attribute
  3923. // is true, the text is meant to appear as an attribute value, and
  3924. // normalizable whitespace is preserved by replacing it with character
  3925. // references.
  3926. //
  3927. // Invalid XML characters in str, if any, are stripped from the output.
  3928. // It is expected that most, if not all, of the text processed by this
  3929. // module will consist of ordinary English text.
  3930. // If this module is ever modified to produce version 1.1 XML output,
  3931. // most invalid characters can be retained using character references.
  3932. // TODO(wan): It might be nice to have a minimally invasive, human-readable
  3933. // escaping scheme for invalid characters, rather than dropping them.
  3934. std::string XmlUnitTestResultPrinter::EscapeXml(
  3935. const std::string& str, bool is_attribute) {
  3936. Message m;
  3937. for (size_t i = 0; i < str.size(); ++i) {
  3938. const char ch = str[i];
  3939. switch (ch) {
  3940. case '<':
  3941. m << "&lt;";
  3942. break;
  3943. case '>':
  3944. m << "&gt;";
  3945. break;
  3946. case '&':
  3947. m << "&amp;";
  3948. break;
  3949. case '\'':
  3950. if (is_attribute)
  3951. m << "&apos;";
  3952. else
  3953. m << '\'';
  3954. break;
  3955. case '"':
  3956. if (is_attribute)
  3957. m << "&quot;";
  3958. else
  3959. m << '"';
  3960. break;
  3961. default:
  3962. if (IsValidXmlCharacter(ch)) {
  3963. if (is_attribute && IsNormalizableWhitespace(ch))
  3964. m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
  3965. << ";";
  3966. else
  3967. m << ch;
  3968. }
  3969. break;
  3970. }
  3971. }
  3972. return m.GetString();
  3973. }
  3974. // Returns the given string with all characters invalid in XML removed.
  3975. // Currently invalid characters are dropped from the string. An
  3976. // alternative is to replace them with certain characters such as . or ?.
  3977. std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
  3978. const std::string& str) {
  3979. std::string output;
  3980. output.reserve(str.size());
  3981. for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
  3982. if (IsValidXmlCharacter(*it))
  3983. output.push_back(*it);
  3984. return output;
  3985. }
  3986. // The following routines generate an XML representation of a UnitTest
  3987. // object.
  3988. //
  3989. // This is how Google Test concepts map to the DTD:
  3990. //
  3991. // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
  3992. // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
  3993. // <testcase name="test-name"> <-- corresponds to a TestInfo object
  3994. // <failure message="...">...</failure>
  3995. // <failure message="...">...</failure>
  3996. // <failure message="...">...</failure>
  3997. // <-- individual assertion failures
  3998. // </testcase>
  3999. // </testsuite>
  4000. // </testsuites>
  4001. // Formats the given time in milliseconds as seconds.
  4002. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
  4003. ::std::stringstream ss;
  4004. ss << ms/1000.0;
  4005. return ss.str();
  4006. }
  4007. // Converts the given epoch time in milliseconds to a date string in the ISO
  4008. // 8601 format, without the timezone information.
  4009. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
  4010. // Using non-reentrant version as localtime_r is not portable.
  4011. time_t seconds = static_cast<time_t>(ms / 1000);
  4012. #ifdef _MSC_VER
  4013. # pragma warning(push) // Saves the current warning state.
  4014. # pragma warning(disable:4996) // Temporarily disables warning 4996
  4015. // (function or variable may be unsafe).
  4016. const struct tm* const time_struct = localtime(&seconds); // NOLINT
  4017. # pragma warning(pop) // Restores the warning state again.
  4018. #else
  4019. const struct tm* const time_struct = localtime(&seconds); // NOLINT
  4020. #endif
  4021. if (time_struct == NULL)
  4022. return ""; // Invalid ms value
  4023. // YYYY-MM-DDThh:mm:ss
  4024. return StreamableToString(time_struct->tm_year + 1900) + "-" +
  4025. String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
  4026. String::FormatIntWidth2(time_struct->tm_mday) + "T" +
  4027. String::FormatIntWidth2(time_struct->tm_hour) + ":" +
  4028. String::FormatIntWidth2(time_struct->tm_min) + ":" +
  4029. String::FormatIntWidth2(time_struct->tm_sec);
  4030. }
  4031. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  4032. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
  4033. const char* data) {
  4034. const char* segment = data;
  4035. *stream << "<![CDATA[";
  4036. for (;;) {
  4037. const char* const next_segment = strstr(segment, "]]>");
  4038. if (next_segment != NULL) {
  4039. stream->write(
  4040. segment, static_cast<std::streamsize>(next_segment - segment));
  4041. *stream << "]]>]]&gt;<![CDATA[";
  4042. segment = next_segment + strlen("]]>");
  4043. } else {
  4044. *stream << segment;
  4045. break;
  4046. }
  4047. }
  4048. *stream << "]]>";
  4049. }
  4050. void XmlUnitTestResultPrinter::OutputXmlAttribute(
  4051. std::ostream* stream,
  4052. const std::string& element_name,
  4053. const std::string& name,
  4054. const std::string& value) {
  4055. const std::vector<std::string>& allowed_names =
  4056. GetReservedAttributesForElement(element_name);
  4057. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4058. allowed_names.end())
  4059. << "Attribute " << name << " is not allowed for element <" << element_name
  4060. << ">.";
  4061. *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
  4062. }
  4063. // Prints an XML representation of a TestInfo object.
  4064. // TODO(wan): There is also value in printing properties with the plain printer.
  4065. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
  4066. const char* test_case_name,
  4067. const TestInfo& test_info) {
  4068. const TestResult& result = *test_info.result();
  4069. const std::string kTestcase = "testcase";
  4070. *stream << " <testcase";
  4071. OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
  4072. if (test_info.value_param() != NULL) {
  4073. OutputXmlAttribute(stream, kTestcase, "value_param",
  4074. test_info.value_param());
  4075. }
  4076. if (test_info.type_param() != NULL) {
  4077. OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
  4078. }
  4079. OutputXmlAttribute(stream, kTestcase, "status",
  4080. test_info.should_run() ? "run" : "notrun");
  4081. OutputXmlAttribute(stream, kTestcase, "time",
  4082. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  4083. OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
  4084. *stream << TestPropertiesAsXmlAttributes(result);
  4085. int failures = 0;
  4086. for (int i = 0; i < result.total_part_count(); ++i) {
  4087. const TestPartResult& part = result.GetTestPartResult(i);
  4088. if (part.failed()) {
  4089. if (++failures == 1) {
  4090. *stream << ">\n";
  4091. }
  4092. const string location = internal::FormatCompilerIndependentFileLocation(
  4093. part.file_name(), part.line_number());
  4094. const string summary = location + "\n" + part.summary();
  4095. *stream << " <failure message=\""
  4096. << EscapeXmlAttribute(summary.c_str())
  4097. << "\" type=\"\">";
  4098. const string detail = location + "\n" + part.message();
  4099. OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
  4100. *stream << "</failure>\n";
  4101. }
  4102. }
  4103. if (failures == 0)
  4104. *stream << " />\n";
  4105. else
  4106. *stream << " </testcase>\n";
  4107. }
  4108. // Prints an XML representation of a TestCase object
  4109. void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
  4110. const TestCase& test_case) {
  4111. const std::string kTestsuite = "testsuite";
  4112. *stream << " <" << kTestsuite;
  4113. OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
  4114. OutputXmlAttribute(stream, kTestsuite, "tests",
  4115. StreamableToString(test_case.reportable_test_count()));
  4116. OutputXmlAttribute(stream, kTestsuite, "failures",
  4117. StreamableToString(test_case.failed_test_count()));
  4118. OutputXmlAttribute(
  4119. stream, kTestsuite, "disabled",
  4120. StreamableToString(test_case.reportable_disabled_test_count()));
  4121. OutputXmlAttribute(stream, kTestsuite, "errors", "0");
  4122. OutputXmlAttribute(stream, kTestsuite, "time",
  4123. FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
  4124. *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
  4125. << ">\n";
  4126. for (int i = 0; i < test_case.total_test_count(); ++i) {
  4127. if (test_case.GetTestInfo(i)->is_reportable())
  4128. OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
  4129. }
  4130. *stream << " </" << kTestsuite << ">\n";
  4131. }
  4132. // Prints an XML summary of unit_test to output stream out.
  4133. void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
  4134. const UnitTest& unit_test) {
  4135. const std::string kTestsuites = "testsuites";
  4136. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  4137. *stream << "<" << kTestsuites;
  4138. OutputXmlAttribute(stream, kTestsuites, "tests",
  4139. StreamableToString(unit_test.reportable_test_count()));
  4140. OutputXmlAttribute(stream, kTestsuites, "failures",
  4141. StreamableToString(unit_test.failed_test_count()));
  4142. OutputXmlAttribute(
  4143. stream, kTestsuites, "disabled",
  4144. StreamableToString(unit_test.reportable_disabled_test_count()));
  4145. OutputXmlAttribute(stream, kTestsuites, "errors", "0");
  4146. OutputXmlAttribute(
  4147. stream, kTestsuites, "timestamp",
  4148. FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
  4149. OutputXmlAttribute(stream, kTestsuites, "time",
  4150. FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
  4151. if (GTEST_FLAG(shuffle)) {
  4152. OutputXmlAttribute(stream, kTestsuites, "random_seed",
  4153. StreamableToString(unit_test.random_seed()));
  4154. }
  4155. *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
  4156. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  4157. *stream << ">\n";
  4158. for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  4159. if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
  4160. PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
  4161. }
  4162. *stream << "</" << kTestsuites << ">\n";
  4163. }
  4164. // Produces a string representing the test properties in a result as space
  4165. // delimited XML attributes based on the property key="value" pairs.
  4166. std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
  4167. const TestResult& result) {
  4168. Message attributes;
  4169. for (int i = 0; i < result.test_property_count(); ++i) {
  4170. const TestProperty& property = result.GetTestProperty(i);
  4171. attributes << " " << property.key() << "="
  4172. << "\"" << EscapeXmlAttribute(property.value()) << "\"";
  4173. }
  4174. return attributes.GetString();
  4175. }
  4176. // End XmlUnitTestResultPrinter
  4177. #if GTEST_CAN_STREAM_RESULTS_
  4178. // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
  4179. // replaces them by "%xx" where xx is their hexadecimal value. For
  4180. // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
  4181. // in both time and space -- important as the input str may contain an
  4182. // arbitrarily long test failure message and stack trace.
  4183. string StreamingListener::UrlEncode(const char* str) {
  4184. string result;
  4185. result.reserve(strlen(str) + 1);
  4186. for (char ch = *str; ch != '\0'; ch = *++str) {
  4187. switch (ch) {
  4188. case '%':
  4189. case '=':
  4190. case '&':
  4191. case '\n':
  4192. result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
  4193. break;
  4194. default:
  4195. result.push_back(ch);
  4196. break;
  4197. }
  4198. }
  4199. return result;
  4200. }
  4201. void StreamingListener::SocketWriter::MakeConnection() {
  4202. GTEST_CHECK_(sockfd_ == -1)
  4203. << "MakeConnection() can't be called when there is already a connection.";
  4204. addrinfo hints;
  4205. memset(&hints, 0, sizeof(hints));
  4206. hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
  4207. hints.ai_socktype = SOCK_STREAM;
  4208. addrinfo* servinfo = NULL;
  4209. // Use the getaddrinfo() to get a linked list of IP addresses for
  4210. // the given host name.
  4211. const int error_num = getaddrinfo(
  4212. host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
  4213. if (error_num != 0) {
  4214. GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
  4215. << gai_strerror(error_num);
  4216. }
  4217. // Loop through all the results and connect to the first we can.
  4218. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
  4219. cur_addr = cur_addr->ai_next) {
  4220. sockfd_ = socket(
  4221. cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
  4222. if (sockfd_ != -1) {
  4223. // Connect the client socket to the server socket.
  4224. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
  4225. close(sockfd_);
  4226. sockfd_ = -1;
  4227. }
  4228. }
  4229. }
  4230. freeaddrinfo(servinfo); // all done with this structure
  4231. if (sockfd_ == -1) {
  4232. GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
  4233. << host_name_ << ":" << port_num_;
  4234. }
  4235. }
  4236. // End of class Streaming Listener
  4237. #endif // GTEST_CAN_STREAM_RESULTS__
  4238. // Class ScopedTrace
  4239. // Pushes the given source file location and message onto a per-thread
  4240. // trace stack maintained by Google Test.
  4241. ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
  4242. GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
  4243. TraceInfo trace;
  4244. trace.file = file;
  4245. trace.line = line;
  4246. trace.message = message.GetString();
  4247. UnitTest::GetInstance()->PushGTestTrace(trace);
  4248. }
  4249. // Pops the info pushed by the c'tor.
  4250. ScopedTrace::~ScopedTrace()
  4251. GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
  4252. UnitTest::GetInstance()->PopGTestTrace();
  4253. }
  4254. // class OsStackTraceGetter
  4255. // Returns the current OS stack trace as an std::string. Parameters:
  4256. //
  4257. // max_depth - the maximum number of stack frames to be included
  4258. // in the trace.
  4259. // skip_count - the number of top frames to be skipped; doesn't count
  4260. // against max_depth.
  4261. //
  4262. string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
  4263. int /* skip_count */)
  4264. GTEST_LOCK_EXCLUDED_(mutex_) {
  4265. return "";
  4266. }
  4267. void OsStackTraceGetter::UponLeavingGTest()
  4268. GTEST_LOCK_EXCLUDED_(mutex_) {
  4269. }
  4270. const char* const
  4271. OsStackTraceGetter::kElidedFramesMarker =
  4272. "... " GTEST_NAME_ " internal frames ...";
  4273. // A helper class that creates the premature-exit file in its
  4274. // constructor and deletes the file in its destructor.
  4275. class ScopedPrematureExitFile {
  4276. public:
  4277. explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
  4278. : premature_exit_filepath_(premature_exit_filepath) {
  4279. // If a path to the premature-exit file is specified...
  4280. if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
  4281. // create the file with a single "0" character in it. I/O
  4282. // errors are ignored as there's nothing better we can do and we
  4283. // don't want to fail the test because of this.
  4284. FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
  4285. fwrite("0", 1, 1, pfile);
  4286. fclose(pfile);
  4287. }
  4288. }
  4289. ~ScopedPrematureExitFile() {
  4290. if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
  4291. remove(premature_exit_filepath_);
  4292. }
  4293. }
  4294. private:
  4295. const char* const premature_exit_filepath_;
  4296. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
  4297. };
  4298. } // namespace internal
  4299. // class TestEventListeners
  4300. TestEventListeners::TestEventListeners()
  4301. : repeater_(new internal::TestEventRepeater()),
  4302. default_result_printer_(NULL),
  4303. default_xml_generator_(NULL) {
  4304. }
  4305. TestEventListeners::~TestEventListeners() { delete repeater_; }
  4306. // Returns the standard listener responsible for the default console
  4307. // output. Can be removed from the listeners list to shut down default
  4308. // console output. Note that removing this object from the listener list
  4309. // with Release transfers its ownership to the user.
  4310. void TestEventListeners::Append(TestEventListener* listener) {
  4311. repeater_->Append(listener);
  4312. }
  4313. // Removes the given event listener from the list and returns it. It then
  4314. // becomes the caller's responsibility to delete the listener. Returns
  4315. // NULL if the listener is not found in the list.
  4316. TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
  4317. if (listener == default_result_printer_)
  4318. default_result_printer_ = NULL;
  4319. else if (listener == default_xml_generator_)
  4320. default_xml_generator_ = NULL;
  4321. return repeater_->Release(listener);
  4322. }
  4323. // Returns repeater that broadcasts the TestEventListener events to all
  4324. // subscribers.
  4325. TestEventListener* TestEventListeners::repeater() { return repeater_; }
  4326. // Sets the default_result_printer attribute to the provided listener.
  4327. // The listener is also added to the listener list and previous
  4328. // default_result_printer is removed from it and deleted. The listener can
  4329. // also be NULL in which case it will not be added to the list. Does
  4330. // nothing if the previous and the current listener objects are the same.
  4331. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
  4332. if (default_result_printer_ != listener) {
  4333. // It is an error to pass this method a listener that is already in the
  4334. // list.
  4335. delete Release(default_result_printer_);
  4336. default_result_printer_ = listener;
  4337. if (listener != NULL)
  4338. Append(listener);
  4339. }
  4340. }
  4341. // Sets the default_xml_generator attribute to the provided listener. The
  4342. // listener is also added to the listener list and previous
  4343. // default_xml_generator is removed from it and deleted. The listener can
  4344. // also be NULL in which case it will not be added to the list. Does
  4345. // nothing if the previous and the current listener objects are the same.
  4346. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
  4347. if (default_xml_generator_ != listener) {
  4348. // It is an error to pass this method a listener that is already in the
  4349. // list.
  4350. delete Release(default_xml_generator_);
  4351. default_xml_generator_ = listener;
  4352. if (listener != NULL)
  4353. Append(listener);
  4354. }
  4355. }
  4356. // Controls whether events will be forwarded by the repeater to the
  4357. // listeners in the list.
  4358. bool TestEventListeners::EventForwardingEnabled() const {
  4359. return repeater_->forwarding_enabled();
  4360. }
  4361. void TestEventListeners::SuppressEventForwarding() {
  4362. repeater_->set_forwarding_enabled(false);
  4363. }
  4364. // class UnitTest
  4365. // Gets the singleton UnitTest object. The first time this method is
  4366. // called, a UnitTest object is constructed and returned. Consecutive
  4367. // calls will return the same object.
  4368. //
  4369. // We don't protect this under mutex_ as a user is not supposed to
  4370. // call this before main() starts, from which point on the return
  4371. // value will never change.
  4372. UnitTest* UnitTest::GetInstance() {
  4373. // When compiled with MSVC 7.1 in optimized mode, destroying the
  4374. // UnitTest object upon exiting the program messes up the exit code,
  4375. // causing successful tests to appear failed. We have to use a
  4376. // different implementation in this case to bypass the compiler bug.
  4377. // This implementation makes the compiler happy, at the cost of
  4378. // leaking the UnitTest object.
  4379. // CodeGear C++Builder insists on a public destructor for the
  4380. // default implementation. Use this implementation to keep good OO
  4381. // design with private destructor.
  4382. #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  4383. static UnitTest* const instance = new UnitTest;
  4384. return instance;
  4385. #else
  4386. static UnitTest instance;
  4387. return &instance;
  4388. #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  4389. }
  4390. // Gets the number of successful test cases.
  4391. int UnitTest::successful_test_case_count() const {
  4392. return impl()->successful_test_case_count();
  4393. }
  4394. // Gets the number of failed test cases.
  4395. int UnitTest::failed_test_case_count() const {
  4396. return impl()->failed_test_case_count();
  4397. }
  4398. // Gets the number of all test cases.
  4399. int UnitTest::total_test_case_count() const {
  4400. return impl()->total_test_case_count();
  4401. }
  4402. // Gets the number of all test cases that contain at least one test
  4403. // that should run.
  4404. int UnitTest::test_case_to_run_count() const {
  4405. return impl()->test_case_to_run_count();
  4406. }
  4407. // Gets the number of successful tests.
  4408. int UnitTest::successful_test_count() const {
  4409. return impl()->successful_test_count();
  4410. }
  4411. // Gets the number of failed tests.
  4412. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
  4413. // Gets the number of disabled tests that will be reported in the XML report.
  4414. int UnitTest::reportable_disabled_test_count() const {
  4415. return impl()->reportable_disabled_test_count();
  4416. }
  4417. // Gets the number of disabled tests.
  4418. int UnitTest::disabled_test_count() const {
  4419. return impl()->disabled_test_count();
  4420. }
  4421. // Gets the number of tests to be printed in the XML report.
  4422. int UnitTest::reportable_test_count() const {
  4423. return impl()->reportable_test_count();
  4424. }
  4425. // Gets the number of all tests.
  4426. int UnitTest::total_test_count() const { return impl()->total_test_count(); }
  4427. // Gets the number of tests that should run.
  4428. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
  4429. // Gets the time of the test program start, in ms from the start of the
  4430. // UNIX epoch.
  4431. internal::TimeInMillis UnitTest::start_timestamp() const {
  4432. return impl()->start_timestamp();
  4433. }
  4434. // Gets the elapsed time, in milliseconds.
  4435. internal::TimeInMillis UnitTest::elapsed_time() const {
  4436. return impl()->elapsed_time();
  4437. }
  4438. // Returns true iff the unit test passed (i.e. all test cases passed).
  4439. bool UnitTest::Passed() const { return impl()->Passed(); }
  4440. // Returns true iff the unit test failed (i.e. some test case failed
  4441. // or something outside of all tests failed).
  4442. bool UnitTest::Failed() const { return impl()->Failed(); }
  4443. // Gets the i-th test case among all the test cases. i can range from 0 to
  4444. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  4445. const TestCase* UnitTest::GetTestCase(int i) const {
  4446. return impl()->GetTestCase(i);
  4447. }
  4448. // Returns the TestResult containing information on test failures and
  4449. // properties logged outside of individual test cases.
  4450. const TestResult& UnitTest::ad_hoc_test_result() const {
  4451. return *impl()->ad_hoc_test_result();
  4452. }
  4453. // Gets the i-th test case among all the test cases. i can range from 0 to
  4454. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  4455. TestCase* UnitTest::GetMutableTestCase(int i) {
  4456. return impl()->GetMutableTestCase(i);
  4457. }
  4458. // Returns the list of event listeners that can be used to track events
  4459. // inside Google Test.
  4460. TestEventListeners& UnitTest::listeners() {
  4461. return *impl()->listeners();
  4462. }
  4463. // Registers and returns a global test environment. When a test
  4464. // program is run, all global test environments will be set-up in the
  4465. // order they were registered. After all tests in the program have
  4466. // finished, all global test environments will be torn-down in the
  4467. // *reverse* order they were registered.
  4468. //
  4469. // The UnitTest object takes ownership of the given environment.
  4470. //
  4471. // We don't protect this under mutex_, as we only support calling it
  4472. // from the main thread.
  4473. Environment* UnitTest::AddEnvironment(Environment* env) {
  4474. if (env == NULL) {
  4475. return NULL;
  4476. }
  4477. impl_->environments().push_back(env);
  4478. return env;
  4479. }
  4480. // Adds a TestPartResult to the current TestResult object. All Google Test
  4481. // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
  4482. // this to report their results. The user code should use the
  4483. // assertion macros instead of calling this directly.
  4484. void UnitTest::AddTestPartResult(
  4485. TestPartResult::Type result_type,
  4486. const char* file_name,
  4487. int line_number,
  4488. const std::string& message,
  4489. const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
  4490. Message msg;
  4491. msg << message;
  4492. internal::MutexLock lock(&mutex_);
  4493. if (impl_->gtest_trace_stack().size() > 0) {
  4494. msg << "\n" << GTEST_NAME_ << " trace:";
  4495. for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
  4496. i > 0; --i) {
  4497. const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
  4498. msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
  4499. << " " << trace.message;
  4500. }
  4501. }
  4502. if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
  4503. msg << internal::kStackTraceMarker << os_stack_trace;
  4504. }
  4505. const TestPartResult result =
  4506. TestPartResult(result_type, file_name, line_number,
  4507. msg.GetString().c_str());
  4508. impl_->GetTestPartResultReporterForCurrentThread()->
  4509. ReportTestPartResult(result);
  4510. if (result_type != TestPartResult::kSuccess) {
  4511. // gtest_break_on_failure takes precedence over
  4512. // gtest_throw_on_failure. This allows a user to set the latter
  4513. // in the code (perhaps in order to use Google Test assertions
  4514. // with another testing framework) and specify the former on the
  4515. // command line for debugging.
  4516. if (GTEST_FLAG(break_on_failure)) {
  4517. #if GTEST_OS_WINDOWS
  4518. // Using DebugBreak on Windows allows gtest to still break into a debugger
  4519. // when a failure happens and both the --gtest_break_on_failure and
  4520. // the --gtest_catch_exceptions flags are specified.
  4521. DebugBreak();
  4522. #else
  4523. // Dereference NULL through a volatile pointer to prevent the compiler
  4524. // from removing. We use this rather than abort() or __builtin_trap() for
  4525. // portability: Symbian doesn't implement abort() well, and some debuggers
  4526. // don't correctly trap abort().
  4527. *static_cast<volatile int*>(NULL) = 1;
  4528. #endif // GTEST_OS_WINDOWS
  4529. } else if (GTEST_FLAG(throw_on_failure)) {
  4530. #if GTEST_HAS_EXCEPTIONS
  4531. throw internal::GoogleTestFailureException(result);
  4532. #else
  4533. // We cannot call abort() as it generates a pop-up in debug mode
  4534. // that cannot be suppressed in VC 7.1 or below.
  4535. exit(1);
  4536. #endif
  4537. }
  4538. }
  4539. }
  4540. // Adds a TestProperty to the current TestResult object when invoked from
  4541. // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
  4542. // from SetUpTestCase or TearDownTestCase, or to the global property set
  4543. // when invoked elsewhere. If the result already contains a property with
  4544. // the same key, the value will be updated.
  4545. void UnitTest::RecordProperty(const std::string& key,
  4546. const std::string& value) {
  4547. impl_->RecordProperty(TestProperty(key, value));
  4548. }
  4549. // Runs all tests in this UnitTest object and prints the result.
  4550. // Returns 0 if successful, or 1 otherwise.
  4551. //
  4552. // We don't protect this under mutex_, as we only support calling it
  4553. // from the main thread.
  4554. int UnitTest::Run() {
  4555. const bool in_death_test_child_process =
  4556. internal::GTEST_FLAG(internal_run_death_test).length() > 0;
  4557. // Google Test implements this protocol for catching that a test
  4558. // program exits before returning control to Google Test:
  4559. //
  4560. // 1. Upon start, Google Test creates a file whose absolute path
  4561. // is specified by the environment variable
  4562. // TEST_PREMATURE_EXIT_FILE.
  4563. // 2. When Google Test has finished its work, it deletes the file.
  4564. //
  4565. // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
  4566. // running a Google-Test-based test program and check the existence
  4567. // of the file at the end of the test execution to see if it has
  4568. // exited prematurely.
  4569. // If we are in the child process of a death test, don't
  4570. // create/delete the premature exit file, as doing so is unnecessary
  4571. // and will confuse the parent process. Otherwise, create/delete
  4572. // the file upon entering/leaving this function. If the program
  4573. // somehow exits before this function has a chance to return, the
  4574. // premature-exit file will be left undeleted, causing a test runner
  4575. // that understands the premature-exit-file protocol to report the
  4576. // test as having failed.
  4577. const internal::ScopedPrematureExitFile premature_exit_file(
  4578. in_death_test_child_process ?
  4579. NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
  4580. // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
  4581. // used for the duration of the program.
  4582. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
  4583. #if GTEST_HAS_SEH
  4584. // Either the user wants Google Test to catch exceptions thrown by the
  4585. // tests or this is executing in the context of death test child
  4586. // process. In either case the user does not want to see pop-up dialogs
  4587. // about crashes - they are expected.
  4588. if (impl()->catch_exceptions() || in_death_test_child_process) {
  4589. # if !GTEST_OS_WINDOWS_MOBILE
  4590. // SetErrorMode doesn't exist on CE.
  4591. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
  4592. SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
  4593. # endif // !GTEST_OS_WINDOWS_MOBILE
  4594. # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
  4595. // Death test children can be terminated with _abort(). On Windows,
  4596. // _abort() can show a dialog with a warning message. This forces the
  4597. // abort message to go to stderr instead.
  4598. _set_error_mode(_OUT_TO_STDERR);
  4599. # endif
  4600. # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
  4601. // In the debug version, Visual Studio pops up a separate dialog
  4602. // offering a choice to debug the aborted program. We need to suppress
  4603. // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
  4604. // executed. Google Test will notify the user of any unexpected
  4605. // failure via stderr.
  4606. //
  4607. // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
  4608. // Users of prior VC versions shall suffer the agony and pain of
  4609. // clicking through the countless debug dialogs.
  4610. // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
  4611. // debug mode when compiled with VC 7.1 or lower.
  4612. if (!GTEST_FLAG(break_on_failure))
  4613. _set_abort_behavior(
  4614. 0x0, // Clear the following flags:
  4615. _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
  4616. # endif
  4617. }
  4618. #endif // GTEST_HAS_SEH
  4619. return internal::HandleExceptionsInMethodIfSupported(
  4620. impl(),
  4621. &internal::UnitTestImpl::RunAllTests,
  4622. "auxiliary test code (environments or event listeners)") ? 0 : 1;
  4623. }
  4624. // Returns the working directory when the first TEST() or TEST_F() was
  4625. // executed.
  4626. const char* UnitTest::original_working_dir() const {
  4627. return impl_->original_working_dir_.c_str();
  4628. }
  4629. // Returns the TestCase object for the test that's currently running,
  4630. // or NULL if no test is running.
  4631. const TestCase* UnitTest::current_test_case() const
  4632. GTEST_LOCK_EXCLUDED_(mutex_) {
  4633. internal::MutexLock lock(&mutex_);
  4634. return impl_->current_test_case();
  4635. }
  4636. // Returns the TestInfo object for the test that's currently running,
  4637. // or NULL if no test is running.
  4638. const TestInfo* UnitTest::current_test_info() const
  4639. GTEST_LOCK_EXCLUDED_(mutex_) {
  4640. internal::MutexLock lock(&mutex_);
  4641. return impl_->current_test_info();
  4642. }
  4643. // Returns the random seed used at the start of the current test run.
  4644. int UnitTest::random_seed() const { return impl_->random_seed(); }
  4645. #if GTEST_HAS_PARAM_TEST
  4646. // Returns ParameterizedTestCaseRegistry object used to keep track of
  4647. // value-parameterized tests and instantiate and register them.
  4648. internal::ParameterizedTestCaseRegistry&
  4649. UnitTest::parameterized_test_registry()
  4650. GTEST_LOCK_EXCLUDED_(mutex_) {
  4651. return impl_->parameterized_test_registry();
  4652. }
  4653. #endif // GTEST_HAS_PARAM_TEST
  4654. // Creates an empty UnitTest.
  4655. UnitTest::UnitTest() {
  4656. impl_ = new internal::UnitTestImpl(this);
  4657. }
  4658. // Destructor of UnitTest.
  4659. UnitTest::~UnitTest() {
  4660. delete impl_;
  4661. }
  4662. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  4663. // Google Test trace stack.
  4664. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
  4665. GTEST_LOCK_EXCLUDED_(mutex_) {
  4666. internal::MutexLock lock(&mutex_);
  4667. impl_->gtest_trace_stack().push_back(trace);
  4668. }
  4669. // Pops a trace from the per-thread Google Test trace stack.
  4670. void UnitTest::PopGTestTrace()
  4671. GTEST_LOCK_EXCLUDED_(mutex_) {
  4672. internal::MutexLock lock(&mutex_);
  4673. impl_->gtest_trace_stack().pop_back();
  4674. }
  4675. namespace internal {
  4676. UnitTestImpl::UnitTestImpl(UnitTest* parent)
  4677. : parent_(parent),
  4678. #ifdef _MSC_VER
  4679. # pragma warning(push) // Saves the current warning state.
  4680. # pragma warning(disable:4355) // Temporarily disables warning 4355
  4681. // (using this in initializer).
  4682. default_global_test_part_result_reporter_(this),
  4683. default_per_thread_test_part_result_reporter_(this),
  4684. # pragma warning(pop) // Restores the warning state again.
  4685. #else
  4686. default_global_test_part_result_reporter_(this),
  4687. default_per_thread_test_part_result_reporter_(this),
  4688. #endif // _MSC_VER
  4689. global_test_part_result_repoter_(
  4690. &default_global_test_part_result_reporter_),
  4691. per_thread_test_part_result_reporter_(
  4692. &default_per_thread_test_part_result_reporter_),
  4693. #if GTEST_HAS_PARAM_TEST
  4694. parameterized_test_registry_(),
  4695. parameterized_tests_registered_(false),
  4696. #endif // GTEST_HAS_PARAM_TEST
  4697. last_death_test_case_(-1),
  4698. current_test_case_(NULL),
  4699. current_test_info_(NULL),
  4700. ad_hoc_test_result_(),
  4701. os_stack_trace_getter_(NULL),
  4702. post_flag_parse_init_performed_(false),
  4703. random_seed_(0), // Will be overridden by the flag before first use.
  4704. random_(0), // Will be reseeded before first use.
  4705. start_timestamp_(0),
  4706. elapsed_time_(0),
  4707. #if GTEST_HAS_DEATH_TEST
  4708. death_test_factory_(new DefaultDeathTestFactory),
  4709. #endif
  4710. // Will be overridden by the flag before first use.
  4711. catch_exceptions_(false) {
  4712. listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
  4713. }
  4714. UnitTestImpl::~UnitTestImpl() {
  4715. // Deletes every TestCase.
  4716. ForEach(test_cases_, internal::Delete<TestCase>);
  4717. // Deletes every Environment.
  4718. ForEach(environments_, internal::Delete<Environment>);
  4719. delete os_stack_trace_getter_;
  4720. }
  4721. // Adds a TestProperty to the current TestResult object when invoked in a
  4722. // context of a test, to current test case's ad_hoc_test_result when invoke
  4723. // from SetUpTestCase/TearDownTestCase, or to the global property set
  4724. // otherwise. If the result already contains a property with the same key,
  4725. // the value will be updated.
  4726. void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
  4727. std::string xml_element;
  4728. TestResult* test_result; // TestResult appropriate for property recording.
  4729. if (current_test_info_ != NULL) {
  4730. xml_element = "testcase";
  4731. test_result = &(current_test_info_->result_);
  4732. } else if (current_test_case_ != NULL) {
  4733. xml_element = "testsuite";
  4734. test_result = &(current_test_case_->ad_hoc_test_result_);
  4735. } else {
  4736. xml_element = "testsuites";
  4737. test_result = &ad_hoc_test_result_;
  4738. }
  4739. test_result->RecordProperty(xml_element, test_property);
  4740. }
  4741. #if GTEST_HAS_DEATH_TEST
  4742. // Disables event forwarding if the control is currently in a death test
  4743. // subprocess. Must not be called before InitGoogleTest.
  4744. void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
  4745. if (internal_run_death_test_flag_.get() != NULL)
  4746. listeners()->SuppressEventForwarding();
  4747. }
  4748. #endif // GTEST_HAS_DEATH_TEST
  4749. // Initializes event listeners performing XML output as specified by
  4750. // UnitTestOptions. Must not be called before InitGoogleTest.
  4751. void UnitTestImpl::ConfigureXmlOutput() {
  4752. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  4753. if (output_format == "xml") {
  4754. listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
  4755. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  4756. } else if (output_format != "") {
  4757. printf("WARNING: unrecognized output format \"%s\" ignored.\n",
  4758. output_format.c_str());
  4759. fflush(stdout);
  4760. }
  4761. }
  4762. #if GTEST_CAN_STREAM_RESULTS_
  4763. // Initializes event listeners for streaming test results in string form.
  4764. // Must not be called before InitGoogleTest.
  4765. void UnitTestImpl::ConfigureStreamingOutput() {
  4766. const std::string& target = GTEST_FLAG(stream_result_to);
  4767. if (!target.empty()) {
  4768. const size_t pos = target.find(':');
  4769. if (pos != std::string::npos) {
  4770. listeners()->Append(new StreamingListener(target.substr(0, pos),
  4771. target.substr(pos+1)));
  4772. } else {
  4773. printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
  4774. target.c_str());
  4775. fflush(stdout);
  4776. }
  4777. }
  4778. }
  4779. #endif // GTEST_CAN_STREAM_RESULTS_
  4780. // Performs initialization dependent upon flag values obtained in
  4781. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  4782. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  4783. // this function is also called from RunAllTests. Since this function can be
  4784. // called more than once, it has to be idempotent.
  4785. void UnitTestImpl::PostFlagParsingInit() {
  4786. // Ensures that this function does not execute more than once.
  4787. if (!post_flag_parse_init_performed_) {
  4788. post_flag_parse_init_performed_ = true;
  4789. #if GTEST_HAS_DEATH_TEST
  4790. InitDeathTestSubprocessControlInfo();
  4791. SuppressTestEventsIfInSubprocess();
  4792. #endif // GTEST_HAS_DEATH_TEST
  4793. // Registers parameterized tests. This makes parameterized tests
  4794. // available to the UnitTest reflection API without running
  4795. // RUN_ALL_TESTS.
  4796. RegisterParameterizedTests();
  4797. // Configures listeners for XML output. This makes it possible for users
  4798. // to shut down the default XML output before invoking RUN_ALL_TESTS.
  4799. ConfigureXmlOutput();
  4800. #if GTEST_CAN_STREAM_RESULTS_
  4801. // Configures listeners for streaming test results to the specified server.
  4802. ConfigureStreamingOutput();
  4803. #endif // GTEST_CAN_STREAM_RESULTS_
  4804. }
  4805. }
  4806. // A predicate that checks the name of a TestCase against a known
  4807. // value.
  4808. //
  4809. // This is used for implementation of the UnitTest class only. We put
  4810. // it in the anonymous namespace to prevent polluting the outer
  4811. // namespace.
  4812. //
  4813. // TestCaseNameIs is copyable.
  4814. class TestCaseNameIs {
  4815. public:
  4816. // Constructor.
  4817. explicit TestCaseNameIs(const std::string& name)
  4818. : name_(name) {}
  4819. // Returns true iff the name of test_case matches name_.
  4820. bool operator()(const TestCase* test_case) const {
  4821. return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
  4822. }
  4823. private:
  4824. std::string name_;
  4825. };
  4826. // Finds and returns a TestCase with the given name. If one doesn't
  4827. // exist, creates one and returns it. It's the CALLER'S
  4828. // RESPONSIBILITY to ensure that this function is only called WHEN THE
  4829. // TESTS ARE NOT SHUFFLED.
  4830. //
  4831. // Arguments:
  4832. //
  4833. // test_case_name: name of the test case
  4834. // type_param: the name of the test case's type parameter, or NULL if
  4835. // this is not a typed or a type-parameterized test case.
  4836. // set_up_tc: pointer to the function that sets up the test case
  4837. // tear_down_tc: pointer to the function that tears down the test case
  4838. TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
  4839. const char* type_param,
  4840. Test::SetUpTestCaseFunc set_up_tc,
  4841. Test::TearDownTestCaseFunc tear_down_tc) {
  4842. // Can we find a TestCase with the given name?
  4843. const std::vector<TestCase*>::const_iterator test_case =
  4844. std::find_if(test_cases_.begin(), test_cases_.end(),
  4845. TestCaseNameIs(test_case_name));
  4846. if (test_case != test_cases_.end())
  4847. return *test_case;
  4848. // No. Let's create one.
  4849. TestCase* const new_test_case =
  4850. new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
  4851. // Is this a death test case?
  4852. if (internal::UnitTestOptions::MatchesFilter(test_case_name,
  4853. kDeathTestCaseFilter)) {
  4854. // Yes. Inserts the test case after the last death test case
  4855. // defined so far. This only works when the test cases haven't
  4856. // been shuffled. Otherwise we may end up running a death test
  4857. // after a non-death test.
  4858. ++last_death_test_case_;
  4859. test_cases_.insert(test_cases_.begin() + last_death_test_case_,
  4860. new_test_case);
  4861. } else {
  4862. // No. Appends to the end of the list.
  4863. test_cases_.push_back(new_test_case);
  4864. }
  4865. test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
  4866. return new_test_case;
  4867. }
  4868. // Helpers for setting up / tearing down the given environment. They
  4869. // are for use in the ForEach() function.
  4870. static void SetUpEnvironment(Environment* env) { env->SetUp(); }
  4871. static void TearDownEnvironment(Environment* env) { env->TearDown(); }
  4872. // Runs all tests in this UnitTest object, prints the result, and
  4873. // returns true if all tests are successful. If any exception is
  4874. // thrown during a test, the test is considered to be failed, but the
  4875. // rest of the tests will still be run.
  4876. //
  4877. // When parameterized tests are enabled, it expands and registers
  4878. // parameterized tests first in RegisterParameterizedTests().
  4879. // All other functions called from RunAllTests() may safely assume that
  4880. // parameterized tests are ready to be counted and run.
  4881. bool UnitTestImpl::RunAllTests() {
  4882. // Makes sure InitGoogleTest() was called.
  4883. if (!GTestIsInitialized()) {
  4884. printf("%s",
  4885. "\nThis test program did NOT call ::testing::InitGoogleTest "
  4886. "before calling RUN_ALL_TESTS(). Please fix it.\n");
  4887. return false;
  4888. }
  4889. // Do not run any test if the --help flag was specified.
  4890. if (g_help_flag)
  4891. return true;
  4892. // Repeats the call to the post-flag parsing initialization in case the
  4893. // user didn't call InitGoogleTest.
  4894. PostFlagParsingInit();
  4895. // Even if sharding is not on, test runners may want to use the
  4896. // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
  4897. // protocol.
  4898. internal::WriteToShardStatusFileIfNeeded();
  4899. // True iff we are in a subprocess for running a thread-safe-style
  4900. // death test.
  4901. bool in_subprocess_for_death_test = false;
  4902. #if GTEST_HAS_DEATH_TEST
  4903. in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
  4904. #endif // GTEST_HAS_DEATH_TEST
  4905. const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
  4906. in_subprocess_for_death_test);
  4907. // Compares the full test names with the filter to decide which
  4908. // tests to run.
  4909. const bool has_tests_to_run = FilterTests(should_shard
  4910. ? HONOR_SHARDING_PROTOCOL
  4911. : IGNORE_SHARDING_PROTOCOL) > 0;
  4912. // Lists the tests and exits if the --gtest_list_tests flag was specified.
  4913. if (GTEST_FLAG(list_tests)) {
  4914. // This must be called *after* FilterTests() has been called.
  4915. ListTestsMatchingFilter();
  4916. return true;
  4917. }
  4918. random_seed_ = GTEST_FLAG(shuffle) ?
  4919. GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
  4920. // True iff at least one test has failed.
  4921. bool failed = false;
  4922. TestEventListener* repeater = listeners()->repeater();
  4923. start_timestamp_ = GetTimeInMillis();
  4924. repeater->OnTestProgramStart(*parent_);
  4925. // How many times to repeat the tests? We don't want to repeat them
  4926. // when we are inside the subprocess of a death test.
  4927. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
  4928. // Repeats forever if the repeat count is negative.
  4929. const bool forever = repeat < 0;
  4930. for (int i = 0; forever || i != repeat; i++) {
  4931. // We want to preserve failures generated by ad-hoc test
  4932. // assertions executed before RUN_ALL_TESTS().
  4933. ClearNonAdHocTestResult();
  4934. const TimeInMillis start = GetTimeInMillis();
  4935. // Shuffles test cases and tests if requested.
  4936. if (has_tests_to_run && GTEST_FLAG(shuffle)) {
  4937. random()->Reseed(random_seed_);
  4938. // This should be done before calling OnTestIterationStart(),
  4939. // such that a test event listener can see the actual test order
  4940. // in the event.
  4941. ShuffleTests();
  4942. }
  4943. // Tells the unit test event listeners that the tests are about to start.
  4944. repeater->OnTestIterationStart(*parent_, i);
  4945. // Runs each test case if there is at least one test to run.
  4946. if (has_tests_to_run) {
  4947. // Sets up all environments beforehand.
  4948. repeater->OnEnvironmentsSetUpStart(*parent_);
  4949. ForEach(environments_, SetUpEnvironment);
  4950. repeater->OnEnvironmentsSetUpEnd(*parent_);
  4951. // Runs the tests only if there was no fatal failure during global
  4952. // set-up.
  4953. if (!Test::HasFatalFailure()) {
  4954. for (int test_index = 0; test_index < total_test_case_count();
  4955. test_index++) {
  4956. GetMutableTestCase(test_index)->Run();
  4957. }
  4958. }
  4959. // Tears down all environments in reverse order afterwards.
  4960. repeater->OnEnvironmentsTearDownStart(*parent_);
  4961. std::for_each(environments_.rbegin(), environments_.rend(),
  4962. TearDownEnvironment);
  4963. repeater->OnEnvironmentsTearDownEnd(*parent_);
  4964. }
  4965. elapsed_time_ = GetTimeInMillis() - start;
  4966. // Tells the unit test event listener that the tests have just finished.
  4967. repeater->OnTestIterationEnd(*parent_, i);
  4968. // Gets the result and clears it.
  4969. if (!Passed()) {
  4970. failed = true;
  4971. }
  4972. // Restores the original test order after the iteration. This
  4973. // allows the user to quickly repro a failure that happens in the
  4974. // N-th iteration without repeating the first (N - 1) iterations.
  4975. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
  4976. // case the user somehow changes the value of the flag somewhere
  4977. // (it's always safe to unshuffle the tests).
  4978. UnshuffleTests();
  4979. if (GTEST_FLAG(shuffle)) {
  4980. // Picks a new random seed for each iteration.
  4981. random_seed_ = GetNextRandomSeed(random_seed_);
  4982. }
  4983. }
  4984. repeater->OnTestProgramEnd(*parent_);
  4985. return !failed;
  4986. }
  4987. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  4988. // if the variable is present. If a file already exists at this location, this
  4989. // function will write over it. If the variable is present, but the file cannot
  4990. // be created, prints an error and exits.
  4991. void WriteToShardStatusFileIfNeeded() {
  4992. const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
  4993. if (test_shard_file != NULL) {
  4994. FILE* const file = posix::FOpen(test_shard_file, "w");
  4995. if (file == NULL) {
  4996. ColoredPrintf(COLOR_RED,
  4997. "Could not write to the test shard status file \"%s\" "
  4998. "specified by the %s environment variable.\n",
  4999. test_shard_file, kTestShardStatusFile);
  5000. fflush(stdout);
  5001. exit(EXIT_FAILURE);
  5002. }
  5003. fclose(file);
  5004. }
  5005. }
  5006. // Checks whether sharding is enabled by examining the relevant
  5007. // environment variable values. If the variables are present,
  5008. // but inconsistent (i.e., shard_index >= total_shards), prints
  5009. // an error and exits. If in_subprocess_for_death_test, sharding is
  5010. // disabled because it must only be applied to the original test
  5011. // process. Otherwise, we could filter out death tests we intended to execute.
  5012. bool ShouldShard(const char* total_shards_env,
  5013. const char* shard_index_env,
  5014. bool in_subprocess_for_death_test) {
  5015. if (in_subprocess_for_death_test) {
  5016. return false;
  5017. }
  5018. const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
  5019. const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
  5020. if (total_shards == -1 && shard_index == -1) {
  5021. return false;
  5022. } else if (total_shards == -1 && shard_index != -1) {
  5023. const Message msg = Message()
  5024. << "Invalid environment variables: you have "
  5025. << kTestShardIndex << " = " << shard_index
  5026. << ", but have left " << kTestTotalShards << " unset.\n";
  5027. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5028. fflush(stdout);
  5029. exit(EXIT_FAILURE);
  5030. } else if (total_shards != -1 && shard_index == -1) {
  5031. const Message msg = Message()
  5032. << "Invalid environment variables: you have "
  5033. << kTestTotalShards << " = " << total_shards
  5034. << ", but have left " << kTestShardIndex << " unset.\n";
  5035. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5036. fflush(stdout);
  5037. exit(EXIT_FAILURE);
  5038. } else if (shard_index < 0 || shard_index >= total_shards) {
  5039. const Message msg = Message()
  5040. << "Invalid environment variables: we require 0 <= "
  5041. << kTestShardIndex << " < " << kTestTotalShards
  5042. << ", but you have " << kTestShardIndex << "=" << shard_index
  5043. << ", " << kTestTotalShards << "=" << total_shards << ".\n";
  5044. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5045. fflush(stdout);
  5046. exit(EXIT_FAILURE);
  5047. }
  5048. return total_shards > 1;
  5049. }
  5050. // Parses the environment variable var as an Int32. If it is unset,
  5051. // returns default_val. If it is not an Int32, prints an error
  5052. // and aborts.
  5053. Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
  5054. const char* str_val = posix::GetEnv(var);
  5055. if (str_val == NULL) {
  5056. return default_val;
  5057. }
  5058. Int32 result;
  5059. if (!ParseInt32(Message() << "The value of environment variable " << var,
  5060. str_val, &result)) {
  5061. exit(EXIT_FAILURE);
  5062. }
  5063. return result;
  5064. }
  5065. // Given the total number of shards, the shard index, and the test id,
  5066. // returns true iff the test should be run on this shard. The test id is
  5067. // some arbitrary but unique non-negative integer assigned to each test
  5068. // method. Assumes that 0 <= shard_index < total_shards.
  5069. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
  5070. return (test_id % total_shards) == shard_index;
  5071. }
  5072. // Compares the name of each test with the user-specified filter to
  5073. // decide whether the test should be run, then records the result in
  5074. // each TestCase and TestInfo object.
  5075. // If shard_tests == true, further filters tests based on sharding
  5076. // variables in the environment - see
  5077. // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
  5078. // Returns the number of tests that should run.
  5079. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
  5080. const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
  5081. Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
  5082. const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
  5083. Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
  5084. // num_runnable_tests are the number of tests that will
  5085. // run across all shards (i.e., match filter and are not disabled).
  5086. // num_selected_tests are the number of tests to be run on
  5087. // this shard.
  5088. int num_runnable_tests = 0;
  5089. int num_selected_tests = 0;
  5090. for (size_t i = 0; i < test_cases_.size(); i++) {
  5091. TestCase* const test_case = test_cases_[i];
  5092. const std::string &test_case_name = test_case->name();
  5093. test_case->set_should_run(false);
  5094. for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  5095. TestInfo* const test_info = test_case->test_info_list()[j];
  5096. const std::string test_name(test_info->name());
  5097. // A test is disabled if test case name or test name matches
  5098. // kDisableTestFilter.
  5099. const bool is_disabled =
  5100. internal::UnitTestOptions::MatchesFilter(test_case_name,
  5101. kDisableTestFilter) ||
  5102. internal::UnitTestOptions::MatchesFilter(test_name,
  5103. kDisableTestFilter);
  5104. test_info->is_disabled_ = is_disabled;
  5105. const bool matches_filter =
  5106. internal::UnitTestOptions::FilterMatchesTest(test_case_name,
  5107. test_name);
  5108. test_info->matches_filter_ = matches_filter;
  5109. const bool is_runnable =
  5110. (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
  5111. matches_filter;
  5112. const bool is_selected = is_runnable &&
  5113. (shard_tests == IGNORE_SHARDING_PROTOCOL ||
  5114. ShouldRunTestOnShard(total_shards, shard_index,
  5115. num_runnable_tests));
  5116. num_runnable_tests += is_runnable;
  5117. num_selected_tests += is_selected;
  5118. test_info->should_run_ = is_selected;
  5119. test_case->set_should_run(test_case->should_run() || is_selected);
  5120. }
  5121. }
  5122. return num_selected_tests;
  5123. }
  5124. // Prints the given C-string on a single line by replacing all '\n'
  5125. // characters with string "\\n". If the output takes more than
  5126. // max_length characters, only prints the first max_length characters
  5127. // and "...".
  5128. static void PrintOnOneLine(const char* str, int max_length) {
  5129. if (str != NULL) {
  5130. for (int i = 0; *str != '\0'; ++str) {
  5131. if (i >= max_length) {
  5132. printf("...");
  5133. break;
  5134. }
  5135. if (*str == '\n') {
  5136. printf("\\n");
  5137. i += 2;
  5138. } else {
  5139. printf("%c", *str);
  5140. ++i;
  5141. }
  5142. }
  5143. }
  5144. }
  5145. // Prints the names of the tests matching the user-specified filter flag.
  5146. void UnitTestImpl::ListTestsMatchingFilter() {
  5147. // Print at most this many characters for each type/value parameter.
  5148. const int kMaxParamLength = 250;
  5149. for (size_t i = 0; i < test_cases_.size(); i++) {
  5150. const TestCase* const test_case = test_cases_[i];
  5151. bool printed_test_case_name = false;
  5152. for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  5153. const TestInfo* const test_info =
  5154. test_case->test_info_list()[j];
  5155. if (test_info->matches_filter_) {
  5156. if (!printed_test_case_name) {
  5157. printed_test_case_name = true;
  5158. printf("%s.", test_case->name());
  5159. if (test_case->type_param() != NULL) {
  5160. printf(" # %s = ", kTypeParamLabel);
  5161. // We print the type parameter on a single line to make
  5162. // the output easy to parse by a program.
  5163. PrintOnOneLine(test_case->type_param(), kMaxParamLength);
  5164. }
  5165. printf("\n");
  5166. }
  5167. printf(" %s", test_info->name());
  5168. if (test_info->value_param() != NULL) {
  5169. printf(" # %s = ", kValueParamLabel);
  5170. // We print the value parameter on a single line to make the
  5171. // output easy to parse by a program.
  5172. PrintOnOneLine(test_info->value_param(), kMaxParamLength);
  5173. }
  5174. printf("\n");
  5175. }
  5176. }
  5177. }
  5178. fflush(stdout);
  5179. }
  5180. // Sets the OS stack trace getter.
  5181. //
  5182. // Does nothing if the input and the current OS stack trace getter are
  5183. // the same; otherwise, deletes the old getter and makes the input the
  5184. // current getter.
  5185. void UnitTestImpl::set_os_stack_trace_getter(
  5186. OsStackTraceGetterInterface* getter) {
  5187. if (os_stack_trace_getter_ != getter) {
  5188. delete os_stack_trace_getter_;
  5189. os_stack_trace_getter_ = getter;
  5190. }
  5191. }
  5192. // Returns the current OS stack trace getter if it is not NULL;
  5193. // otherwise, creates an OsStackTraceGetter, makes it the current
  5194. // getter, and returns it.
  5195. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
  5196. if (os_stack_trace_getter_ == NULL) {
  5197. os_stack_trace_getter_ = new OsStackTraceGetter;
  5198. }
  5199. return os_stack_trace_getter_;
  5200. }
  5201. // Returns the TestResult for the test that's currently running, or
  5202. // the TestResult for the ad hoc test if no test is running.
  5203. TestResult* UnitTestImpl::current_test_result() {
  5204. return current_test_info_ ?
  5205. &(current_test_info_->result_) : &ad_hoc_test_result_;
  5206. }
  5207. // Shuffles all test cases, and the tests within each test case,
  5208. // making sure that death tests are still run first.
  5209. void UnitTestImpl::ShuffleTests() {
  5210. // Shuffles the death test cases.
  5211. ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
  5212. // Shuffles the non-death test cases.
  5213. ShuffleRange(random(), last_death_test_case_ + 1,
  5214. static_cast<int>(test_cases_.size()), &test_case_indices_);
  5215. // Shuffles the tests inside each test case.
  5216. for (size_t i = 0; i < test_cases_.size(); i++) {
  5217. test_cases_[i]->ShuffleTests(random());
  5218. }
  5219. }
  5220. // Restores the test cases and tests to their order before the first shuffle.
  5221. void UnitTestImpl::UnshuffleTests() {
  5222. for (size_t i = 0; i < test_cases_.size(); i++) {
  5223. // Unshuffles the tests in each test case.
  5224. test_cases_[i]->UnshuffleTests();
  5225. // Resets the index of each test case.
  5226. test_case_indices_[i] = static_cast<int>(i);
  5227. }
  5228. }
  5229. // Returns the current OS stack trace as an std::string.
  5230. //
  5231. // The maximum number of stack frames to be included is specified by
  5232. // the gtest_stack_trace_depth flag. The skip_count parameter
  5233. // specifies the number of top frames to be skipped, which doesn't
  5234. // count against the number of frames to be included.
  5235. //
  5236. // For example, if Foo() calls Bar(), which in turn calls
  5237. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  5238. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  5239. std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
  5240. int skip_count) {
  5241. // We pass skip_count + 1 to skip this wrapper function in addition
  5242. // to what the user really wants to skip.
  5243. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
  5244. }
  5245. // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
  5246. // suppress unreachable code warnings.
  5247. namespace {
  5248. class ClassUniqueToAlwaysTrue {};
  5249. }
  5250. bool IsTrue(bool condition) { return condition; }
  5251. bool AlwaysTrue() {
  5252. #if GTEST_HAS_EXCEPTIONS
  5253. // This condition is always false so AlwaysTrue() never actually throws,
  5254. // but it makes the compiler think that it may throw.
  5255. if (IsTrue(false))
  5256. throw ClassUniqueToAlwaysTrue();
  5257. #endif // GTEST_HAS_EXCEPTIONS
  5258. return true;
  5259. }
  5260. // If *pstr starts with the given prefix, modifies *pstr to be right
  5261. // past the prefix and returns true; otherwise leaves *pstr unchanged
  5262. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  5263. bool SkipPrefix(const char* prefix, const char** pstr) {
  5264. const size_t prefix_len = strlen(prefix);
  5265. if (strncmp(*pstr, prefix, prefix_len) == 0) {
  5266. *pstr += prefix_len;
  5267. return true;
  5268. }
  5269. return false;
  5270. }
  5271. // Parses a string as a command line flag. The string should have
  5272. // the format "--flag=value". When def_optional is true, the "=value"
  5273. // part can be omitted.
  5274. //
  5275. // Returns the value of the flag, or NULL if the parsing failed.
  5276. const char* ParseFlagValue(const char* str,
  5277. const char* flag,
  5278. bool def_optional) {
  5279. // str and flag must not be NULL.
  5280. if (str == NULL || flag == NULL) return NULL;
  5281. // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
  5282. const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
  5283. const size_t flag_len = flag_str.length();
  5284. if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
  5285. // Skips the flag name.
  5286. const char* flag_end = str + flag_len;
  5287. // When def_optional is true, it's OK to not have a "=value" part.
  5288. if (def_optional && (flag_end[0] == '\0')) {
  5289. return flag_end;
  5290. }
  5291. // If def_optional is true and there are more characters after the
  5292. // flag name, or if def_optional is false, there must be a '=' after
  5293. // the flag name.
  5294. if (flag_end[0] != '=') return NULL;
  5295. // Returns the string after "=".
  5296. return flag_end + 1;
  5297. }
  5298. // Parses a string for a bool flag, in the form of either
  5299. // "--flag=value" or "--flag".
  5300. //
  5301. // In the former case, the value is taken as true as long as it does
  5302. // not start with '0', 'f', or 'F'.
  5303. //
  5304. // In the latter case, the value is taken as true.
  5305. //
  5306. // On success, stores the value of the flag in *value, and returns
  5307. // true. On failure, returns false without changing *value.
  5308. bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
  5309. // Gets the value of the flag as a string.
  5310. const char* const value_str = ParseFlagValue(str, flag, true);
  5311. // Aborts if the parsing failed.
  5312. if (value_str == NULL) return false;
  5313. // Converts the string value to a bool.
  5314. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  5315. return true;
  5316. }
  5317. // Parses a string for an Int32 flag, in the form of
  5318. // "--flag=value".
  5319. //
  5320. // On success, stores the value of the flag in *value, and returns
  5321. // true. On failure, returns false without changing *value.
  5322. bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
  5323. // Gets the value of the flag as a string.
  5324. const char* const value_str = ParseFlagValue(str, flag, false);
  5325. // Aborts if the parsing failed.
  5326. if (value_str == NULL) return false;
  5327. // Sets *value to the value of the flag.
  5328. return ParseInt32(Message() << "The value of flag --" << flag,
  5329. value_str, value);
  5330. }
  5331. // Parses a string for a string flag, in the form of
  5332. // "--flag=value".
  5333. //
  5334. // On success, stores the value of the flag in *value, and returns
  5335. // true. On failure, returns false without changing *value.
  5336. bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
  5337. // Gets the value of the flag as a string.
  5338. const char* const value_str = ParseFlagValue(str, flag, false);
  5339. // Aborts if the parsing failed.
  5340. if (value_str == NULL) return false;
  5341. // Sets *value to the value of the flag.
  5342. *value = value_str;
  5343. return true;
  5344. }
  5345. // Determines whether a string has a prefix that Google Test uses for its
  5346. // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
  5347. // If Google Test detects that a command line flag has its prefix but is not
  5348. // recognized, it will print its help message. Flags starting with
  5349. // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
  5350. // internal flags and do not trigger the help message.
  5351. static bool HasGoogleTestFlagPrefix(const char* str) {
  5352. return (SkipPrefix("--", &str) ||
  5353. SkipPrefix("-", &str) ||
  5354. SkipPrefix("/", &str)) &&
  5355. !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
  5356. (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
  5357. SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
  5358. }
  5359. // Prints a string containing code-encoded text. The following escape
  5360. // sequences can be used in the string to control the text color:
  5361. //
  5362. // @@ prints a single '@' character.
  5363. // @R changes the color to red.
  5364. // @G changes the color to green.
  5365. // @Y changes the color to yellow.
  5366. // @D changes to the default terminal text color.
  5367. //
  5368. // TODO(wan@google.com): Write tests for this once we add stdout
  5369. // capturing to Google Test.
  5370. static void PrintColorEncoded(const char* str) {
  5371. GTestColor color = COLOR_DEFAULT; // The current color.
  5372. // Conceptually, we split the string into segments divided by escape
  5373. // sequences. Then we print one segment at a time. At the end of
  5374. // each iteration, the str pointer advances to the beginning of the
  5375. // next segment.
  5376. for (;;) {
  5377. const char* p = strchr(str, '@');
  5378. if (p == NULL) {
  5379. ColoredPrintf(color, "%s", str);
  5380. return;
  5381. }
  5382. ColoredPrintf(color, "%s", std::string(str, p).c_str());
  5383. const char ch = p[1];
  5384. str = p + 2;
  5385. if (ch == '@') {
  5386. ColoredPrintf(color, "@");
  5387. } else if (ch == 'D') {
  5388. color = COLOR_DEFAULT;
  5389. } else if (ch == 'R') {
  5390. color = COLOR_RED;
  5391. } else if (ch == 'G') {
  5392. color = COLOR_GREEN;
  5393. } else if (ch == 'Y') {
  5394. color = COLOR_YELLOW;
  5395. } else {
  5396. --str;
  5397. }
  5398. }
  5399. }
  5400. static const char kColorEncodedHelpMessage[] =
  5401. "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
  5402. "following command line flags to control its behavior:\n"
  5403. "\n"
  5404. "Test Selection:\n"
  5405. " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
  5406. " List the names of all tests instead of running them. The name of\n"
  5407. " TEST(Foo, Bar) is \"Foo.Bar\".\n"
  5408. " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
  5409. "[@G-@YNEGATIVE_PATTERNS]@D\n"
  5410. " Run only the tests whose name matches one of the positive patterns but\n"
  5411. " none of the negative patterns. '?' matches any single character; '*'\n"
  5412. " matches any substring; ':' separates two patterns.\n"
  5413. " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
  5414. " Run all disabled tests too.\n"
  5415. "\n"
  5416. "Test Execution:\n"
  5417. " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
  5418. " Run the tests repeatedly; use a negative count to repeat forever.\n"
  5419. " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
  5420. " Randomize tests' orders on every iteration.\n"
  5421. " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
  5422. " Random number seed to use for shuffling test orders (between 1 and\n"
  5423. " 99999, or 0 to use a seed based on the current time).\n"
  5424. "\n"
  5425. "Test Output:\n"
  5426. " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
  5427. " Enable/disable colored output. The default is @Gauto@D.\n"
  5428. " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
  5429. " Don't print the elapsed time of each test.\n"
  5430. " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
  5431. GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
  5432. " Generate an XML report in the given directory or with the given file\n"
  5433. " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
  5434. #if GTEST_CAN_STREAM_RESULTS_
  5435. " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
  5436. " Stream test results to the given server.\n"
  5437. #endif // GTEST_CAN_STREAM_RESULTS_
  5438. "\n"
  5439. "Assertion Behavior:\n"
  5440. #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  5441. " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
  5442. " Set the default death test style.\n"
  5443. #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  5444. " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
  5445. " Turn assertion failures into debugger break-points.\n"
  5446. " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
  5447. " Turn assertion failures into C++ exceptions.\n"
  5448. " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
  5449. " Do not report exceptions as test failures. Instead, allow them\n"
  5450. " to crash the program or throw a pop-up (on Windows).\n"
  5451. "\n"
  5452. "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
  5453. "the corresponding\n"
  5454. "environment variable of a flag (all letters in upper-case). For example, to\n"
  5455. "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
  5456. "color=no@D or set\n"
  5457. "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
  5458. "\n"
  5459. "For more information, please read the " GTEST_NAME_ " documentation at\n"
  5460. "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
  5461. "(not one in your own code or tests), please report it to\n"
  5462. "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
  5463. // Parses the command line for Google Test flags, without initializing
  5464. // other parts of Google Test. The type parameter CharType can be
  5465. // instantiated to either char or wchar_t.
  5466. template <typename CharType>
  5467. void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
  5468. for (int i = 1; i < *argc; i++) {
  5469. const std::string arg_string = StreamableToString(argv[i]);
  5470. const char* const arg = arg_string.c_str();
  5471. using internal::ParseBoolFlag;
  5472. using internal::ParseInt32Flag;
  5473. using internal::ParseStringFlag;
  5474. // Do we see a Google Test flag?
  5475. if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
  5476. &GTEST_FLAG(also_run_disabled_tests)) ||
  5477. ParseBoolFlag(arg, kBreakOnFailureFlag,
  5478. &GTEST_FLAG(break_on_failure)) ||
  5479. ParseBoolFlag(arg, kCatchExceptionsFlag,
  5480. &GTEST_FLAG(catch_exceptions)) ||
  5481. ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
  5482. ParseStringFlag(arg, kDeathTestStyleFlag,
  5483. &GTEST_FLAG(death_test_style)) ||
  5484. ParseBoolFlag(arg, kDeathTestUseFork,
  5485. &GTEST_FLAG(death_test_use_fork)) ||
  5486. ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
  5487. ParseStringFlag(arg, kInternalRunDeathTestFlag,
  5488. &GTEST_FLAG(internal_run_death_test)) ||
  5489. ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
  5490. ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
  5491. ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
  5492. ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
  5493. ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
  5494. ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
  5495. ParseInt32Flag(arg, kStackTraceDepthFlag,
  5496. &GTEST_FLAG(stack_trace_depth)) ||
  5497. ParseStringFlag(arg, kStreamResultToFlag,
  5498. &GTEST_FLAG(stream_result_to)) ||
  5499. ParseBoolFlag(arg, kThrowOnFailureFlag,
  5500. &GTEST_FLAG(throw_on_failure))
  5501. ) {
  5502. // Yes. Shift the remainder of the argv list left by one. Note
  5503. // that argv has (*argc + 1) elements, the last one always being
  5504. // NULL. The following loop moves the trailing NULL element as
  5505. // well.
  5506. for (int j = i; j != *argc; j++) {
  5507. argv[j] = argv[j + 1];
  5508. }
  5509. // Decrements the argument count.
  5510. (*argc)--;
  5511. // We also need to decrement the iterator as we just removed
  5512. // an element.
  5513. i--;
  5514. } else if (arg_string == "--help" || arg_string == "-h" ||
  5515. arg_string == "-?" || arg_string == "/?" ||
  5516. HasGoogleTestFlagPrefix(arg)) {
  5517. // Both help flag and unrecognized Google Test flags (excluding
  5518. // internal ones) trigger help display.
  5519. g_help_flag = true;
  5520. }
  5521. }
  5522. if (g_help_flag) {
  5523. // We print the help here instead of in RUN_ALL_TESTS(), as the
  5524. // latter may not be called at all if the user is using Google
  5525. // Test with another testing framework.
  5526. PrintColorEncoded(kColorEncodedHelpMessage);
  5527. }
  5528. }
  5529. // Parses the command line for Google Test flags, without initializing
  5530. // other parts of Google Test.
  5531. void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
  5532. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  5533. }
  5534. void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
  5535. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  5536. }
  5537. // The internal implementation of InitGoogleTest().
  5538. //
  5539. // The type parameter CharType can be instantiated to either char or
  5540. // wchar_t.
  5541. template <typename CharType>
  5542. void InitGoogleTestImpl(int* argc, CharType** argv) {
  5543. g_init_gtest_count++;
  5544. // We don't want to run the initialization code twice.
  5545. if (g_init_gtest_count != 1) return;
  5546. if (*argc <= 0) return;
  5547. internal::g_executable_path = internal::StreamableToString(argv[0]);
  5548. #if GTEST_HAS_DEATH_TEST
  5549. g_argvs.clear();
  5550. for (int i = 0; i != *argc; i++) {
  5551. g_argvs.push_back(StreamableToString(argv[i]));
  5552. }
  5553. #endif // GTEST_HAS_DEATH_TEST
  5554. ParseGoogleTestFlagsOnly(argc, argv);
  5555. GetUnitTestImpl()->PostFlagParsingInit();
  5556. }
  5557. } // namespace internal
  5558. // Initializes Google Test. This must be called before calling
  5559. // RUN_ALL_TESTS(). In particular, it parses a command line for the
  5560. // flags that Google Test recognizes. Whenever a Google Test flag is
  5561. // seen, it is removed from argv, and *argc is decremented.
  5562. //
  5563. // No value is returned. Instead, the Google Test flag variables are
  5564. // updated.
  5565. //
  5566. // Calling the function for the second time has no user-visible effect.
  5567. void InitGoogleTest(int* argc, char** argv) {
  5568. internal::InitGoogleTestImpl(argc, argv);
  5569. }
  5570. // This overloaded version can be used in Windows programs compiled in
  5571. // UNICODE mode.
  5572. void InitGoogleTest(int* argc, wchar_t** argv) {
  5573. internal::InitGoogleTestImpl(argc, argv);
  5574. }
  5575. } // namespace testing
  5576. // Copyright 2005, Google Inc.
  5577. // All rights reserved.
  5578. //
  5579. // Redistribution and use in source and binary forms, with or without
  5580. // modification, are permitted provided that the following conditions are
  5581. // met:
  5582. //
  5583. // * Redistributions of source code must retain the above copyright
  5584. // notice, this list of conditions and the following disclaimer.
  5585. // * Redistributions in binary form must reproduce the above
  5586. // copyright notice, this list of conditions and the following disclaimer
  5587. // in the documentation and/or other materials provided with the
  5588. // distribution.
  5589. // * Neither the name of Google Inc. nor the names of its
  5590. // contributors may be used to endorse or promote products derived from
  5591. // this software without specific prior written permission.
  5592. //
  5593. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  5594. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5595. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  5596. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  5597. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  5598. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5599. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  5600. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  5601. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  5602. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  5603. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5604. //
  5605. // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
  5606. //
  5607. // This file implements death tests.
  5608. #if GTEST_HAS_DEATH_TEST
  5609. # if GTEST_OS_MAC
  5610. # include <crt_externs.h>
  5611. # endif // GTEST_OS_MAC
  5612. # include <errno.h>
  5613. # include <fcntl.h>
  5614. # include <limits.h>
  5615. # if GTEST_OS_LINUX
  5616. # include <signal.h>
  5617. # endif // GTEST_OS_LINUX
  5618. # include <stdarg.h>
  5619. # if GTEST_OS_WINDOWS
  5620. # include <windows.h>
  5621. # else
  5622. # include <sys/mman.h>
  5623. # include <sys/wait.h>
  5624. # endif // GTEST_OS_WINDOWS
  5625. # if GTEST_OS_QNX
  5626. # include <spawn.h>
  5627. # endif // GTEST_OS_QNX
  5628. #endif // GTEST_HAS_DEATH_TEST
  5629. // Indicates that this translation unit is part of Google Test's
  5630. // implementation. It must come before gtest-internal-inl.h is
  5631. // included, or there will be a compiler error. This trick is to
  5632. // prevent a user from accidentally including gtest-internal-inl.h in
  5633. // his code.
  5634. #define GTEST_IMPLEMENTATION_ 1
  5635. #undef GTEST_IMPLEMENTATION_
  5636. namespace testing {
  5637. // Constants.
  5638. // The default death test style.
  5639. static const char kDefaultDeathTestStyle[] = "fast";
  5640. GTEST_DEFINE_string_(
  5641. death_test_style,
  5642. internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
  5643. "Indicates how to run a death test in a forked child process: "
  5644. "\"threadsafe\" (child process re-executes the test binary "
  5645. "from the beginning, running only the specific death test) or "
  5646. "\"fast\" (child process runs the death test immediately "
  5647. "after forking).");
  5648. GTEST_DEFINE_bool_(
  5649. death_test_use_fork,
  5650. internal::BoolFromGTestEnv("death_test_use_fork", false),
  5651. "Instructs to use fork()/_exit() instead of clone() in death tests. "
  5652. "Ignored and always uses fork() on POSIX systems where clone() is not "
  5653. "implemented. Useful when running under valgrind or similar tools if "
  5654. "those do not support clone(). Valgrind 3.3.1 will just fail if "
  5655. "it sees an unsupported combination of clone() flags. "
  5656. "It is not recommended to use this flag w/o valgrind though it will "
  5657. "work in 99% of the cases. Once valgrind is fixed, this flag will "
  5658. "most likely be removed.");
  5659. namespace internal {
  5660. GTEST_DEFINE_string_(
  5661. internal_run_death_test, "",
  5662. "Indicates the file, line number, temporal index of "
  5663. "the single death test to run, and a file descriptor to "
  5664. "which a success code may be sent, all separated by "
  5665. "the '|' characters. This flag is specified if and only if the current "
  5666. "process is a sub-process launched for running a thread-safe "
  5667. "death test. FOR INTERNAL USE ONLY.");
  5668. } // namespace internal
  5669. #if GTEST_HAS_DEATH_TEST
  5670. namespace internal {
  5671. // Valid only for fast death tests. Indicates the code is running in the
  5672. // child process of a fast style death test.
  5673. static bool g_in_fast_death_test_child = false;
  5674. // Returns a Boolean value indicating whether the caller is currently
  5675. // executing in the context of the death test child process. Tools such as
  5676. // Valgrind heap checkers may need this to modify their behavior in death
  5677. // tests. IMPORTANT: This is an internal utility. Using it may break the
  5678. // implementation of death tests. User code MUST NOT use it.
  5679. bool InDeathTestChild() {
  5680. # if GTEST_OS_WINDOWS
  5681. // On Windows, death tests are thread-safe regardless of the value of the
  5682. // death_test_style flag.
  5683. return !GTEST_FLAG(internal_run_death_test).empty();
  5684. # else
  5685. if (GTEST_FLAG(death_test_style) == "threadsafe")
  5686. return !GTEST_FLAG(internal_run_death_test).empty();
  5687. else
  5688. return g_in_fast_death_test_child;
  5689. #endif
  5690. }
  5691. } // namespace internal
  5692. // ExitedWithCode constructor.
  5693. ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
  5694. }
  5695. // ExitedWithCode function-call operator.
  5696. bool ExitedWithCode::operator()(int exit_status) const {
  5697. # if GTEST_OS_WINDOWS
  5698. return exit_status == exit_code_;
  5699. # else
  5700. return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
  5701. # endif // GTEST_OS_WINDOWS
  5702. }
  5703. # if !GTEST_OS_WINDOWS
  5704. // KilledBySignal constructor.
  5705. KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
  5706. }
  5707. // KilledBySignal function-call operator.
  5708. bool KilledBySignal::operator()(int exit_status) const {
  5709. return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
  5710. }
  5711. # endif // !GTEST_OS_WINDOWS
  5712. namespace internal {
  5713. // Utilities needed for death tests.
  5714. // Generates a textual description of a given exit code, in the format
  5715. // specified by wait(2).
  5716. static std::string ExitSummary(int exit_code) {
  5717. Message m;
  5718. # if GTEST_OS_WINDOWS
  5719. m << "Exited with exit status " << exit_code;
  5720. # else
  5721. if (WIFEXITED(exit_code)) {
  5722. m << "Exited with exit status " << WEXITSTATUS(exit_code);
  5723. } else if (WIFSIGNALED(exit_code)) {
  5724. m << "Terminated by signal " << WTERMSIG(exit_code);
  5725. }
  5726. # ifdef WCOREDUMP
  5727. if (WCOREDUMP(exit_code)) {
  5728. m << " (core dumped)";
  5729. }
  5730. # endif
  5731. # endif // GTEST_OS_WINDOWS
  5732. return m.GetString();
  5733. }
  5734. // Returns true if exit_status describes a process that was terminated
  5735. // by a signal, or exited normally with a nonzero exit code.
  5736. bool ExitedUnsuccessfully(int exit_status) {
  5737. return !ExitedWithCode(0)(exit_status);
  5738. }
  5739. # if !GTEST_OS_WINDOWS
  5740. // Generates a textual failure message when a death test finds more than
  5741. // one thread running, or cannot determine the number of threads, prior
  5742. // to executing the given statement. It is the responsibility of the
  5743. // caller not to pass a thread_count of 1.
  5744. static std::string DeathTestThreadWarning(size_t thread_count) {
  5745. Message msg;
  5746. msg << "Death tests use fork(), which is unsafe particularly"
  5747. << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
  5748. if (thread_count == 0)
  5749. msg << "couldn't detect the number of threads.";
  5750. else
  5751. msg << "detected " << thread_count << " threads.";
  5752. return msg.GetString();
  5753. }
  5754. # endif // !GTEST_OS_WINDOWS
  5755. // Flag characters for reporting a death test that did not die.
  5756. static const char kDeathTestLived = 'L';
  5757. static const char kDeathTestReturned = 'R';
  5758. static const char kDeathTestThrew = 'T';
  5759. static const char kDeathTestInternalError = 'I';
  5760. // An enumeration describing all of the possible ways that a death test can
  5761. // conclude. DIED means that the process died while executing the test
  5762. // code; LIVED means that process lived beyond the end of the test code;
  5763. // RETURNED means that the test statement attempted to execute a return
  5764. // statement, which is not allowed; THREW means that the test statement
  5765. // returned control by throwing an exception. IN_PROGRESS means the test
  5766. // has not yet concluded.
  5767. // TODO(vladl@google.com): Unify names and possibly values for
  5768. // AbortReason, DeathTestOutcome, and flag characters above.
  5769. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
  5770. // Routine for aborting the program which is safe to call from an
  5771. // exec-style death test child process, in which case the error
  5772. // message is propagated back to the parent process. Otherwise, the
  5773. // message is simply printed to stderr. In either case, the program
  5774. // then exits with status 1.
  5775. void DeathTestAbort(const std::string& message) {
  5776. // On a POSIX system, this function may be called from a threadsafe-style
  5777. // death test child process, which operates on a very small stack. Use
  5778. // the heap for any additional non-minuscule memory requirements.
  5779. const InternalRunDeathTestFlag* const flag =
  5780. GetUnitTestImpl()->internal_run_death_test_flag();
  5781. if (flag != NULL) {
  5782. FILE* parent = posix::FDOpen(flag->write_fd(), "w");
  5783. fputc(kDeathTestInternalError, parent);
  5784. fprintf(parent, "%s", message.c_str());
  5785. fflush(parent);
  5786. _exit(1);
  5787. } else {
  5788. fprintf(stderr, "%s", message.c_str());
  5789. fflush(stderr);
  5790. posix::Abort();
  5791. }
  5792. }
  5793. // A replacement for CHECK that calls DeathTestAbort if the assertion
  5794. // fails.
  5795. # define GTEST_DEATH_TEST_CHECK_(expression) \
  5796. do { \
  5797. if (!::testing::internal::IsTrue(expression)) { \
  5798. DeathTestAbort( \
  5799. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  5800. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  5801. + #expression); \
  5802. } \
  5803. } while (::testing::internal::AlwaysFalse())
  5804. // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
  5805. // evaluating any system call that fulfills two conditions: it must return
  5806. // -1 on failure, and set errno to EINTR when it is interrupted and
  5807. // should be tried again. The macro expands to a loop that repeatedly
  5808. // evaluates the expression as long as it evaluates to -1 and sets
  5809. // errno to EINTR. If the expression evaluates to -1 but errno is
  5810. // something other than EINTR, DeathTestAbort is called.
  5811. # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
  5812. do { \
  5813. int gtest_retval; \
  5814. do { \
  5815. gtest_retval = (expression); \
  5816. } while (gtest_retval == -1 && errno == EINTR); \
  5817. if (gtest_retval == -1) { \
  5818. DeathTestAbort( \
  5819. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  5820. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  5821. + #expression + " != -1"); \
  5822. } \
  5823. } while (::testing::internal::AlwaysFalse())
  5824. // Returns the message describing the last system error in errno.
  5825. std::string GetLastErrnoDescription() {
  5826. return errno == 0 ? "" : posix::StrError(errno);
  5827. }
  5828. // This is called from a death test parent process to read a failure
  5829. // message from the death test child process and log it with the FATAL
  5830. // severity. On Windows, the message is read from a pipe handle. On other
  5831. // platforms, it is read from a file descriptor.
  5832. static void FailFromInternalError(int fd) {
  5833. Message error;
  5834. char buffer[256];
  5835. int num_read;
  5836. do {
  5837. while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
  5838. buffer[num_read] = '\0';
  5839. error << buffer;
  5840. }
  5841. } while (num_read == -1 && errno == EINTR);
  5842. if (num_read == 0) {
  5843. GTEST_LOG_(FATAL) << error.GetString();
  5844. } else {
  5845. const int last_error = errno;
  5846. GTEST_LOG_(FATAL) << "Error while reading death test internal: "
  5847. << GetLastErrnoDescription() << " [" << last_error << "]";
  5848. }
  5849. }
  5850. // Death test constructor. Increments the running death test count
  5851. // for the current test.
  5852. DeathTest::DeathTest() {
  5853. TestInfo* const info = GetUnitTestImpl()->current_test_info();
  5854. if (info == NULL) {
  5855. DeathTestAbort("Cannot run a death test outside of a TEST or "
  5856. "TEST_F construct");
  5857. }
  5858. }
  5859. // Creates and returns a death test by dispatching to the current
  5860. // death test factory.
  5861. bool DeathTest::Create(const char* statement, const RE* regex,
  5862. const char* file, int line, DeathTest** test) {
  5863. return GetUnitTestImpl()->death_test_factory()->Create(
  5864. statement, regex, file, line, test);
  5865. }
  5866. const char* DeathTest::LastMessage() {
  5867. return last_death_test_message_.c_str();
  5868. }
  5869. void DeathTest::set_last_death_test_message(const std::string& message) {
  5870. last_death_test_message_ = message;
  5871. }
  5872. std::string DeathTest::last_death_test_message_;
  5873. // Provides cross platform implementation for some death functionality.
  5874. class DeathTestImpl : public DeathTest {
  5875. protected:
  5876. DeathTestImpl(const char* a_statement, const RE* a_regex)
  5877. : statement_(a_statement),
  5878. regex_(a_regex),
  5879. spawned_(false),
  5880. status_(-1),
  5881. outcome_(IN_PROGRESS),
  5882. read_fd_(-1),
  5883. write_fd_(-1) {}
  5884. // read_fd_ is expected to be closed and cleared by a derived class.
  5885. ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
  5886. void Abort(AbortReason reason);
  5887. virtual bool Passed(bool status_ok);
  5888. const char* statement() const { return statement_; }
  5889. const RE* regex() const { return regex_; }
  5890. bool spawned() const { return spawned_; }
  5891. void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
  5892. int status() const { return status_; }
  5893. void set_status(int a_status) { status_ = a_status; }
  5894. DeathTestOutcome outcome() const { return outcome_; }
  5895. void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
  5896. int read_fd() const { return read_fd_; }
  5897. void set_read_fd(int fd) { read_fd_ = fd; }
  5898. int write_fd() const { return write_fd_; }
  5899. void set_write_fd(int fd) { write_fd_ = fd; }
  5900. // Called in the parent process only. Reads the result code of the death
  5901. // test child process via a pipe, interprets it to set the outcome_
  5902. // member, and closes read_fd_. Outputs diagnostics and terminates in
  5903. // case of unexpected codes.
  5904. void ReadAndInterpretStatusByte();
  5905. private:
  5906. // The textual content of the code this object is testing. This class
  5907. // doesn't own this string and should not attempt to delete it.
  5908. const char* const statement_;
  5909. // The regular expression which test output must match. DeathTestImpl
  5910. // doesn't own this object and should not attempt to delete it.
  5911. const RE* const regex_;
  5912. // True if the death test child process has been successfully spawned.
  5913. bool spawned_;
  5914. // The exit status of the child process.
  5915. int status_;
  5916. // How the death test concluded.
  5917. DeathTestOutcome outcome_;
  5918. // Descriptor to the read end of the pipe to the child process. It is
  5919. // always -1 in the child process. The child keeps its write end of the
  5920. // pipe in write_fd_.
  5921. int read_fd_;
  5922. // Descriptor to the child's write end of the pipe to the parent process.
  5923. // It is always -1 in the parent process. The parent keeps its end of the
  5924. // pipe in read_fd_.
  5925. int write_fd_;
  5926. };
  5927. // Called in the parent process only. Reads the result code of the death
  5928. // test child process via a pipe, interprets it to set the outcome_
  5929. // member, and closes read_fd_. Outputs diagnostics and terminates in
  5930. // case of unexpected codes.
  5931. void DeathTestImpl::ReadAndInterpretStatusByte() {
  5932. char flag;
  5933. int bytes_read;
  5934. // The read() here blocks until data is available (signifying the
  5935. // failure of the death test) or until the pipe is closed (signifying
  5936. // its success), so it's okay to call this in the parent before
  5937. // the child process has exited.
  5938. do {
  5939. bytes_read = posix::Read(read_fd(), &flag, 1);
  5940. } while (bytes_read == -1 && errno == EINTR);
  5941. if (bytes_read == 0) {
  5942. set_outcome(DIED);
  5943. } else if (bytes_read == 1) {
  5944. switch (flag) {
  5945. case kDeathTestReturned:
  5946. set_outcome(RETURNED);
  5947. break;
  5948. case kDeathTestThrew:
  5949. set_outcome(THREW);
  5950. break;
  5951. case kDeathTestLived:
  5952. set_outcome(LIVED);
  5953. break;
  5954. case kDeathTestInternalError:
  5955. FailFromInternalError(read_fd()); // Does not return.
  5956. break;
  5957. default:
  5958. GTEST_LOG_(FATAL) << "Death test child process reported "
  5959. << "unexpected status byte ("
  5960. << static_cast<unsigned int>(flag) << ")";
  5961. }
  5962. } else {
  5963. GTEST_LOG_(FATAL) << "Read from death test child process failed: "
  5964. << GetLastErrnoDescription();
  5965. }
  5966. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
  5967. set_read_fd(-1);
  5968. }
  5969. // Signals that the death test code which should have exited, didn't.
  5970. // Should be called only in a death test child process.
  5971. // Writes a status byte to the child's status file descriptor, then
  5972. // calls _exit(1).
  5973. void DeathTestImpl::Abort(AbortReason reason) {
  5974. // The parent process considers the death test to be a failure if
  5975. // it finds any data in our pipe. So, here we write a single flag byte
  5976. // to the pipe, then exit.
  5977. const char status_ch =
  5978. reason == TEST_DID_NOT_DIE ? kDeathTestLived :
  5979. reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
  5980. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
  5981. // We are leaking the descriptor here because on some platforms (i.e.,
  5982. // when built as Windows DLL), destructors of global objects will still
  5983. // run after calling _exit(). On such systems, write_fd_ will be
  5984. // indirectly closed from the destructor of UnitTestImpl, causing double
  5985. // close if it is also closed here. On debug configurations, double close
  5986. // may assert. As there are no in-process buffers to flush here, we are
  5987. // relying on the OS to close the descriptor after the process terminates
  5988. // when the destructors are not run.
  5989. _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
  5990. }
  5991. // Returns an indented copy of stderr output for a death test.
  5992. // This makes distinguishing death test output lines from regular log lines
  5993. // much easier.
  5994. static ::std::string FormatDeathTestOutput(const ::std::string& output) {
  5995. ::std::string ret;
  5996. for (size_t at = 0; ; ) {
  5997. const size_t line_end = output.find('\n', at);
  5998. ret += "[ DEATH ] ";
  5999. if (line_end == ::std::string::npos) {
  6000. ret += output.substr(at);
  6001. break;
  6002. }
  6003. ret += output.substr(at, line_end + 1 - at);
  6004. at = line_end + 1;
  6005. }
  6006. return ret;
  6007. }
  6008. // Assesses the success or failure of a death test, using both private
  6009. // members which have previously been set, and one argument:
  6010. //
  6011. // Private data members:
  6012. // outcome: An enumeration describing how the death test
  6013. // concluded: DIED, LIVED, THREW, or RETURNED. The death test
  6014. // fails in the latter three cases.
  6015. // status: The exit status of the child process. On *nix, it is in the
  6016. // in the format specified by wait(2). On Windows, this is the
  6017. // value supplied to the ExitProcess() API or a numeric code
  6018. // of the exception that terminated the program.
  6019. // regex: A regular expression object to be applied to
  6020. // the test's captured standard error output; the death test
  6021. // fails if it does not match.
  6022. //
  6023. // Argument:
  6024. // status_ok: true if exit_status is acceptable in the context of
  6025. // this particular death test, which fails if it is false
  6026. //
  6027. // Returns true iff all of the above conditions are met. Otherwise, the
  6028. // first failing condition, in the order given above, is the one that is
  6029. // reported. Also sets the last death test message string.
  6030. bool DeathTestImpl::Passed(bool status_ok) {
  6031. if (!spawned())
  6032. return false;
  6033. const std::string error_message = GetCapturedStderr();
  6034. bool success = false;
  6035. Message buffer;
  6036. buffer << "Death test: " << statement() << "\n";
  6037. switch (outcome()) {
  6038. case LIVED:
  6039. buffer << " Result: failed to die.\n"
  6040. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6041. break;
  6042. case THREW:
  6043. buffer << " Result: threw an exception.\n"
  6044. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6045. break;
  6046. case RETURNED:
  6047. buffer << " Result: illegal return in test statement.\n"
  6048. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6049. break;
  6050. case DIED:
  6051. if (status_ok) {
  6052. const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
  6053. if (matched) {
  6054. success = true;
  6055. } else {
  6056. buffer << " Result: died but not with expected error.\n"
  6057. << " Expected: " << regex()->pattern() << "\n"
  6058. << "Actual msg:\n" << FormatDeathTestOutput(error_message);
  6059. }
  6060. } else {
  6061. buffer << " Result: died but not with expected exit code:\n"
  6062. << " " << ExitSummary(status()) << "\n"
  6063. << "Actual msg:\n" << FormatDeathTestOutput(error_message);
  6064. }
  6065. break;
  6066. case IN_PROGRESS:
  6067. default:
  6068. GTEST_LOG_(FATAL)
  6069. << "DeathTest::Passed somehow called before conclusion of test";
  6070. }
  6071. DeathTest::set_last_death_test_message(buffer.GetString());
  6072. return success;
  6073. }
  6074. # if GTEST_OS_WINDOWS
  6075. // WindowsDeathTest implements death tests on Windows. Due to the
  6076. // specifics of starting new processes on Windows, death tests there are
  6077. // always threadsafe, and Google Test considers the
  6078. // --gtest_death_test_style=fast setting to be equivalent to
  6079. // --gtest_death_test_style=threadsafe there.
  6080. //
  6081. // A few implementation notes: Like the Linux version, the Windows
  6082. // implementation uses pipes for child-to-parent communication. But due to
  6083. // the specifics of pipes on Windows, some extra steps are required:
  6084. //
  6085. // 1. The parent creates a communication pipe and stores handles to both
  6086. // ends of it.
  6087. // 2. The parent starts the child and provides it with the information
  6088. // necessary to acquire the handle to the write end of the pipe.
  6089. // 3. The child acquires the write end of the pipe and signals the parent
  6090. // using a Windows event.
  6091. // 4. Now the parent can release the write end of the pipe on its side. If
  6092. // this is done before step 3, the object's reference count goes down to
  6093. // 0 and it is destroyed, preventing the child from acquiring it. The
  6094. // parent now has to release it, or read operations on the read end of
  6095. // the pipe will not return when the child terminates.
  6096. // 5. The parent reads child's output through the pipe (outcome code and
  6097. // any possible error messages) from the pipe, and its stderr and then
  6098. // determines whether to fail the test.
  6099. //
  6100. // Note: to distinguish Win32 API calls from the local method and function
  6101. // calls, the former are explicitly resolved in the global namespace.
  6102. //
  6103. class WindowsDeathTest : public DeathTestImpl {
  6104. public:
  6105. WindowsDeathTest(const char* a_statement,
  6106. const RE* a_regex,
  6107. const char* file,
  6108. int line)
  6109. : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
  6110. // All of these virtual functions are inherited from DeathTest.
  6111. virtual int Wait();
  6112. virtual TestRole AssumeRole();
  6113. private:
  6114. // The name of the file in which the death test is located.
  6115. const char* const file_;
  6116. // The line number on which the death test is located.
  6117. const int line_;
  6118. // Handle to the write end of the pipe to the child process.
  6119. AutoHandle write_handle_;
  6120. // Child process handle.
  6121. AutoHandle child_handle_;
  6122. // Event the child process uses to signal the parent that it has
  6123. // acquired the handle to the write end of the pipe. After seeing this
  6124. // event the parent can release its own handles to make sure its
  6125. // ReadFile() calls return when the child terminates.
  6126. AutoHandle event_handle_;
  6127. };
  6128. // Waits for the child in a death test to exit, returning its exit
  6129. // status, or 0 if no child process exists. As a side effect, sets the
  6130. // outcome data member.
  6131. int WindowsDeathTest::Wait() {
  6132. if (!spawned())
  6133. return 0;
  6134. // Wait until the child either signals that it has acquired the write end
  6135. // of the pipe or it dies.
  6136. const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
  6137. switch (::WaitForMultipleObjects(2,
  6138. wait_handles,
  6139. FALSE, // Waits for any of the handles.
  6140. INFINITE)) {
  6141. case WAIT_OBJECT_0:
  6142. case WAIT_OBJECT_0 + 1:
  6143. break;
  6144. default:
  6145. GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
  6146. }
  6147. // The child has acquired the write end of the pipe or exited.
  6148. // We release the handle on our side and continue.
  6149. write_handle_.Reset();
  6150. event_handle_.Reset();
  6151. ReadAndInterpretStatusByte();
  6152. // Waits for the child process to exit if it haven't already. This
  6153. // returns immediately if the child has already exited, regardless of
  6154. // whether previous calls to WaitForMultipleObjects synchronized on this
  6155. // handle or not.
  6156. GTEST_DEATH_TEST_CHECK_(
  6157. WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
  6158. INFINITE));
  6159. DWORD status_code;
  6160. GTEST_DEATH_TEST_CHECK_(
  6161. ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
  6162. child_handle_.Reset();
  6163. set_status(static_cast<int>(status_code));
  6164. return status();
  6165. }
  6166. // The AssumeRole process for a Windows death test. It creates a child
  6167. // process with the same executable as the current process to run the
  6168. // death test. The child process is given the --gtest_filter and
  6169. // --gtest_internal_run_death_test flags such that it knows to run the
  6170. // current death test only.
  6171. DeathTest::TestRole WindowsDeathTest::AssumeRole() {
  6172. const UnitTestImpl* const impl = GetUnitTestImpl();
  6173. const InternalRunDeathTestFlag* const flag =
  6174. impl->internal_run_death_test_flag();
  6175. const TestInfo* const info = impl->current_test_info();
  6176. const int death_test_index = info->result()->death_test_count();
  6177. if (flag != NULL) {
  6178. // ParseInternalRunDeathTestFlag() has performed all the necessary
  6179. // processing.
  6180. set_write_fd(flag->write_fd());
  6181. return EXECUTE_TEST;
  6182. }
  6183. // WindowsDeathTest uses an anonymous pipe to communicate results of
  6184. // a death test.
  6185. SECURITY_ATTRIBUTES handles_are_inheritable = {
  6186. sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
  6187. HANDLE read_handle, write_handle;
  6188. GTEST_DEATH_TEST_CHECK_(
  6189. ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
  6190. 0) // Default buffer size.
  6191. != FALSE);
  6192. set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
  6193. O_RDONLY));
  6194. write_handle_.Reset(write_handle);
  6195. event_handle_.Reset(::CreateEvent(
  6196. &handles_are_inheritable,
  6197. TRUE, // The event will automatically reset to non-signaled state.
  6198. FALSE, // The initial state is non-signalled.
  6199. NULL)); // The even is unnamed.
  6200. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
  6201. const std::string filter_flag =
  6202. std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
  6203. info->test_case_name() + "." + info->name();
  6204. const std::string internal_flag =
  6205. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
  6206. "=" + file_ + "|" + StreamableToString(line_) + "|" +
  6207. StreamableToString(death_test_index) + "|" +
  6208. StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
  6209. // size_t has the same width as pointers on both 32-bit and 64-bit
  6210. // Windows platforms.
  6211. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
  6212. "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
  6213. "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
  6214. char executable_path[_MAX_PATH + 1]; // NOLINT
  6215. GTEST_DEATH_TEST_CHECK_(
  6216. _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
  6217. executable_path,
  6218. _MAX_PATH));
  6219. std::string command_line =
  6220. std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
  6221. internal_flag + "\"";
  6222. DeathTest::set_last_death_test_message("");
  6223. CaptureStderr();
  6224. // Flush the log buffers since the log streams are shared with the child.
  6225. FlushInfoLog();
  6226. // The child process will share the standard handles with the parent.
  6227. STARTUPINFOA startup_info;
  6228. memset(&startup_info, 0, sizeof(STARTUPINFO));
  6229. startup_info.dwFlags = STARTF_USESTDHANDLES;
  6230. startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
  6231. startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
  6232. startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
  6233. PROCESS_INFORMATION process_info;
  6234. GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
  6235. executable_path,
  6236. const_cast<char*>(command_line.c_str()),
  6237. NULL, // Retuned process handle is not inheritable.
  6238. NULL, // Retuned thread handle is not inheritable.
  6239. TRUE, // Child inherits all inheritable handles (for write_handle_).
  6240. 0x0, // Default creation flags.
  6241. NULL, // Inherit the parent's environment.
  6242. UnitTest::GetInstance()->original_working_dir(),
  6243. &startup_info,
  6244. &process_info) != FALSE);
  6245. child_handle_.Reset(process_info.hProcess);
  6246. ::CloseHandle(process_info.hThread);
  6247. set_spawned(true);
  6248. return OVERSEE_TEST;
  6249. }
  6250. # else // We are not on Windows.
  6251. // ForkingDeathTest provides implementations for most of the abstract
  6252. // methods of the DeathTest interface. Only the AssumeRole method is
  6253. // left undefined.
  6254. class ForkingDeathTest : public DeathTestImpl {
  6255. public:
  6256. ForkingDeathTest(const char* statement, const RE* regex);
  6257. // All of these virtual functions are inherited from DeathTest.
  6258. virtual int Wait();
  6259. protected:
  6260. void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
  6261. private:
  6262. // PID of child process during death test; 0 in the child process itself.
  6263. pid_t child_pid_;
  6264. };
  6265. // Constructs a ForkingDeathTest.
  6266. ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
  6267. : DeathTestImpl(a_statement, a_regex),
  6268. child_pid_(-1) {}
  6269. // Waits for the child in a death test to exit, returning its exit
  6270. // status, or 0 if no child process exists. As a side effect, sets the
  6271. // outcome data member.
  6272. int ForkingDeathTest::Wait() {
  6273. if (!spawned())
  6274. return 0;
  6275. ReadAndInterpretStatusByte();
  6276. int status_value;
  6277. GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
  6278. set_status(status_value);
  6279. return status_value;
  6280. }
  6281. // A concrete death test class that forks, then immediately runs the test
  6282. // in the child process.
  6283. class NoExecDeathTest : public ForkingDeathTest {
  6284. public:
  6285. NoExecDeathTest(const char* a_statement, const RE* a_regex) :
  6286. ForkingDeathTest(a_statement, a_regex) { }
  6287. virtual TestRole AssumeRole();
  6288. };
  6289. // The AssumeRole process for a fork-and-run death test. It implements a
  6290. // straightforward fork, with a simple pipe to transmit the status byte.
  6291. DeathTest::TestRole NoExecDeathTest::AssumeRole() {
  6292. const size_t thread_count = GetThreadCount();
  6293. if (thread_count != 1) {
  6294. GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
  6295. }
  6296. int pipe_fd[2];
  6297. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  6298. DeathTest::set_last_death_test_message("");
  6299. CaptureStderr();
  6300. // When we fork the process below, the log file buffers are copied, but the
  6301. // file descriptors are shared. We flush all log files here so that closing
  6302. // the file descriptors in the child process doesn't throw off the
  6303. // synchronization between descriptors and buffers in the parent process.
  6304. // This is as close to the fork as possible to avoid a race condition in case
  6305. // there are multiple threads running before the death test, and another
  6306. // thread writes to the log file.
  6307. FlushInfoLog();
  6308. const pid_t child_pid = fork();
  6309. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  6310. set_child_pid(child_pid);
  6311. if (child_pid == 0) {
  6312. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
  6313. set_write_fd(pipe_fd[1]);
  6314. // Redirects all logging to stderr in the child process to prevent
  6315. // concurrent writes to the log files. We capture stderr in the parent
  6316. // process and append the child process' output to a log.
  6317. LogToStderr();
  6318. // Event forwarding to the listeners of event listener API mush be shut
  6319. // down in death test subprocesses.
  6320. GetUnitTestImpl()->listeners()->SuppressEventForwarding();
  6321. g_in_fast_death_test_child = true;
  6322. return EXECUTE_TEST;
  6323. } else {
  6324. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  6325. set_read_fd(pipe_fd[0]);
  6326. set_spawned(true);
  6327. return OVERSEE_TEST;
  6328. }
  6329. }
  6330. // A concrete death test class that forks and re-executes the main
  6331. // program from the beginning, with command-line flags set that cause
  6332. // only this specific death test to be run.
  6333. class ExecDeathTest : public ForkingDeathTest {
  6334. public:
  6335. ExecDeathTest(const char* a_statement, const RE* a_regex,
  6336. const char* file, int line) :
  6337. ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
  6338. virtual TestRole AssumeRole();
  6339. private:
  6340. static ::std::vector<testing::internal::string>
  6341. GetArgvsForDeathTestChildProcess() {
  6342. ::std::vector<testing::internal::string> args = GetInjectableArgvs();
  6343. return args;
  6344. }
  6345. // The name of the file in which the death test is located.
  6346. const char* const file_;
  6347. // The line number on which the death test is located.
  6348. const int line_;
  6349. };
  6350. // Utility class for accumulating command-line arguments.
  6351. class Arguments {
  6352. public:
  6353. Arguments() {
  6354. args_.push_back(NULL);
  6355. }
  6356. ~Arguments() {
  6357. for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
  6358. ++i) {
  6359. free(*i);
  6360. }
  6361. }
  6362. void AddArgument(const char* argument) {
  6363. args_.insert(args_.end() - 1, posix::StrDup(argument));
  6364. }
  6365. template <typename Str>
  6366. void AddArguments(const ::std::vector<Str>& arguments) {
  6367. for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
  6368. i != arguments.end();
  6369. ++i) {
  6370. args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
  6371. }
  6372. }
  6373. char* const* Argv() {
  6374. return &args_[0];
  6375. }
  6376. private:
  6377. std::vector<char*> args_;
  6378. };
  6379. // A struct that encompasses the arguments to the child process of a
  6380. // threadsafe-style death test process.
  6381. struct ExecDeathTestArgs {
  6382. char* const* argv; // Command-line arguments for the child's call to exec
  6383. int close_fd; // File descriptor to close; the read end of a pipe
  6384. };
  6385. # if GTEST_OS_MAC
  6386. inline char** GetEnviron() {
  6387. // When Google Test is built as a framework on MacOS X, the environ variable
  6388. // is unavailable. Apple's documentation (man environ) recommends using
  6389. // _NSGetEnviron() instead.
  6390. return *_NSGetEnviron();
  6391. }
  6392. # else
  6393. // Some POSIX platforms expect you to declare environ. extern "C" makes
  6394. // it reside in the global namespace.
  6395. extern "C" char** environ;
  6396. inline char** GetEnviron() { return environ; }
  6397. # endif // GTEST_OS_MAC
  6398. # if !GTEST_OS_QNX
  6399. // The main function for a threadsafe-style death test child process.
  6400. // This function is called in a clone()-ed process and thus must avoid
  6401. // any potentially unsafe operations like malloc or libc functions.
  6402. static int ExecDeathTestChildMain(void* child_arg) {
  6403. ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
  6404. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
  6405. // We need to execute the test program in the same environment where
  6406. // it was originally invoked. Therefore we change to the original
  6407. // working directory first.
  6408. const char* const original_dir =
  6409. UnitTest::GetInstance()->original_working_dir();
  6410. // We can safely call chdir() as it's a direct system call.
  6411. if (chdir(original_dir) != 0) {
  6412. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  6413. GetLastErrnoDescription());
  6414. return EXIT_FAILURE;
  6415. }
  6416. // We can safely call execve() as it's a direct system call. We
  6417. // cannot use execvp() as it's a libc function and thus potentially
  6418. // unsafe. Since execve() doesn't search the PATH, the user must
  6419. // invoke the test program via a valid path that contains at least
  6420. // one path separator.
  6421. execve(args->argv[0], args->argv, GetEnviron());
  6422. DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
  6423. original_dir + " failed: " +
  6424. GetLastErrnoDescription());
  6425. return EXIT_FAILURE;
  6426. }
  6427. # endif // !GTEST_OS_QNX
  6428. // Two utility routines that together determine the direction the stack
  6429. // grows.
  6430. // This could be accomplished more elegantly by a single recursive
  6431. // function, but we want to guard against the unlikely possibility of
  6432. // a smart compiler optimizing the recursion away.
  6433. //
  6434. // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
  6435. // StackLowerThanAddress into StackGrowsDown, which then doesn't give
  6436. // correct answer.
  6437. void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
  6438. void StackLowerThanAddress(const void* ptr, bool* result) {
  6439. int dummy;
  6440. *result = (&dummy < ptr);
  6441. }
  6442. bool StackGrowsDown() {
  6443. int dummy;
  6444. bool result;
  6445. StackLowerThanAddress(&dummy, &result);
  6446. return result;
  6447. }
  6448. // Spawns a child process with the same executable as the current process in
  6449. // a thread-safe manner and instructs it to run the death test. The
  6450. // implementation uses fork(2) + exec. On systems where clone(2) is
  6451. // available, it is used instead, being slightly more thread-safe. On QNX,
  6452. // fork supports only single-threaded environments, so this function uses
  6453. // spawn(2) there instead. The function dies with an error message if
  6454. // anything goes wrong.
  6455. static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
  6456. ExecDeathTestArgs args = { argv, close_fd };
  6457. pid_t child_pid = -1;
  6458. # if GTEST_OS_QNX
  6459. // Obtains the current directory and sets it to be closed in the child
  6460. // process.
  6461. const int cwd_fd = open(".", O_RDONLY);
  6462. GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
  6463. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
  6464. // We need to execute the test program in the same environment where
  6465. // it was originally invoked. Therefore we change to the original
  6466. // working directory first.
  6467. const char* const original_dir =
  6468. UnitTest::GetInstance()->original_working_dir();
  6469. // We can safely call chdir() as it's a direct system call.
  6470. if (chdir(original_dir) != 0) {
  6471. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  6472. GetLastErrnoDescription());
  6473. return EXIT_FAILURE;
  6474. }
  6475. int fd_flags;
  6476. // Set close_fd to be closed after spawn.
  6477. GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
  6478. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
  6479. fd_flags | FD_CLOEXEC));
  6480. struct inheritance inherit = {0};
  6481. // spawn is a system call.
  6482. child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
  6483. // Restores the current working directory.
  6484. GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
  6485. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
  6486. # else // GTEST_OS_QNX
  6487. # if GTEST_OS_LINUX
  6488. // When a SIGPROF signal is received while fork() or clone() are executing,
  6489. // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
  6490. // it after the call to fork()/clone() is complete.
  6491. struct sigaction saved_sigprof_action;
  6492. struct sigaction ignore_sigprof_action;
  6493. memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
  6494. sigemptyset(&ignore_sigprof_action.sa_mask);
  6495. ignore_sigprof_action.sa_handler = SIG_IGN;
  6496. GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
  6497. SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
  6498. # endif // GTEST_OS_LINUX
  6499. # if GTEST_HAS_CLONE
  6500. const bool use_fork = GTEST_FLAG(death_test_use_fork);
  6501. if (!use_fork) {
  6502. static const bool stack_grows_down = StackGrowsDown();
  6503. const size_t stack_size = getpagesize();
  6504. // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
  6505. void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
  6506. MAP_ANON | MAP_PRIVATE, -1, 0);
  6507. GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
  6508. // Maximum stack alignment in bytes: For a downward-growing stack, this
  6509. // amount is subtracted from size of the stack space to get an address
  6510. // that is within the stack space and is aligned on all systems we care
  6511. // about. As far as I know there is no ABI with stack alignment greater
  6512. // than 64. We assume stack and stack_size already have alignment of
  6513. // kMaxStackAlignment.
  6514. const size_t kMaxStackAlignment = 64;
  6515. void* const stack_top =
  6516. static_cast<char*>(stack) +
  6517. (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
  6518. GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
  6519. reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
  6520. child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
  6521. GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
  6522. }
  6523. # else
  6524. const bool use_fork = true;
  6525. # endif // GTEST_HAS_CLONE
  6526. if (use_fork && (child_pid = fork()) == 0) {
  6527. ExecDeathTestChildMain(&args);
  6528. _exit(0);
  6529. }
  6530. # endif // GTEST_OS_QNX
  6531. # if GTEST_OS_LINUX
  6532. GTEST_DEATH_TEST_CHECK_SYSCALL_(
  6533. sigaction(SIGPROF, &saved_sigprof_action, NULL));
  6534. # endif // GTEST_OS_LINUX
  6535. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  6536. return child_pid;
  6537. }
  6538. // The AssumeRole process for a fork-and-exec death test. It re-executes the
  6539. // main program from the beginning, setting the --gtest_filter
  6540. // and --gtest_internal_run_death_test flags to cause only the current
  6541. // death test to be re-run.
  6542. DeathTest::TestRole ExecDeathTest::AssumeRole() {
  6543. const UnitTestImpl* const impl = GetUnitTestImpl();
  6544. const InternalRunDeathTestFlag* const flag =
  6545. impl->internal_run_death_test_flag();
  6546. const TestInfo* const info = impl->current_test_info();
  6547. const int death_test_index = info->result()->death_test_count();
  6548. if (flag != NULL) {
  6549. set_write_fd(flag->write_fd());
  6550. return EXECUTE_TEST;
  6551. }
  6552. int pipe_fd[2];
  6553. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  6554. // Clear the close-on-exec flag on the write end of the pipe, lest
  6555. // it be closed when the child process does an exec:
  6556. GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
  6557. const std::string filter_flag =
  6558. std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
  6559. + info->test_case_name() + "." + info->name();
  6560. const std::string internal_flag =
  6561. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
  6562. + file_ + "|" + StreamableToString(line_) + "|"
  6563. + StreamableToString(death_test_index) + "|"
  6564. + StreamableToString(pipe_fd[1]);
  6565. Arguments args;
  6566. args.AddArguments(GetArgvsForDeathTestChildProcess());
  6567. args.AddArgument(filter_flag.c_str());
  6568. args.AddArgument(internal_flag.c_str());
  6569. DeathTest::set_last_death_test_message("");
  6570. CaptureStderr();
  6571. // See the comment in NoExecDeathTest::AssumeRole for why the next line
  6572. // is necessary.
  6573. FlushInfoLog();
  6574. const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
  6575. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  6576. set_child_pid(child_pid);
  6577. set_read_fd(pipe_fd[0]);
  6578. set_spawned(true);
  6579. return OVERSEE_TEST;
  6580. }
  6581. # endif // !GTEST_OS_WINDOWS
  6582. // Creates a concrete DeathTest-derived class that depends on the
  6583. // --gtest_death_test_style flag, and sets the pointer pointed to
  6584. // by the "test" argument to its address. If the test should be
  6585. // skipped, sets that pointer to NULL. Returns true, unless the
  6586. // flag is set to an invalid value.
  6587. bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
  6588. const char* file, int line,
  6589. DeathTest** test) {
  6590. UnitTestImpl* const impl = GetUnitTestImpl();
  6591. const InternalRunDeathTestFlag* const flag =
  6592. impl->internal_run_death_test_flag();
  6593. const int death_test_index = impl->current_test_info()
  6594. ->increment_death_test_count();
  6595. if (flag != NULL) {
  6596. if (death_test_index > flag->index()) {
  6597. DeathTest::set_last_death_test_message(
  6598. "Death test count (" + StreamableToString(death_test_index)
  6599. + ") somehow exceeded expected maximum ("
  6600. + StreamableToString(flag->index()) + ")");
  6601. return false;
  6602. }
  6603. if (!(flag->file() == file && flag->line() == line &&
  6604. flag->index() == death_test_index)) {
  6605. *test = NULL;
  6606. return true;
  6607. }
  6608. }
  6609. # if GTEST_OS_WINDOWS
  6610. if (GTEST_FLAG(death_test_style) == "threadsafe" ||
  6611. GTEST_FLAG(death_test_style) == "fast") {
  6612. *test = new WindowsDeathTest(statement, regex, file, line);
  6613. }
  6614. # else
  6615. if (GTEST_FLAG(death_test_style) == "threadsafe") {
  6616. *test = new ExecDeathTest(statement, regex, file, line);
  6617. } else if (GTEST_FLAG(death_test_style) == "fast") {
  6618. *test = new NoExecDeathTest(statement, regex);
  6619. }
  6620. # endif // GTEST_OS_WINDOWS
  6621. else { // NOLINT - this is more readable than unbalanced brackets inside #if.
  6622. DeathTest::set_last_death_test_message(
  6623. "Unknown death test style \"" + GTEST_FLAG(death_test_style)
  6624. + "\" encountered");
  6625. return false;
  6626. }
  6627. return true;
  6628. }
  6629. // Splits a given string on a given delimiter, populating a given
  6630. // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
  6631. // ::std::string, so we can use it here.
  6632. static void SplitString(const ::std::string& str, char delimiter,
  6633. ::std::vector< ::std::string>* dest) {
  6634. ::std::vector< ::std::string> parsed;
  6635. ::std::string::size_type pos = 0;
  6636. while (::testing::internal::AlwaysTrue()) {
  6637. const ::std::string::size_type colon = str.find(delimiter, pos);
  6638. if (colon == ::std::string::npos) {
  6639. parsed.push_back(str.substr(pos));
  6640. break;
  6641. } else {
  6642. parsed.push_back(str.substr(pos, colon - pos));
  6643. pos = colon + 1;
  6644. }
  6645. }
  6646. dest->swap(parsed);
  6647. }
  6648. # if GTEST_OS_WINDOWS
  6649. // Recreates the pipe and event handles from the provided parameters,
  6650. // signals the event, and returns a file descriptor wrapped around the pipe
  6651. // handle. This function is called in the child process only.
  6652. int GetStatusFileDescriptor(unsigned int parent_process_id,
  6653. size_t write_handle_as_size_t,
  6654. size_t event_handle_as_size_t) {
  6655. AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
  6656. FALSE, // Non-inheritable.
  6657. parent_process_id));
  6658. if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
  6659. DeathTestAbort("Unable to open parent process " +
  6660. StreamableToString(parent_process_id));
  6661. }
  6662. // TODO(vladl@google.com): Replace the following check with a
  6663. // compile-time assertion when available.
  6664. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
  6665. const HANDLE write_handle =
  6666. reinterpret_cast<HANDLE>(write_handle_as_size_t);
  6667. HANDLE dup_write_handle;
  6668. // The newly initialized handle is accessible only in in the parent
  6669. // process. To obtain one accessible within the child, we need to use
  6670. // DuplicateHandle.
  6671. if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
  6672. ::GetCurrentProcess(), &dup_write_handle,
  6673. 0x0, // Requested privileges ignored since
  6674. // DUPLICATE_SAME_ACCESS is used.
  6675. FALSE, // Request non-inheritable handler.
  6676. DUPLICATE_SAME_ACCESS)) {
  6677. DeathTestAbort("Unable to duplicate the pipe handle " +
  6678. StreamableToString(write_handle_as_size_t) +
  6679. " from the parent process " +
  6680. StreamableToString(parent_process_id));
  6681. }
  6682. const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
  6683. HANDLE dup_event_handle;
  6684. if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
  6685. ::GetCurrentProcess(), &dup_event_handle,
  6686. 0x0,
  6687. FALSE,
  6688. DUPLICATE_SAME_ACCESS)) {
  6689. DeathTestAbort("Unable to duplicate the event handle " +
  6690. StreamableToString(event_handle_as_size_t) +
  6691. " from the parent process " +
  6692. StreamableToString(parent_process_id));
  6693. }
  6694. const int write_fd =
  6695. ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
  6696. if (write_fd == -1) {
  6697. DeathTestAbort("Unable to convert pipe handle " +
  6698. StreamableToString(write_handle_as_size_t) +
  6699. " to a file descriptor");
  6700. }
  6701. // Signals the parent that the write end of the pipe has been acquired
  6702. // so the parent can release its own write end.
  6703. ::SetEvent(dup_event_handle);
  6704. return write_fd;
  6705. }
  6706. # endif // GTEST_OS_WINDOWS
  6707. // Returns a newly created InternalRunDeathTestFlag object with fields
  6708. // initialized from the GTEST_FLAG(internal_run_death_test) flag if
  6709. // the flag is specified; otherwise returns NULL.
  6710. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
  6711. if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
  6712. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
  6713. // can use it here.
  6714. int line = -1;
  6715. int index = -1;
  6716. ::std::vector< ::std::string> fields;
  6717. SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
  6718. int write_fd = -1;
  6719. # if GTEST_OS_WINDOWS
  6720. unsigned int parent_process_id = 0;
  6721. size_t write_handle_as_size_t = 0;
  6722. size_t event_handle_as_size_t = 0;
  6723. if (fields.size() != 6
  6724. || !ParseNaturalNumber(fields[1], &line)
  6725. || !ParseNaturalNumber(fields[2], &index)
  6726. || !ParseNaturalNumber(fields[3], &parent_process_id)
  6727. || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
  6728. || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
  6729. DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
  6730. GTEST_FLAG(internal_run_death_test));
  6731. }
  6732. write_fd = GetStatusFileDescriptor(parent_process_id,
  6733. write_handle_as_size_t,
  6734. event_handle_as_size_t);
  6735. # else
  6736. if (fields.size() != 4
  6737. || !ParseNaturalNumber(fields[1], &line)
  6738. || !ParseNaturalNumber(fields[2], &index)
  6739. || !ParseNaturalNumber(fields[3], &write_fd)) {
  6740. DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
  6741. + GTEST_FLAG(internal_run_death_test));
  6742. }
  6743. # endif // GTEST_OS_WINDOWS
  6744. return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
  6745. }
  6746. } // namespace internal
  6747. #endif // GTEST_HAS_DEATH_TEST
  6748. } // namespace testing
  6749. // Copyright 2008, Google Inc.
  6750. // All rights reserved.
  6751. //
  6752. // Redistribution and use in source and binary forms, with or without
  6753. // modification, are permitted provided that the following conditions are
  6754. // met:
  6755. //
  6756. // * Redistributions of source code must retain the above copyright
  6757. // notice, this list of conditions and the following disclaimer.
  6758. // * Redistributions in binary form must reproduce the above
  6759. // copyright notice, this list of conditions and the following disclaimer
  6760. // in the documentation and/or other materials provided with the
  6761. // distribution.
  6762. // * Neither the name of Google Inc. nor the names of its
  6763. // contributors may be used to endorse or promote products derived from
  6764. // this software without specific prior written permission.
  6765. //
  6766. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6767. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6768. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6769. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6770. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6771. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6772. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6773. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6774. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6775. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6776. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6777. //
  6778. // Authors: keith.ray@gmail.com (Keith Ray)
  6779. #include <stdlib.h>
  6780. #if GTEST_OS_WINDOWS_MOBILE
  6781. # include <windows.h>
  6782. #elif GTEST_OS_WINDOWS
  6783. # include <direct.h>
  6784. # include <io.h>
  6785. #elif GTEST_OS_SYMBIAN
  6786. // Symbian OpenC has PATH_MAX in sys/syslimits.h
  6787. # include <sys/syslimits.h>
  6788. #else
  6789. # include <limits.h>
  6790. # include <climits> // Some Linux distributions define PATH_MAX here.
  6791. #endif // GTEST_OS_WINDOWS_MOBILE
  6792. #if GTEST_OS_WINDOWS
  6793. # define GTEST_PATH_MAX_ _MAX_PATH
  6794. #elif defined(PATH_MAX)
  6795. # define GTEST_PATH_MAX_ PATH_MAX
  6796. #elif defined(_XOPEN_PATH_MAX)
  6797. # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
  6798. #else
  6799. # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
  6800. #endif // GTEST_OS_WINDOWS
  6801. namespace testing {
  6802. namespace internal {
  6803. #if GTEST_OS_WINDOWS
  6804. // On Windows, '\\' is the standard path separator, but many tools and the
  6805. // Windows API also accept '/' as an alternate path separator. Unless otherwise
  6806. // noted, a file path can contain either kind of path separators, or a mixture
  6807. // of them.
  6808. const char kPathSeparator = '\\';
  6809. const char kAlternatePathSeparator = '/';
  6810. const char kPathSeparatorString[] = "\\";
  6811. const char kAlternatePathSeparatorString[] = "/";
  6812. # if GTEST_OS_WINDOWS_MOBILE
  6813. // Windows CE doesn't have a current directory. You should not use
  6814. // the current directory in tests on Windows CE, but this at least
  6815. // provides a reasonable fallback.
  6816. const char kCurrentDirectoryString[] = "\\";
  6817. // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
  6818. const DWORD kInvalidFileAttributes = 0xffffffff;
  6819. # else
  6820. const char kCurrentDirectoryString[] = ".\\";
  6821. # endif // GTEST_OS_WINDOWS_MOBILE
  6822. #else
  6823. const char kPathSeparator = '/';
  6824. const char kPathSeparatorString[] = "/";
  6825. const char kCurrentDirectoryString[] = "./";
  6826. #endif // GTEST_OS_WINDOWS
  6827. // Returns whether the given character is a valid path separator.
  6828. static bool IsPathSeparator(char c) {
  6829. #if GTEST_HAS_ALT_PATH_SEP_
  6830. return (c == kPathSeparator) || (c == kAlternatePathSeparator);
  6831. #else
  6832. return c == kPathSeparator;
  6833. #endif
  6834. }
  6835. // Returns the current working directory, or "" if unsuccessful.
  6836. FilePath FilePath::GetCurrentDir() {
  6837. #if GTEST_OS_WINDOWS_MOBILE
  6838. // Windows CE doesn't have a current directory, so we just return
  6839. // something reasonable.
  6840. return FilePath(kCurrentDirectoryString);
  6841. #elif GTEST_OS_WINDOWS
  6842. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  6843. return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
  6844. #else
  6845. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  6846. return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
  6847. #endif // GTEST_OS_WINDOWS_MOBILE
  6848. }
  6849. // Returns a copy of the FilePath with the case-insensitive extension removed.
  6850. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
  6851. // FilePath("dir/file"). If a case-insensitive extension is not
  6852. // found, returns a copy of the original FilePath.
  6853. FilePath FilePath::RemoveExtension(const char* extension) const {
  6854. const std::string dot_extension = std::string(".") + extension;
  6855. if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
  6856. return FilePath(pathname_.substr(
  6857. 0, pathname_.length() - dot_extension.length()));
  6858. }
  6859. return *this;
  6860. }
  6861. // Returns a pointer to the last occurence of a valid path separator in
  6862. // the FilePath. On Windows, for example, both '/' and '\' are valid path
  6863. // separators. Returns NULL if no path separator was found.
  6864. const char* FilePath::FindLastPathSeparator() const {
  6865. const char* const last_sep = strrchr(c_str(), kPathSeparator);
  6866. #if GTEST_HAS_ALT_PATH_SEP_
  6867. const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
  6868. // Comparing two pointers of which only one is NULL is undefined.
  6869. if (last_alt_sep != NULL &&
  6870. (last_sep == NULL || last_alt_sep > last_sep)) {
  6871. return last_alt_sep;
  6872. }
  6873. #endif
  6874. return last_sep;
  6875. }
  6876. // Returns a copy of the FilePath with the directory part removed.
  6877. // Example: FilePath("path/to/file").RemoveDirectoryName() returns
  6878. // FilePath("file"). If there is no directory part ("just_a_file"), it returns
  6879. // the FilePath unmodified. If there is no file part ("just_a_dir/") it
  6880. // returns an empty FilePath ("").
  6881. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  6882. FilePath FilePath::RemoveDirectoryName() const {
  6883. const char* const last_sep = FindLastPathSeparator();
  6884. return last_sep ? FilePath(last_sep + 1) : *this;
  6885. }
  6886. // RemoveFileName returns the directory path with the filename removed.
  6887. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
  6888. // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
  6889. // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
  6890. // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
  6891. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  6892. FilePath FilePath::RemoveFileName() const {
  6893. const char* const last_sep = FindLastPathSeparator();
  6894. std::string dir;
  6895. if (last_sep) {
  6896. dir = std::string(c_str(), last_sep + 1 - c_str());
  6897. } else {
  6898. dir = kCurrentDirectoryString;
  6899. }
  6900. return FilePath(dir);
  6901. }
  6902. // Helper functions for naming files in a directory for xml output.
  6903. // Given directory = "dir", base_name = "test", number = 0,
  6904. // extension = "xml", returns "dir/test.xml". If number is greater
  6905. // than zero (e.g., 12), returns "dir/test_12.xml".
  6906. // On Windows platform, uses \ as the separator rather than /.
  6907. FilePath FilePath::MakeFileName(const FilePath& directory,
  6908. const FilePath& base_name,
  6909. int number,
  6910. const char* extension) {
  6911. std::string file;
  6912. if (number == 0) {
  6913. file = base_name.string() + "." + extension;
  6914. } else {
  6915. file = base_name.string() + "_" + StreamableToString(number)
  6916. + "." + extension;
  6917. }
  6918. return ConcatPaths(directory, FilePath(file));
  6919. }
  6920. // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
  6921. // On Windows, uses \ as the separator rather than /.
  6922. FilePath FilePath::ConcatPaths(const FilePath& directory,
  6923. const FilePath& relative_path) {
  6924. if (directory.IsEmpty())
  6925. return relative_path;
  6926. const FilePath dir(directory.RemoveTrailingPathSeparator());
  6927. return FilePath(dir.string() + kPathSeparator + relative_path.string());
  6928. }
  6929. // Returns true if pathname describes something findable in the file-system,
  6930. // either a file, directory, or whatever.
  6931. bool FilePath::FileOrDirectoryExists() const {
  6932. #if GTEST_OS_WINDOWS_MOBILE
  6933. LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
  6934. const DWORD attributes = GetFileAttributes(unicode);
  6935. delete [] unicode;
  6936. return attributes != kInvalidFileAttributes;
  6937. #else
  6938. posix::StatStruct file_stat;
  6939. return posix::Stat(pathname_.c_str(), &file_stat) == 0;
  6940. #endif // GTEST_OS_WINDOWS_MOBILE
  6941. }
  6942. // Returns true if pathname describes a directory in the file-system
  6943. // that exists.
  6944. bool FilePath::DirectoryExists() const {
  6945. bool result = false;
  6946. #if GTEST_OS_WINDOWS
  6947. // Don't strip off trailing separator if path is a root directory on
  6948. // Windows (like "C:\\").
  6949. const FilePath& path(IsRootDirectory() ? *this :
  6950. RemoveTrailingPathSeparator());
  6951. #else
  6952. const FilePath& path(*this);
  6953. #endif
  6954. #if GTEST_OS_WINDOWS_MOBILE
  6955. LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
  6956. const DWORD attributes = GetFileAttributes(unicode);
  6957. delete [] unicode;
  6958. if ((attributes != kInvalidFileAttributes) &&
  6959. (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  6960. result = true;
  6961. }
  6962. #else
  6963. posix::StatStruct file_stat;
  6964. result = posix::Stat(path.c_str(), &file_stat) == 0 &&
  6965. posix::IsDir(file_stat);
  6966. #endif // GTEST_OS_WINDOWS_MOBILE
  6967. return result;
  6968. }
  6969. // Returns true if pathname describes a root directory. (Windows has one
  6970. // root directory per disk drive.)
  6971. bool FilePath::IsRootDirectory() const {
  6972. #if GTEST_OS_WINDOWS
  6973. // TODO(wan@google.com): on Windows a network share like
  6974. // \\server\share can be a root directory, although it cannot be the
  6975. // current directory. Handle this properly.
  6976. return pathname_.length() == 3 && IsAbsolutePath();
  6977. #else
  6978. return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
  6979. #endif
  6980. }
  6981. // Returns true if pathname describes an absolute path.
  6982. bool FilePath::IsAbsolutePath() const {
  6983. const char* const name = pathname_.c_str();
  6984. #if GTEST_OS_WINDOWS
  6985. return pathname_.length() >= 3 &&
  6986. ((name[0] >= 'a' && name[0] <= 'z') ||
  6987. (name[0] >= 'A' && name[0] <= 'Z')) &&
  6988. name[1] == ':' &&
  6989. IsPathSeparator(name[2]);
  6990. #else
  6991. return IsPathSeparator(name[0]);
  6992. #endif
  6993. }
  6994. // Returns a pathname for a file that does not currently exist. The pathname
  6995. // will be directory/base_name.extension or
  6996. // directory/base_name_<number>.extension if directory/base_name.extension
  6997. // already exists. The number will be incremented until a pathname is found
  6998. // that does not already exist.
  6999. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
  7000. // There could be a race condition if two or more processes are calling this
  7001. // function at the same time -- they could both pick the same filename.
  7002. FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
  7003. const FilePath& base_name,
  7004. const char* extension) {
  7005. FilePath full_pathname;
  7006. int number = 0;
  7007. do {
  7008. full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
  7009. } while (full_pathname.FileOrDirectoryExists());
  7010. return full_pathname;
  7011. }
  7012. // Returns true if FilePath ends with a path separator, which indicates that
  7013. // it is intended to represent a directory. Returns false otherwise.
  7014. // This does NOT check that a directory (or file) actually exists.
  7015. bool FilePath::IsDirectory() const {
  7016. return !pathname_.empty() &&
  7017. IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
  7018. }
  7019. // Create directories so that path exists. Returns true if successful or if
  7020. // the directories already exist; returns false if unable to create directories
  7021. // for any reason.
  7022. bool FilePath::CreateDirectoriesRecursively() const {
  7023. if (!this->IsDirectory()) {
  7024. return false;
  7025. }
  7026. if (pathname_.length() == 0 || this->DirectoryExists()) {
  7027. return true;
  7028. }
  7029. const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
  7030. return parent.CreateDirectoriesRecursively() && this->CreateFolder();
  7031. }
  7032. // Create the directory so that path exists. Returns true if successful or
  7033. // if the directory already exists; returns false if unable to create the
  7034. // directory for any reason, including if the parent directory does not
  7035. // exist. Not named "CreateDirectory" because that's a macro on Windows.
  7036. bool FilePath::CreateFolder() const {
  7037. #if GTEST_OS_WINDOWS_MOBILE
  7038. FilePath removed_sep(this->RemoveTrailingPathSeparator());
  7039. LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
  7040. int result = CreateDirectory(unicode, NULL) ? 0 : -1;
  7041. delete [] unicode;
  7042. #elif GTEST_OS_WINDOWS
  7043. int result = _mkdir(pathname_.c_str());
  7044. #else
  7045. int result = mkdir(pathname_.c_str(), 0777);
  7046. #endif // GTEST_OS_WINDOWS_MOBILE
  7047. if (result == -1) {
  7048. return this->DirectoryExists(); // An error is OK if the directory exists.
  7049. }
  7050. return true; // No error.
  7051. }
  7052. // If input name has a trailing separator character, remove it and return the
  7053. // name, otherwise return the name string unmodified.
  7054. // On Windows platform, uses \ as the separator, other platforms use /.
  7055. FilePath FilePath::RemoveTrailingPathSeparator() const {
  7056. return IsDirectory()
  7057. ? FilePath(pathname_.substr(0, pathname_.length() - 1))
  7058. : *this;
  7059. }
  7060. // Removes any redundant separators that might be in the pathname.
  7061. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
  7062. // redundancies that might be in a pathname involving "." or "..".
  7063. // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
  7064. void FilePath::Normalize() {
  7065. if (pathname_.c_str() == NULL) {
  7066. pathname_ = "";
  7067. return;
  7068. }
  7069. const char* src = pathname_.c_str();
  7070. char* const dest = new char[pathname_.length() + 1];
  7071. char* dest_ptr = dest;
  7072. memset(dest_ptr, 0, pathname_.length() + 1);
  7073. while (*src != '\0') {
  7074. *dest_ptr = *src;
  7075. if (!IsPathSeparator(*src)) {
  7076. src++;
  7077. } else {
  7078. #if GTEST_HAS_ALT_PATH_SEP_
  7079. if (*dest_ptr == kAlternatePathSeparator) {
  7080. *dest_ptr = kPathSeparator;
  7081. }
  7082. #endif
  7083. while (IsPathSeparator(*src))
  7084. src++;
  7085. }
  7086. dest_ptr++;
  7087. }
  7088. *dest_ptr = '\0';
  7089. pathname_ = dest;
  7090. delete[] dest;
  7091. }
  7092. } // namespace internal
  7093. } // namespace testing
  7094. // Copyright 2008, Google Inc.
  7095. // All rights reserved.
  7096. //
  7097. // Redistribution and use in source and binary forms, with or without
  7098. // modification, are permitted provided that the following conditions are
  7099. // met:
  7100. //
  7101. // * Redistributions of source code must retain the above copyright
  7102. // notice, this list of conditions and the following disclaimer.
  7103. // * Redistributions in binary form must reproduce the above
  7104. // copyright notice, this list of conditions and the following disclaimer
  7105. // in the documentation and/or other materials provided with the
  7106. // distribution.
  7107. // * Neither the name of Google Inc. nor the names of its
  7108. // contributors may be used to endorse or promote products derived from
  7109. // this software without specific prior written permission.
  7110. //
  7111. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7112. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7113. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7114. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7115. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7116. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7117. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7118. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7119. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7120. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7121. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7122. //
  7123. // Author: wan@google.com (Zhanyong Wan)
  7124. #include <limits.h>
  7125. #include <stdlib.h>
  7126. #include <stdio.h>
  7127. #include <string.h>
  7128. #if GTEST_OS_WINDOWS_MOBILE
  7129. # include <windows.h> // For TerminateProcess()
  7130. #elif GTEST_OS_WINDOWS
  7131. # include <io.h>
  7132. # include <sys/stat.h>
  7133. #else
  7134. # include <unistd.h>
  7135. #endif // GTEST_OS_WINDOWS_MOBILE
  7136. #if GTEST_OS_MAC
  7137. # include <mach/mach_init.h>
  7138. # include <mach/task.h>
  7139. # include <mach/vm_map.h>
  7140. #endif // GTEST_OS_MAC
  7141. #if GTEST_OS_QNX
  7142. # include <devctl.h>
  7143. # include <sys/procfs.h>
  7144. #endif // GTEST_OS_QNX
  7145. // Indicates that this translation unit is part of Google Test's
  7146. // implementation. It must come before gtest-internal-inl.h is
  7147. // included, or there will be a compiler error. This trick is to
  7148. // prevent a user from accidentally including gtest-internal-inl.h in
  7149. // his code.
  7150. #define GTEST_IMPLEMENTATION_ 1
  7151. #undef GTEST_IMPLEMENTATION_
  7152. namespace testing {
  7153. namespace internal {
  7154. #if defined(_MSC_VER) || defined(__BORLANDC__)
  7155. // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
  7156. const int kStdOutFileno = 1;
  7157. const int kStdErrFileno = 2;
  7158. #else
  7159. const int kStdOutFileno = STDOUT_FILENO;
  7160. const int kStdErrFileno = STDERR_FILENO;
  7161. #endif // _MSC_VER
  7162. #if GTEST_OS_MAC
  7163. // Returns the number of threads running in the process, or 0 to indicate that
  7164. // we cannot detect it.
  7165. size_t GetThreadCount() {
  7166. const task_t task = mach_task_self();
  7167. mach_msg_type_number_t thread_count;
  7168. thread_act_array_t thread_list;
  7169. const kern_return_t status = task_threads(task, &thread_list, &thread_count);
  7170. if (status == KERN_SUCCESS) {
  7171. // task_threads allocates resources in thread_list and we need to free them
  7172. // to avoid leaks.
  7173. vm_deallocate(task,
  7174. reinterpret_cast<vm_address_t>(thread_list),
  7175. sizeof(thread_t) * thread_count);
  7176. return static_cast<size_t>(thread_count);
  7177. } else {
  7178. return 0;
  7179. }
  7180. }
  7181. #elif GTEST_OS_QNX
  7182. // Returns the number of threads running in the process, or 0 to indicate that
  7183. // we cannot detect it.
  7184. size_t GetThreadCount() {
  7185. const int fd = open("/proc/self/as", O_RDONLY);
  7186. if (fd < 0) {
  7187. return 0;
  7188. }
  7189. procfs_info process_info;
  7190. const int status =
  7191. devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
  7192. close(fd);
  7193. if (status == EOK) {
  7194. return static_cast<size_t>(process_info.num_threads);
  7195. } else {
  7196. return 0;
  7197. }
  7198. }
  7199. #else
  7200. size_t GetThreadCount() {
  7201. // There's no portable way to detect the number of threads, so we just
  7202. // return 0 to indicate that we cannot detect it.
  7203. return 0;
  7204. }
  7205. #endif // GTEST_OS_MAC
  7206. #if GTEST_USES_POSIX_RE
  7207. // Implements RE. Currently only needed for death tests.
  7208. RE::~RE() {
  7209. if (is_valid_) {
  7210. // regfree'ing an invalid regex might crash because the content
  7211. // of the regex is undefined. Since the regex's are essentially
  7212. // the same, one cannot be valid (or invalid) without the other
  7213. // being so too.
  7214. regfree(&partial_regex_);
  7215. regfree(&full_regex_);
  7216. }
  7217. free(const_cast<char*>(pattern_));
  7218. }
  7219. // Returns true iff regular expression re matches the entire str.
  7220. bool RE::FullMatch(const char* str, const RE& re) {
  7221. if (!re.is_valid_) return false;
  7222. regmatch_t match;
  7223. return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
  7224. }
  7225. // Returns true iff regular expression re matches a substring of str
  7226. // (including str itself).
  7227. bool RE::PartialMatch(const char* str, const RE& re) {
  7228. if (!re.is_valid_) return false;
  7229. regmatch_t match;
  7230. return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
  7231. }
  7232. // Initializes an RE from its string representation.
  7233. void RE::Init(const char* regex) {
  7234. pattern_ = posix::StrDup(regex);
  7235. // Reserves enough bytes to hold the regular expression used for a
  7236. // full match.
  7237. const size_t full_regex_len = strlen(regex) + 10;
  7238. char* const full_pattern = new char[full_regex_len];
  7239. snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
  7240. is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
  7241. // We want to call regcomp(&partial_regex_, ...) even if the
  7242. // previous expression returns false. Otherwise partial_regex_ may
  7243. // not be properly initialized can may cause trouble when it's
  7244. // freed.
  7245. //
  7246. // Some implementation of POSIX regex (e.g. on at least some
  7247. // versions of Cygwin) doesn't accept the empty string as a valid
  7248. // regex. We change it to an equivalent form "()" to be safe.
  7249. if (is_valid_) {
  7250. const char* const partial_regex = (*regex == '\0') ? "()" : regex;
  7251. is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
  7252. }
  7253. EXPECT_TRUE(is_valid_)
  7254. << "Regular expression \"" << regex
  7255. << "\" is not a valid POSIX Extended regular expression.";
  7256. delete[] full_pattern;
  7257. }
  7258. #elif GTEST_USES_SIMPLE_RE
  7259. // Returns true iff ch appears anywhere in str (excluding the
  7260. // terminating '\0' character).
  7261. bool IsInSet(char ch, const char* str) {
  7262. return ch != '\0' && strchr(str, ch) != NULL;
  7263. }
  7264. // Returns true iff ch belongs to the given classification. Unlike
  7265. // similar functions in <ctype.h>, these aren't affected by the
  7266. // current locale.
  7267. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
  7268. bool IsAsciiPunct(char ch) {
  7269. return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
  7270. }
  7271. bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
  7272. bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
  7273. bool IsAsciiWordChar(char ch) {
  7274. return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
  7275. ('0' <= ch && ch <= '9') || ch == '_';
  7276. }
  7277. // Returns true iff "\\c" is a supported escape sequence.
  7278. bool IsValidEscape(char c) {
  7279. return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
  7280. }
  7281. // Returns true iff the given atom (specified by escaped and pattern)
  7282. // matches ch. The result is undefined if the atom is invalid.
  7283. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
  7284. if (escaped) { // "\\p" where p is pattern_char.
  7285. switch (pattern_char) {
  7286. case 'd': return IsAsciiDigit(ch);
  7287. case 'D': return !IsAsciiDigit(ch);
  7288. case 'f': return ch == '\f';
  7289. case 'n': return ch == '\n';
  7290. case 'r': return ch == '\r';
  7291. case 's': return IsAsciiWhiteSpace(ch);
  7292. case 'S': return !IsAsciiWhiteSpace(ch);
  7293. case 't': return ch == '\t';
  7294. case 'v': return ch == '\v';
  7295. case 'w': return IsAsciiWordChar(ch);
  7296. case 'W': return !IsAsciiWordChar(ch);
  7297. }
  7298. return IsAsciiPunct(pattern_char) && pattern_char == ch;
  7299. }
  7300. return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
  7301. }
  7302. // Helper function used by ValidateRegex() to format error messages.
  7303. std::string FormatRegexSyntaxError(const char* regex, int index) {
  7304. return (Message() << "Syntax error at index " << index
  7305. << " in simple regular expression \"" << regex << "\": ").GetString();
  7306. }
  7307. // Generates non-fatal failures and returns false if regex is invalid;
  7308. // otherwise returns true.
  7309. bool ValidateRegex(const char* regex) {
  7310. if (regex == NULL) {
  7311. // TODO(wan@google.com): fix the source file location in the
  7312. // assertion failures to match where the regex is used in user
  7313. // code.
  7314. ADD_FAILURE() << "NULL is not a valid simple regular expression.";
  7315. return false;
  7316. }
  7317. bool is_valid = true;
  7318. // True iff ?, *, or + can follow the previous atom.
  7319. bool prev_repeatable = false;
  7320. for (int i = 0; regex[i]; i++) {
  7321. if (regex[i] == '\\') { // An escape sequence
  7322. i++;
  7323. if (regex[i] == '\0') {
  7324. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  7325. << "'\\' cannot appear at the end.";
  7326. return false;
  7327. }
  7328. if (!IsValidEscape(regex[i])) {
  7329. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  7330. << "invalid escape sequence \"\\" << regex[i] << "\".";
  7331. is_valid = false;
  7332. }
  7333. prev_repeatable = true;
  7334. } else { // Not an escape sequence.
  7335. const char ch = regex[i];
  7336. if (ch == '^' && i > 0) {
  7337. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  7338. << "'^' can only appear at the beginning.";
  7339. is_valid = false;
  7340. } else if (ch == '$' && regex[i + 1] != '\0') {
  7341. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  7342. << "'$' can only appear at the end.";
  7343. is_valid = false;
  7344. } else if (IsInSet(ch, "()[]{}|")) {
  7345. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  7346. << "'" << ch << "' is unsupported.";
  7347. is_valid = false;
  7348. } else if (IsRepeat(ch) && !prev_repeatable) {
  7349. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  7350. << "'" << ch << "' can only follow a repeatable token.";
  7351. is_valid = false;
  7352. }
  7353. prev_repeatable = !IsInSet(ch, "^$?*+");
  7354. }
  7355. }
  7356. return is_valid;
  7357. }
  7358. // Matches a repeated regex atom followed by a valid simple regular
  7359. // expression. The regex atom is defined as c if escaped is false,
  7360. // or \c otherwise. repeat is the repetition meta character (?, *,
  7361. // or +). The behavior is undefined if str contains too many
  7362. // characters to be indexable by size_t, in which case the test will
  7363. // probably time out anyway. We are fine with this limitation as
  7364. // std::string has it too.
  7365. bool MatchRepetitionAndRegexAtHead(
  7366. bool escaped, char c, char repeat, const char* regex,
  7367. const char* str) {
  7368. const size_t min_count = (repeat == '+') ? 1 : 0;
  7369. const size_t max_count = (repeat == '?') ? 1 :
  7370. static_cast<size_t>(-1) - 1;
  7371. // We cannot call numeric_limits::max() as it conflicts with the
  7372. // max() macro on Windows.
  7373. for (size_t i = 0; i <= max_count; ++i) {
  7374. // We know that the atom matches each of the first i characters in str.
  7375. if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
  7376. // We have enough matches at the head, and the tail matches too.
  7377. // Since we only care about *whether* the pattern matches str
  7378. // (as opposed to *how* it matches), there is no need to find a
  7379. // greedy match.
  7380. return true;
  7381. }
  7382. if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
  7383. return false;
  7384. }
  7385. return false;
  7386. }
  7387. // Returns true iff regex matches a prefix of str. regex must be a
  7388. // valid simple regular expression and not start with "^", or the
  7389. // result is undefined.
  7390. bool MatchRegexAtHead(const char* regex, const char* str) {
  7391. if (*regex == '\0') // An empty regex matches a prefix of anything.
  7392. return true;
  7393. // "$" only matches the end of a string. Note that regex being
  7394. // valid guarantees that there's nothing after "$" in it.
  7395. if (*regex == '$')
  7396. return *str == '\0';
  7397. // Is the first thing in regex an escape sequence?
  7398. const bool escaped = *regex == '\\';
  7399. if (escaped)
  7400. ++regex;
  7401. if (IsRepeat(regex[1])) {
  7402. // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
  7403. // here's an indirect recursion. It terminates as the regex gets
  7404. // shorter in each recursion.
  7405. return MatchRepetitionAndRegexAtHead(
  7406. escaped, regex[0], regex[1], regex + 2, str);
  7407. } else {
  7408. // regex isn't empty, isn't "$", and doesn't start with a
  7409. // repetition. We match the first atom of regex with the first
  7410. // character of str and recurse.
  7411. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
  7412. MatchRegexAtHead(regex + 1, str + 1);
  7413. }
  7414. }
  7415. // Returns true iff regex matches any substring of str. regex must be
  7416. // a valid simple regular expression, or the result is undefined.
  7417. //
  7418. // The algorithm is recursive, but the recursion depth doesn't exceed
  7419. // the regex length, so we won't need to worry about running out of
  7420. // stack space normally. In rare cases the time complexity can be
  7421. // exponential with respect to the regex length + the string length,
  7422. // but usually it's must faster (often close to linear).
  7423. bool MatchRegexAnywhere(const char* regex, const char* str) {
  7424. if (regex == NULL || str == NULL)
  7425. return false;
  7426. if (*regex == '^')
  7427. return MatchRegexAtHead(regex + 1, str);
  7428. // A successful match can be anywhere in str.
  7429. do {
  7430. if (MatchRegexAtHead(regex, str))
  7431. return true;
  7432. } while (*str++ != '\0');
  7433. return false;
  7434. }
  7435. // Implements the RE class.
  7436. RE::~RE() {
  7437. free(const_cast<char*>(pattern_));
  7438. free(const_cast<char*>(full_pattern_));
  7439. }
  7440. // Returns true iff regular expression re matches the entire str.
  7441. bool RE::FullMatch(const char* str, const RE& re) {
  7442. return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
  7443. }
  7444. // Returns true iff regular expression re matches a substring of str
  7445. // (including str itself).
  7446. bool RE::PartialMatch(const char* str, const RE& re) {
  7447. return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
  7448. }
  7449. // Initializes an RE from its string representation.
  7450. void RE::Init(const char* regex) {
  7451. pattern_ = full_pattern_ = NULL;
  7452. if (regex != NULL) {
  7453. pattern_ = posix::StrDup(regex);
  7454. }
  7455. is_valid_ = ValidateRegex(regex);
  7456. if (!is_valid_) {
  7457. // No need to calculate the full pattern when the regex is invalid.
  7458. return;
  7459. }
  7460. const size_t len = strlen(regex);
  7461. // Reserves enough bytes to hold the regular expression used for a
  7462. // full match: we need space to prepend a '^', append a '$', and
  7463. // terminate the string with '\0'.
  7464. char* buffer = static_cast<char*>(malloc(len + 3));
  7465. full_pattern_ = buffer;
  7466. if (*regex != '^')
  7467. *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
  7468. // We don't use snprintf or strncpy, as they trigger a warning when
  7469. // compiled with VC++ 8.0.
  7470. memcpy(buffer, regex, len);
  7471. buffer += len;
  7472. if (len == 0 || regex[len - 1] != '$')
  7473. *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
  7474. *buffer = '\0';
  7475. }
  7476. #endif // GTEST_USES_POSIX_RE
  7477. const char kUnknownFile[] = "unknown file";
  7478. // Formats a source file path and a line number as they would appear
  7479. // in an error message from the compiler used to compile this code.
  7480. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
  7481. const std::string file_name(file == NULL ? kUnknownFile : file);
  7482. if (line < 0) {
  7483. return file_name + ":";
  7484. }
  7485. #ifdef _MSC_VER
  7486. return file_name + "(" + StreamableToString(line) + "):";
  7487. #else
  7488. return file_name + ":" + StreamableToString(line) + ":";
  7489. #endif // _MSC_VER
  7490. }
  7491. // Formats a file location for compiler-independent XML output.
  7492. // Although this function is not platform dependent, we put it next to
  7493. // FormatFileLocation in order to contrast the two functions.
  7494. // Note that FormatCompilerIndependentFileLocation() does NOT append colon
  7495. // to the file location it produces, unlike FormatFileLocation().
  7496. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
  7497. const char* file, int line) {
  7498. const std::string file_name(file == NULL ? kUnknownFile : file);
  7499. if (line < 0)
  7500. return file_name;
  7501. else
  7502. return file_name + ":" + StreamableToString(line);
  7503. }
  7504. GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
  7505. : severity_(severity) {
  7506. const char* const marker =
  7507. severity == GTEST_INFO ? "[ INFO ]" :
  7508. severity == GTEST_WARNING ? "[WARNING]" :
  7509. severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
  7510. GetStream() << ::std::endl << marker << " "
  7511. << FormatFileLocation(file, line).c_str() << ": ";
  7512. }
  7513. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  7514. GTestLog::~GTestLog() {
  7515. GetStream() << ::std::endl;
  7516. if (severity_ == GTEST_FATAL) {
  7517. fflush(stderr);
  7518. posix::Abort();
  7519. }
  7520. }
  7521. // Disable Microsoft deprecation warnings for POSIX functions called from
  7522. // this class (creat, dup, dup2, and close)
  7523. #ifdef _MSC_VER
  7524. # pragma warning(push)
  7525. # pragma warning(disable: 4996)
  7526. #endif // _MSC_VER
  7527. #if GTEST_HAS_STREAM_REDIRECTION
  7528. // Object that captures an output stream (stdout/stderr).
  7529. class CapturedStream {
  7530. public:
  7531. // The ctor redirects the stream to a temporary file.
  7532. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
  7533. # if GTEST_OS_WINDOWS
  7534. char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  7535. char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  7536. ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
  7537. const UINT success = ::GetTempFileNameA(temp_dir_path,
  7538. "gtest_redir",
  7539. 0, // Generate unique file name.
  7540. temp_file_path);
  7541. GTEST_CHECK_(success != 0)
  7542. << "Unable to create a temporary file in " << temp_dir_path;
  7543. const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
  7544. GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
  7545. << temp_file_path;
  7546. filename_ = temp_file_path;
  7547. # else
  7548. // There's no guarantee that a test has write access to the current
  7549. // directory, so we create the temporary file in the /tmp directory
  7550. // instead. We use /tmp on most systems, and /sdcard on Android.
  7551. // That's because Android doesn't have /tmp.
  7552. # if GTEST_OS_LINUX_ANDROID
  7553. // Note: Android applications are expected to call the framework's
  7554. // Context.getExternalStorageDirectory() method through JNI to get
  7555. // the location of the world-writable SD Card directory. However,
  7556. // this requires a Context handle, which cannot be retrieved
  7557. // globally from native code. Doing so also precludes running the
  7558. // code as part of a regular standalone executable, which doesn't
  7559. // run in a Dalvik process (e.g. when running it through 'adb shell').
  7560. //
  7561. // The location /sdcard is directly accessible from native code
  7562. // and is the only location (unofficially) supported by the Android
  7563. // team. It's generally a symlink to the real SD Card mount point
  7564. // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
  7565. // other OEM-customized locations. Never rely on these, and always
  7566. // use /sdcard.
  7567. char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
  7568. # else
  7569. char name_template[] = "/tmp/captured_stream.XXXXXX";
  7570. # endif // GTEST_OS_LINUX_ANDROID
  7571. const int captured_fd = mkstemp(name_template);
  7572. filename_ = name_template;
  7573. # endif // GTEST_OS_WINDOWS
  7574. fflush(NULL);
  7575. dup2(captured_fd, fd_);
  7576. close(captured_fd);
  7577. }
  7578. ~CapturedStream() {
  7579. remove(filename_.c_str());
  7580. }
  7581. std::string GetCapturedString() {
  7582. if (uncaptured_fd_ != -1) {
  7583. // Restores the original stream.
  7584. fflush(NULL);
  7585. dup2(uncaptured_fd_, fd_);
  7586. close(uncaptured_fd_);
  7587. uncaptured_fd_ = -1;
  7588. }
  7589. FILE* const file = posix::FOpen(filename_.c_str(), "r");
  7590. const std::string content = ReadEntireFile(file);
  7591. posix::FClose(file);
  7592. return content;
  7593. }
  7594. private:
  7595. // Reads the entire content of a file as an std::string.
  7596. static std::string ReadEntireFile(FILE* file);
  7597. // Returns the size (in bytes) of a file.
  7598. static size_t GetFileSize(FILE* file);
  7599. const int fd_; // A stream to capture.
  7600. int uncaptured_fd_;
  7601. // Name of the temporary file holding the stderr output.
  7602. ::std::string filename_;
  7603. GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
  7604. };
  7605. // Returns the size (in bytes) of a file.
  7606. size_t CapturedStream::GetFileSize(FILE* file) {
  7607. fseek(file, 0, SEEK_END);
  7608. return static_cast<size_t>(ftell(file));
  7609. }
  7610. // Reads the entire content of a file as a string.
  7611. std::string CapturedStream::ReadEntireFile(FILE* file) {
  7612. const size_t file_size = GetFileSize(file);
  7613. char* const buffer = new char[file_size];
  7614. size_t bytes_last_read = 0; // # of bytes read in the last fread()
  7615. size_t bytes_read = 0; // # of bytes read so far
  7616. fseek(file, 0, SEEK_SET);
  7617. // Keeps reading the file until we cannot read further or the
  7618. // pre-determined file size is reached.
  7619. do {
  7620. bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
  7621. bytes_read += bytes_last_read;
  7622. } while (bytes_last_read > 0 && bytes_read < file_size);
  7623. const std::string content(buffer, bytes_read);
  7624. delete[] buffer;
  7625. return content;
  7626. }
  7627. # ifdef _MSC_VER
  7628. # pragma warning(pop)
  7629. # endif // _MSC_VER
  7630. static CapturedStream* g_captured_stderr = NULL;
  7631. static CapturedStream* g_captured_stdout = NULL;
  7632. // Starts capturing an output stream (stdout/stderr).
  7633. void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
  7634. if (*stream != NULL) {
  7635. GTEST_LOG_(FATAL) << "Only one " << stream_name
  7636. << " capturer can exist at a time.";
  7637. }
  7638. *stream = new CapturedStream(fd);
  7639. }
  7640. // Stops capturing the output stream and returns the captured string.
  7641. std::string GetCapturedStream(CapturedStream** captured_stream) {
  7642. const std::string content = (*captured_stream)->GetCapturedString();
  7643. delete *captured_stream;
  7644. *captured_stream = NULL;
  7645. return content;
  7646. }
  7647. // Starts capturing stdout.
  7648. void CaptureStdout() {
  7649. CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
  7650. }
  7651. // Starts capturing stderr.
  7652. void CaptureStderr() {
  7653. CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
  7654. }
  7655. // Stops capturing stdout and returns the captured string.
  7656. std::string GetCapturedStdout() {
  7657. return GetCapturedStream(&g_captured_stdout);
  7658. }
  7659. // Stops capturing stderr and returns the captured string.
  7660. std::string GetCapturedStderr() {
  7661. return GetCapturedStream(&g_captured_stderr);
  7662. }
  7663. #endif // GTEST_HAS_STREAM_REDIRECTION
  7664. #if GTEST_HAS_DEATH_TEST
  7665. // A copy of all command line arguments. Set by InitGoogleTest().
  7666. ::std::vector<testing::internal::string> g_argvs;
  7667. static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
  7668. NULL; // Owned.
  7669. void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
  7670. if (g_injected_test_argvs != argvs)
  7671. delete g_injected_test_argvs;
  7672. g_injected_test_argvs = argvs;
  7673. }
  7674. const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
  7675. if (g_injected_test_argvs != NULL) {
  7676. return *g_injected_test_argvs;
  7677. }
  7678. return g_argvs;
  7679. }
  7680. #endif // GTEST_HAS_DEATH_TEST
  7681. #if GTEST_OS_WINDOWS_MOBILE
  7682. namespace posix {
  7683. void Abort() {
  7684. DebugBreak();
  7685. TerminateProcess(GetCurrentProcess(), 1);
  7686. }
  7687. } // namespace posix
  7688. #endif // GTEST_OS_WINDOWS_MOBILE
  7689. // Returns the name of the environment variable corresponding to the
  7690. // given flag. For example, FlagToEnvVar("foo") will return
  7691. // "GTEST_FOO" in the open-source version.
  7692. static std::string FlagToEnvVar(const char* flag) {
  7693. const std::string full_flag =
  7694. (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
  7695. Message env_var;
  7696. for (size_t i = 0; i != full_flag.length(); i++) {
  7697. env_var << ToUpper(full_flag.c_str()[i]);
  7698. }
  7699. return env_var.GetString();
  7700. }
  7701. // Parses 'str' for a 32-bit signed integer. If successful, writes
  7702. // the result to *value and returns true; otherwise leaves *value
  7703. // unchanged and returns false.
  7704. bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
  7705. // Parses the environment variable as a decimal integer.
  7706. char* end = NULL;
  7707. const long long_value = strtol(str, &end, 10); // NOLINT
  7708. // Has strtol() consumed all characters in the string?
  7709. if (*end != '\0') {
  7710. // No - an invalid character was encountered.
  7711. Message msg;
  7712. msg << "WARNING: " << src_text
  7713. << " is expected to be a 32-bit integer, but actually"
  7714. << " has value \"" << str << "\".\n";
  7715. printf("%s", msg.GetString().c_str());
  7716. fflush(stdout);
  7717. return false;
  7718. }
  7719. // Is the parsed value in the range of an Int32?
  7720. const Int32 result = static_cast<Int32>(long_value);
  7721. if (long_value == LONG_MAX || long_value == LONG_MIN ||
  7722. // The parsed value overflows as a long. (strtol() returns
  7723. // LONG_MAX or LONG_MIN when the input overflows.)
  7724. result != long_value
  7725. // The parsed value overflows as an Int32.
  7726. ) {
  7727. Message msg;
  7728. msg << "WARNING: " << src_text
  7729. << " is expected to be a 32-bit integer, but actually"
  7730. << " has value " << str << ", which overflows.\n";
  7731. printf("%s", msg.GetString().c_str());
  7732. fflush(stdout);
  7733. return false;
  7734. }
  7735. *value = result;
  7736. return true;
  7737. }
  7738. // Reads and returns the Boolean environment variable corresponding to
  7739. // the given flag; if it's not set, returns default_value.
  7740. //
  7741. // The value is considered true iff it's not "0".
  7742. bool BoolFromGTestEnv(const char* flag, bool default_value) {
  7743. const std::string env_var = FlagToEnvVar(flag);
  7744. const char* const string_value = posix::GetEnv(env_var.c_str());
  7745. return string_value == NULL ?
  7746. default_value : strcmp(string_value, "0") != 0;
  7747. }
  7748. // Reads and returns a 32-bit integer stored in the environment
  7749. // variable corresponding to the given flag; if it isn't set or
  7750. // doesn't represent a valid 32-bit integer, returns default_value.
  7751. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
  7752. const std::string env_var = FlagToEnvVar(flag);
  7753. const char* const string_value = posix::GetEnv(env_var.c_str());
  7754. if (string_value == NULL) {
  7755. // The environment variable is not set.
  7756. return default_value;
  7757. }
  7758. Int32 result = default_value;
  7759. if (!ParseInt32(Message() << "Environment variable " << env_var,
  7760. string_value, &result)) {
  7761. printf("The default value %s is used.\n",
  7762. (Message() << default_value).GetString().c_str());
  7763. fflush(stdout);
  7764. return default_value;
  7765. }
  7766. return result;
  7767. }
  7768. // Reads and returns the string environment variable corresponding to
  7769. // the given flag; if it's not set, returns default_value.
  7770. const char* StringFromGTestEnv(const char* flag, const char* default_value) {
  7771. const std::string env_var = FlagToEnvVar(flag);
  7772. const char* const value = posix::GetEnv(env_var.c_str());
  7773. return value == NULL ? default_value : value;
  7774. }
  7775. } // namespace internal
  7776. } // namespace testing
  7777. // Copyright 2007, Google Inc.
  7778. // All rights reserved.
  7779. //
  7780. // Redistribution and use in source and binary forms, with or without
  7781. // modification, are permitted provided that the following conditions are
  7782. // met:
  7783. //
  7784. // * Redistributions of source code must retain the above copyright
  7785. // notice, this list of conditions and the following disclaimer.
  7786. // * Redistributions in binary form must reproduce the above
  7787. // copyright notice, this list of conditions and the following disclaimer
  7788. // in the documentation and/or other materials provided with the
  7789. // distribution.
  7790. // * Neither the name of Google Inc. nor the names of its
  7791. // contributors may be used to endorse or promote products derived from
  7792. // this software without specific prior written permission.
  7793. //
  7794. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7795. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7796. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7797. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7798. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7799. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7800. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7801. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7802. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7803. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7804. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7805. //
  7806. // Author: wan@google.com (Zhanyong Wan)
  7807. // Google Test - The Google C++ Testing Framework
  7808. //
  7809. // This file implements a universal value printer that can print a
  7810. // value of any type T:
  7811. //
  7812. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  7813. //
  7814. // It uses the << operator when possible, and prints the bytes in the
  7815. // object otherwise. A user can override its behavior for a class
  7816. // type Foo by defining either operator<<(::std::ostream&, const Foo&)
  7817. // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
  7818. // defines Foo.
  7819. #include <ctype.h>
  7820. #include <stdio.h>
  7821. #include <ostream> // NOLINT
  7822. #include <string>
  7823. namespace testing {
  7824. namespace {
  7825. using ::std::ostream;
  7826. // Prints a segment of bytes in the given object.
  7827. void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
  7828. size_t count, ostream* os) {
  7829. char text[5] = "";
  7830. for (size_t i = 0; i != count; i++) {
  7831. const size_t j = start + i;
  7832. if (i != 0) {
  7833. // Organizes the bytes into groups of 2 for easy parsing by
  7834. // human.
  7835. if ((j % 2) == 0)
  7836. *os << ' ';
  7837. else
  7838. *os << '-';
  7839. }
  7840. GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
  7841. *os << text;
  7842. }
  7843. }
  7844. // Prints the bytes in the given value to the given ostream.
  7845. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
  7846. ostream* os) {
  7847. // Tells the user how big the object is.
  7848. *os << count << "-byte object <";
  7849. const size_t kThreshold = 132;
  7850. const size_t kChunkSize = 64;
  7851. // If the object size is bigger than kThreshold, we'll have to omit
  7852. // some details by printing only the first and the last kChunkSize
  7853. // bytes.
  7854. // TODO(wan): let the user control the threshold using a flag.
  7855. if (count < kThreshold) {
  7856. PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
  7857. } else {
  7858. PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
  7859. *os << " ... ";
  7860. // Rounds up to 2-byte boundary.
  7861. const size_t resume_pos = (count - kChunkSize + 1)/2*2;
  7862. PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
  7863. }
  7864. *os << ">";
  7865. }
  7866. } // namespace
  7867. namespace internal2 {
  7868. // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
  7869. // given object. The delegation simplifies the implementation, which
  7870. // uses the << operator and thus is easier done outside of the
  7871. // ::testing::internal namespace, which contains a << operator that
  7872. // sometimes conflicts with the one in STL.
  7873. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
  7874. ostream* os) {
  7875. PrintBytesInObjectToImpl(obj_bytes, count, os);
  7876. }
  7877. } // namespace internal2
  7878. namespace internal {
  7879. // Depending on the value of a char (or wchar_t), we print it in one
  7880. // of three formats:
  7881. // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
  7882. // - as a hexidecimal escape sequence (e.g. '\x7F'), or
  7883. // - as a special escape sequence (e.g. '\r', '\n').
  7884. enum CharFormat {
  7885. kAsIs,
  7886. kHexEscape,
  7887. kSpecialEscape
  7888. };
  7889. // Returns true if c is a printable ASCII character. We test the
  7890. // value of c directly instead of calling isprint(), which is buggy on
  7891. // Windows Mobile.
  7892. inline bool IsPrintableAscii(wchar_t c) {
  7893. return 0x20 <= c && c <= 0x7E;
  7894. }
  7895. // Prints a wide or narrow char c as a character literal without the
  7896. // quotes, escaping it when necessary; returns how c was formatted.
  7897. // The template argument UnsignedChar is the unsigned version of Char,
  7898. // which is the type of c.
  7899. template <typename UnsignedChar, typename Char>
  7900. static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
  7901. switch (static_cast<wchar_t>(c)) {
  7902. case L'\0':
  7903. *os << "\\0";
  7904. break;
  7905. case L'\'':
  7906. *os << "\\'";
  7907. break;
  7908. case L'\\':
  7909. *os << "\\\\";
  7910. break;
  7911. case L'\a':
  7912. *os << "\\a";
  7913. break;
  7914. case L'\b':
  7915. *os << "\\b";
  7916. break;
  7917. case L'\f':
  7918. *os << "\\f";
  7919. break;
  7920. case L'\n':
  7921. *os << "\\n";
  7922. break;
  7923. case L'\r':
  7924. *os << "\\r";
  7925. break;
  7926. case L'\t':
  7927. *os << "\\t";
  7928. break;
  7929. case L'\v':
  7930. *os << "\\v";
  7931. break;
  7932. default:
  7933. if (IsPrintableAscii(c)) {
  7934. *os << static_cast<char>(c);
  7935. return kAsIs;
  7936. } else {
  7937. *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
  7938. return kHexEscape;
  7939. }
  7940. }
  7941. return kSpecialEscape;
  7942. }
  7943. // Prints a wchar_t c as if it's part of a string literal, escaping it when
  7944. // necessary; returns how c was formatted.
  7945. static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
  7946. switch (c) {
  7947. case L'\'':
  7948. *os << "'";
  7949. return kAsIs;
  7950. case L'"':
  7951. *os << "\\\"";
  7952. return kSpecialEscape;
  7953. default:
  7954. return PrintAsCharLiteralTo<wchar_t>(c, os);
  7955. }
  7956. }
  7957. // Prints a char c as if it's part of a string literal, escaping it when
  7958. // necessary; returns how c was formatted.
  7959. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
  7960. return PrintAsStringLiteralTo(
  7961. static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
  7962. }
  7963. // Prints a wide or narrow character c and its code. '\0' is printed
  7964. // as "'\\0'", other unprintable characters are also properly escaped
  7965. // using the standard C++ escape sequence. The template argument
  7966. // UnsignedChar is the unsigned version of Char, which is the type of c.
  7967. template <typename UnsignedChar, typename Char>
  7968. void PrintCharAndCodeTo(Char c, ostream* os) {
  7969. // First, print c as a literal in the most readable form we can find.
  7970. *os << ((sizeof(c) > 1) ? "L'" : "'");
  7971. const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
  7972. *os << "'";
  7973. // To aid user debugging, we also print c's code in decimal, unless
  7974. // it's 0 (in which case c was printed as '\\0', making the code
  7975. // obvious).
  7976. if (c == 0)
  7977. return;
  7978. *os << " (" << static_cast<int>(c);
  7979. // For more convenience, we print c's code again in hexidecimal,
  7980. // unless c was already printed in the form '\x##' or the code is in
  7981. // [1, 9].
  7982. if (format == kHexEscape || (1 <= c && c <= 9)) {
  7983. // Do nothing.
  7984. } else {
  7985. *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
  7986. }
  7987. *os << ")";
  7988. }
  7989. void PrintTo(unsigned char c, ::std::ostream* os) {
  7990. PrintCharAndCodeTo<unsigned char>(c, os);
  7991. }
  7992. void PrintTo(signed char c, ::std::ostream* os) {
  7993. PrintCharAndCodeTo<unsigned char>(c, os);
  7994. }
  7995. // Prints a wchar_t as a symbol if it is printable or as its internal
  7996. // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
  7997. void PrintTo(wchar_t wc, ostream* os) {
  7998. PrintCharAndCodeTo<wchar_t>(wc, os);
  7999. }
  8000. // Prints the given array of characters to the ostream. CharType must be either
  8001. // char or wchar_t.
  8002. // The array starts at begin, the length is len, it may include '\0' characters
  8003. // and may not be NUL-terminated.
  8004. template <typename CharType>
  8005. static void PrintCharsAsStringTo(
  8006. const CharType* begin, size_t len, ostream* os) {
  8007. const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
  8008. *os << kQuoteBegin;
  8009. bool is_previous_hex = false;
  8010. for (size_t index = 0; index < len; ++index) {
  8011. const CharType cur = begin[index];
  8012. if (is_previous_hex && IsXDigit(cur)) {
  8013. // Previous character is of '\x..' form and this character can be
  8014. // interpreted as another hexadecimal digit in its number. Break string to
  8015. // disambiguate.
  8016. *os << "\" " << kQuoteBegin;
  8017. }
  8018. is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
  8019. }
  8020. *os << "\"";
  8021. }
  8022. // Prints a (const) char/wchar_t array of 'len' elements, starting at address
  8023. // 'begin'. CharType must be either char or wchar_t.
  8024. template <typename CharType>
  8025. static void UniversalPrintCharArray(
  8026. const CharType* begin, size_t len, ostream* os) {
  8027. // The code
  8028. // const char kFoo[] = "foo";
  8029. // generates an array of 4, not 3, elements, with the last one being '\0'.
  8030. //
  8031. // Therefore when printing a char array, we don't print the last element if
  8032. // it's '\0', such that the output matches the string literal as it's
  8033. // written in the source code.
  8034. if (len > 0 && begin[len - 1] == '\0') {
  8035. PrintCharsAsStringTo(begin, len - 1, os);
  8036. return;
  8037. }
  8038. // If, however, the last element in the array is not '\0', e.g.
  8039. // const char kFoo[] = { 'f', 'o', 'o' };
  8040. // we must print the entire array. We also print a message to indicate
  8041. // that the array is not NUL-terminated.
  8042. PrintCharsAsStringTo(begin, len, os);
  8043. *os << " (no terminating NUL)";
  8044. }
  8045. // Prints a (const) char array of 'len' elements, starting at address 'begin'.
  8046. void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
  8047. UniversalPrintCharArray(begin, len, os);
  8048. }
  8049. // Prints a (const) wchar_t array of 'len' elements, starting at address
  8050. // 'begin'.
  8051. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
  8052. UniversalPrintCharArray(begin, len, os);
  8053. }
  8054. // Prints the given C string to the ostream.
  8055. void PrintTo(const char* s, ostream* os) {
  8056. if (s == NULL) {
  8057. *os << "NULL";
  8058. } else {
  8059. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  8060. PrintCharsAsStringTo(s, strlen(s), os);
  8061. }
  8062. }
  8063. // MSVC compiler can be configured to define whar_t as a typedef
  8064. // of unsigned short. Defining an overload for const wchar_t* in that case
  8065. // would cause pointers to unsigned shorts be printed as wide strings,
  8066. // possibly accessing more memory than intended and causing invalid
  8067. // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
  8068. // wchar_t is implemented as a native type.
  8069. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  8070. // Prints the given wide C string to the ostream.
  8071. void PrintTo(const wchar_t* s, ostream* os) {
  8072. if (s == NULL) {
  8073. *os << "NULL";
  8074. } else {
  8075. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  8076. PrintCharsAsStringTo(s, wcslen(s), os);
  8077. }
  8078. }
  8079. #endif // wchar_t is native
  8080. // Prints a ::string object.
  8081. #if GTEST_HAS_GLOBAL_STRING
  8082. void PrintStringTo(const ::string& s, ostream* os) {
  8083. PrintCharsAsStringTo(s.data(), s.size(), os);
  8084. }
  8085. #endif // GTEST_HAS_GLOBAL_STRING
  8086. void PrintStringTo(const ::std::string& s, ostream* os) {
  8087. PrintCharsAsStringTo(s.data(), s.size(), os);
  8088. }
  8089. // Prints a ::wstring object.
  8090. #if GTEST_HAS_GLOBAL_WSTRING
  8091. void PrintWideStringTo(const ::wstring& s, ostream* os) {
  8092. PrintCharsAsStringTo(s.data(), s.size(), os);
  8093. }
  8094. #endif // GTEST_HAS_GLOBAL_WSTRING
  8095. #if GTEST_HAS_STD_WSTRING
  8096. void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
  8097. PrintCharsAsStringTo(s.data(), s.size(), os);
  8098. }
  8099. #endif // GTEST_HAS_STD_WSTRING
  8100. } // namespace internal
  8101. } // namespace testing
  8102. // Copyright 2008, Google Inc.
  8103. // All rights reserved.
  8104. //
  8105. // Redistribution and use in source and binary forms, with or without
  8106. // modification, are permitted provided that the following conditions are
  8107. // met:
  8108. //
  8109. // * Redistributions of source code must retain the above copyright
  8110. // notice, this list of conditions and the following disclaimer.
  8111. // * Redistributions in binary form must reproduce the above
  8112. // copyright notice, this list of conditions and the following disclaimer
  8113. // in the documentation and/or other materials provided with the
  8114. // distribution.
  8115. // * Neither the name of Google Inc. nor the names of its
  8116. // contributors may be used to endorse or promote products derived from
  8117. // this software without specific prior written permission.
  8118. //
  8119. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8120. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8121. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8122. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8123. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8124. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8125. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8126. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8127. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8128. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8129. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8130. //
  8131. // Author: mheule@google.com (Markus Heule)
  8132. //
  8133. // The Google C++ Testing Framework (Google Test)
  8134. // Indicates that this translation unit is part of Google Test's
  8135. // implementation. It must come before gtest-internal-inl.h is
  8136. // included, or there will be a compiler error. This trick is to
  8137. // prevent a user from accidentally including gtest-internal-inl.h in
  8138. // his code.
  8139. #define GTEST_IMPLEMENTATION_ 1
  8140. #undef GTEST_IMPLEMENTATION_
  8141. namespace testing {
  8142. using internal::GetUnitTestImpl;
  8143. // Gets the summary of the failure message by omitting the stack trace
  8144. // in it.
  8145. std::string TestPartResult::ExtractSummary(const char* message) {
  8146. const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
  8147. return stack_trace == NULL ? message :
  8148. std::string(message, stack_trace);
  8149. }
  8150. // Prints a TestPartResult object.
  8151. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
  8152. return os
  8153. << result.file_name() << ":" << result.line_number() << ": "
  8154. << (result.type() == TestPartResult::kSuccess ? "Success" :
  8155. result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
  8156. "Non-fatal failure") << ":\n"
  8157. << result.message() << std::endl;
  8158. }
  8159. // Appends a TestPartResult to the array.
  8160. void TestPartResultArray::Append(const TestPartResult& result) {
  8161. array_.push_back(result);
  8162. }
  8163. // Returns the TestPartResult at the given index (0-based).
  8164. const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
  8165. if (index < 0 || index >= size()) {
  8166. printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
  8167. internal::posix::Abort();
  8168. }
  8169. return array_[index];
  8170. }
  8171. // Returns the number of TestPartResult objects in the array.
  8172. int TestPartResultArray::size() const {
  8173. return static_cast<int>(array_.size());
  8174. }
  8175. namespace internal {
  8176. HasNewFatalFailureHelper::HasNewFatalFailureHelper()
  8177. : has_new_fatal_failure_(false),
  8178. original_reporter_(GetUnitTestImpl()->
  8179. GetTestPartResultReporterForCurrentThread()) {
  8180. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
  8181. }
  8182. HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
  8183. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
  8184. original_reporter_);
  8185. }
  8186. void HasNewFatalFailureHelper::ReportTestPartResult(
  8187. const TestPartResult& result) {
  8188. if (result.fatally_failed())
  8189. has_new_fatal_failure_ = true;
  8190. original_reporter_->ReportTestPartResult(result);
  8191. }
  8192. } // namespace internal
  8193. } // namespace testing
  8194. // Copyright 2008 Google Inc.
  8195. // All Rights Reserved.
  8196. //
  8197. // Redistribution and use in source and binary forms, with or without
  8198. // modification, are permitted provided that the following conditions are
  8199. // met:
  8200. //
  8201. // * Redistributions of source code must retain the above copyright
  8202. // notice, this list of conditions and the following disclaimer.
  8203. // * Redistributions in binary form must reproduce the above
  8204. // copyright notice, this list of conditions and the following disclaimer
  8205. // in the documentation and/or other materials provided with the
  8206. // distribution.
  8207. // * Neither the name of Google Inc. nor the names of its
  8208. // contributors may be used to endorse or promote products derived from
  8209. // this software without specific prior written permission.
  8210. //
  8211. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8212. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8213. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8214. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8215. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8216. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8217. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8218. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8219. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8220. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8221. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8222. //
  8223. // Author: wan@google.com (Zhanyong Wan)
  8224. namespace testing {
  8225. namespace internal {
  8226. #if GTEST_HAS_TYPED_TEST_P
  8227. // Skips to the first non-space char in str. Returns an empty string if str
  8228. // contains only whitespace characters.
  8229. static const char* SkipSpaces(const char* str) {
  8230. while (IsSpace(*str))
  8231. str++;
  8232. return str;
  8233. }
  8234. // Verifies that registered_tests match the test names in
  8235. // defined_test_names_; returns registered_tests if successful, or
  8236. // aborts the program otherwise.
  8237. const char* TypedTestCasePState::VerifyRegisteredTestNames(
  8238. const char* file, int line, const char* registered_tests) {
  8239. typedef ::std::set<const char*>::const_iterator DefinedTestIter;
  8240. registered_ = true;
  8241. // Skip initial whitespace in registered_tests since some
  8242. // preprocessors prefix stringizied literals with whitespace.
  8243. registered_tests = SkipSpaces(registered_tests);
  8244. Message errors;
  8245. ::std::set<std::string> tests;
  8246. for (const char* names = registered_tests; names != NULL;
  8247. names = SkipComma(names)) {
  8248. const std::string name = GetPrefixUntilComma(names);
  8249. if (tests.count(name) != 0) {
  8250. errors << "Test " << name << " is listed more than once.\n";
  8251. continue;
  8252. }
  8253. bool found = false;
  8254. for (DefinedTestIter it = defined_test_names_.begin();
  8255. it != defined_test_names_.end();
  8256. ++it) {
  8257. if (name == *it) {
  8258. found = true;
  8259. break;
  8260. }
  8261. }
  8262. if (found) {
  8263. tests.insert(name);
  8264. } else {
  8265. errors << "No test named " << name
  8266. << " can be found in this test case.\n";
  8267. }
  8268. }
  8269. for (DefinedTestIter it = defined_test_names_.begin();
  8270. it != defined_test_names_.end();
  8271. ++it) {
  8272. if (tests.count(*it) == 0) {
  8273. errors << "You forgot to list test " << *it << ".\n";
  8274. }
  8275. }
  8276. const std::string& errors_str = errors.GetString();
  8277. if (errors_str != "") {
  8278. fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
  8279. errors_str.c_str());
  8280. fflush(stderr);
  8281. posix::Abort();
  8282. }
  8283. return registered_tests;
  8284. }
  8285. #endif // GTEST_HAS_TYPED_TEST_P
  8286. } // namespace internal
  8287. } // namespace testing