gtest-all.cc 329 KB

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