gtest.cc 243 KB

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