gmock-gtest-all.cc 520 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434
  1. // Copyright 2008, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Google C++ Testing and Mocking Framework (Google Test)
  31. //
  32. // Sometimes it's desirable to build Google Test by compiling a single file.
  33. // This file serves this purpose.
  34. // This line ensures that gtest.h can be compiled on its own, even
  35. // when it's fused.
  36. #include "gtest/gtest.h"
  37. // The following lines pull in the real gtest *.cc files.
  38. // Copyright 2005, Google Inc.
  39. // All rights reserved.
  40. //
  41. // Redistribution and use in source and binary forms, with or without
  42. // modification, are permitted provided that the following conditions are
  43. // met:
  44. //
  45. // * Redistributions of source code must retain the above copyright
  46. // notice, this list of conditions and the following disclaimer.
  47. // * Redistributions in binary form must reproduce the above
  48. // copyright notice, this list of conditions and the following disclaimer
  49. // in the documentation and/or other materials provided with the
  50. // distribution.
  51. // * Neither the name of Google Inc. nor the names of its
  52. // contributors may be used to endorse or promote products derived from
  53. // this software without specific prior written permission.
  54. //
  55. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  56. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  57. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  58. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  59. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  60. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  61. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  62. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  63. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  64. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  65. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  66. //
  67. // The Google C++ Testing and Mocking Framework (Google Test)
  68. // Copyright 2007, Google Inc.
  69. // All rights reserved.
  70. //
  71. // Redistribution and use in source and binary forms, with or without
  72. // modification, are permitted provided that the following conditions are
  73. // met:
  74. //
  75. // * Redistributions of source code must retain the above copyright
  76. // notice, this list of conditions and the following disclaimer.
  77. // * Redistributions in binary form must reproduce the above
  78. // copyright notice, this list of conditions and the following disclaimer
  79. // in the documentation and/or other materials provided with the
  80. // distribution.
  81. // * Neither the name of Google Inc. nor the names of its
  82. // contributors may be used to endorse or promote products derived from
  83. // this software without specific prior written permission.
  84. //
  85. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  86. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  87. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  88. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  89. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  90. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  91. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  92. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  93. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  94. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  95. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  96. //
  97. // Utilities for testing Google Test itself and code that uses Google Test
  98. // (e.g. frameworks built on top of Google Test).
  99. // GOOGLETEST_CM0004 DO NOT DELETE
  100. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
  101. #define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
  102. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  103. /* class A needs to have dll-interface to be used by clients of class B */)
  104. namespace testing {
  105. // This helper class can be used to mock out Google Test failure reporting
  106. // so that we can test Google Test or code that builds on Google Test.
  107. //
  108. // An object of this class appends a TestPartResult object to the
  109. // TestPartResultArray object given in the constructor whenever a Google Test
  110. // failure is reported. It can either intercept only failures that are
  111. // generated in the same thread that created this object or it can intercept
  112. // all generated failures. The scope of this mock object can be controlled with
  113. // the second argument to the two arguments constructor.
  114. class GTEST_API_ ScopedFakeTestPartResultReporter
  115. : public TestPartResultReporterInterface {
  116. public:
  117. // The two possible mocking modes of this object.
  118. enum InterceptMode {
  119. INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
  120. INTERCEPT_ALL_THREADS // Intercepts all failures.
  121. };
  122. // The c'tor sets this object as the test part result reporter used
  123. // by Google Test. The 'result' parameter specifies where to report the
  124. // results. This reporter will only catch failures generated in the current
  125. // thread. DEPRECATED
  126. explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
  127. // Same as above, but you can choose the interception scope of this object.
  128. ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
  129. TestPartResultArray* result);
  130. // The d'tor restores the previous test part result reporter.
  131. ~ScopedFakeTestPartResultReporter() override;
  132. // Appends the TestPartResult object to the TestPartResultArray
  133. // received in the constructor.
  134. //
  135. // This method is from the TestPartResultReporterInterface
  136. // interface.
  137. void ReportTestPartResult(const TestPartResult& result) override;
  138. private:
  139. void Init();
  140. const InterceptMode intercept_mode_;
  141. TestPartResultReporterInterface* old_reporter_;
  142. TestPartResultArray* const result_;
  143. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
  144. };
  145. namespace internal {
  146. // A helper class for implementing EXPECT_FATAL_FAILURE() and
  147. // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
  148. // TestPartResultArray contains exactly one failure that has the given
  149. // type and contains the given substring. If that's not the case, a
  150. // non-fatal failure will be generated.
  151. class GTEST_API_ SingleFailureChecker {
  152. public:
  153. // The constructor remembers the arguments.
  154. SingleFailureChecker(const TestPartResultArray* results,
  155. TestPartResult::Type type, const std::string& substr);
  156. ~SingleFailureChecker();
  157. private:
  158. const TestPartResultArray* const results_;
  159. const TestPartResult::Type type_;
  160. const std::string substr_;
  161. GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
  162. };
  163. } // namespace internal
  164. } // namespace testing
  165. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  166. // A set of macros for testing Google Test assertions or code that's expected
  167. // to generate Google Test fatal failures. It verifies that the given
  168. // statement will cause exactly one fatal Google Test failure with 'substr'
  169. // being part of the failure message.
  170. //
  171. // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
  172. // affects and considers failures generated in the current thread and
  173. // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
  174. //
  175. // The verification of the assertion is done correctly even when the statement
  176. // throws an exception or aborts the current function.
  177. //
  178. // Known restrictions:
  179. // - 'statement' cannot reference local non-static variables or
  180. // non-static members of the current object.
  181. // - 'statement' cannot return a value.
  182. // - You cannot stream a failure message to this macro.
  183. //
  184. // Note that even though the implementations of the following two
  185. // macros are much alike, we cannot refactor them to use a common
  186. // helper macro, due to some peculiarity in how the preprocessor
  187. // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
  188. // gtest_unittest.cc will fail to compile if we do that.
  189. #define EXPECT_FATAL_FAILURE(statement, substr) \
  190. do { \
  191. class GTestExpectFatalFailureHelper {\
  192. public:\
  193. static void Execute() { statement; }\
  194. };\
  195. ::testing::TestPartResultArray gtest_failures;\
  196. ::testing::internal::SingleFailureChecker gtest_checker(\
  197. &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
  198. {\
  199. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  200. ::testing::ScopedFakeTestPartResultReporter:: \
  201. INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
  202. GTestExpectFatalFailureHelper::Execute();\
  203. }\
  204. } while (::testing::internal::AlwaysFalse())
  205. #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
  206. do { \
  207. class GTestExpectFatalFailureHelper {\
  208. public:\
  209. static void Execute() { statement; }\
  210. };\
  211. ::testing::TestPartResultArray gtest_failures;\
  212. ::testing::internal::SingleFailureChecker gtest_checker(\
  213. &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
  214. {\
  215. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  216. ::testing::ScopedFakeTestPartResultReporter:: \
  217. INTERCEPT_ALL_THREADS, &gtest_failures);\
  218. GTestExpectFatalFailureHelper::Execute();\
  219. }\
  220. } while (::testing::internal::AlwaysFalse())
  221. // A macro for testing Google Test assertions or code that's expected to
  222. // generate Google Test non-fatal failures. It asserts that the given
  223. // statement will cause exactly one non-fatal Google Test failure with 'substr'
  224. // being part of the failure message.
  225. //
  226. // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
  227. // affects and considers failures generated in the current thread and
  228. // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
  229. //
  230. // 'statement' is allowed to reference local variables and members of
  231. // the current object.
  232. //
  233. // The verification of the assertion is done correctly even when the statement
  234. // throws an exception or aborts the current function.
  235. //
  236. // Known restrictions:
  237. // - You cannot stream a failure message to this macro.
  238. //
  239. // Note that even though the implementations of the following two
  240. // macros are much alike, we cannot refactor them to use a common
  241. // helper macro, due to some peculiarity in how the preprocessor
  242. // works. If we do that, the code won't compile when the user gives
  243. // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
  244. // expands to code containing an unprotected comma. The
  245. // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
  246. // catches that.
  247. //
  248. // For the same reason, we have to write
  249. // if (::testing::internal::AlwaysTrue()) { statement; }
  250. // instead of
  251. // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
  252. // to avoid an MSVC warning on unreachable code.
  253. #define EXPECT_NONFATAL_FAILURE(statement, substr) \
  254. do {\
  255. ::testing::TestPartResultArray gtest_failures;\
  256. ::testing::internal::SingleFailureChecker gtest_checker(\
  257. &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
  258. (substr));\
  259. {\
  260. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  261. ::testing::ScopedFakeTestPartResultReporter:: \
  262. INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
  263. if (::testing::internal::AlwaysTrue()) { statement; }\
  264. }\
  265. } while (::testing::internal::AlwaysFalse())
  266. #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
  267. do {\
  268. ::testing::TestPartResultArray gtest_failures;\
  269. ::testing::internal::SingleFailureChecker gtest_checker(\
  270. &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
  271. (substr));\
  272. {\
  273. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  274. ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
  275. &gtest_failures);\
  276. if (::testing::internal::AlwaysTrue()) { statement; }\
  277. }\
  278. } while (::testing::internal::AlwaysFalse())
  279. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
  280. #include <ctype.h>
  281. #include <stdarg.h>
  282. #include <stdio.h>
  283. #include <stdlib.h>
  284. #include <time.h>
  285. #include <wchar.h>
  286. #include <wctype.h>
  287. #include <algorithm>
  288. #include <chrono> // NOLINT
  289. #include <cmath>
  290. #include <cstdint>
  291. #include <iomanip>
  292. #include <limits>
  293. #include <list>
  294. #include <map>
  295. #include <ostream> // NOLINT
  296. #include <sstream>
  297. #include <vector>
  298. #if GTEST_OS_LINUX
  299. # include <fcntl.h> // NOLINT
  300. # include <limits.h> // NOLINT
  301. # include <sched.h> // NOLINT
  302. // Declares vsnprintf(). This header is not available on Windows.
  303. # include <strings.h> // NOLINT
  304. # include <sys/mman.h> // NOLINT
  305. # include <sys/time.h> // NOLINT
  306. # include <unistd.h> // NOLINT
  307. # include <string>
  308. #elif GTEST_OS_ZOS
  309. # include <sys/time.h> // NOLINT
  310. // On z/OS we additionally need strings.h for strcasecmp.
  311. # include <strings.h> // NOLINT
  312. #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
  313. # include <windows.h> // NOLINT
  314. # undef min
  315. #elif GTEST_OS_WINDOWS // We are on Windows proper.
  316. # include <windows.h> // NOLINT
  317. # undef min
  318. #ifdef _MSC_VER
  319. # include <crtdbg.h> // NOLINT
  320. #endif
  321. # include <io.h> // NOLINT
  322. # include <sys/timeb.h> // NOLINT
  323. # include <sys/types.h> // NOLINT
  324. # include <sys/stat.h> // NOLINT
  325. # if GTEST_OS_WINDOWS_MINGW
  326. # include <sys/time.h> // NOLINT
  327. # endif // GTEST_OS_WINDOWS_MINGW
  328. #else
  329. // cpplint thinks that the header is already included, so we want to
  330. // silence it.
  331. # include <sys/time.h> // NOLINT
  332. # include <unistd.h> // NOLINT
  333. #endif // GTEST_OS_LINUX
  334. #if GTEST_HAS_EXCEPTIONS
  335. # include <stdexcept>
  336. #endif
  337. #if GTEST_CAN_STREAM_RESULTS_
  338. # include <arpa/inet.h> // NOLINT
  339. # include <netdb.h> // NOLINT
  340. # include <sys/socket.h> // NOLINT
  341. # include <sys/types.h> // NOLINT
  342. #endif
  343. // Copyright 2005, Google Inc.
  344. // All rights reserved.
  345. //
  346. // Redistribution and use in source and binary forms, with or without
  347. // modification, are permitted provided that the following conditions are
  348. // met:
  349. //
  350. // * Redistributions of source code must retain the above copyright
  351. // notice, this list of conditions and the following disclaimer.
  352. // * Redistributions in binary form must reproduce the above
  353. // copyright notice, this list of conditions and the following disclaimer
  354. // in the documentation and/or other materials provided with the
  355. // distribution.
  356. // * Neither the name of Google Inc. nor the names of its
  357. // contributors may be used to endorse or promote products derived from
  358. // this software without specific prior written permission.
  359. //
  360. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  361. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  362. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  363. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  364. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  365. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  366. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  367. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  368. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  369. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  370. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  371. // Utility functions and classes used by the Google C++ testing framework.//
  372. // This file contains purely Google Test's internal implementation. Please
  373. // DO NOT #INCLUDE IT IN A USER PROGRAM.
  374. #ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
  375. #define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
  376. #ifndef _WIN32_WCE
  377. # include <errno.h>
  378. #endif // !_WIN32_WCE
  379. #include <stddef.h>
  380. #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
  381. #include <string.h> // For memmove.
  382. #include <algorithm>
  383. #include <cstdint>
  384. #include <memory>
  385. #include <string>
  386. #include <vector>
  387. #if GTEST_CAN_STREAM_RESULTS_
  388. # include <arpa/inet.h> // NOLINT
  389. # include <netdb.h> // NOLINT
  390. #endif
  391. #if GTEST_OS_WINDOWS
  392. # include <windows.h> // NOLINT
  393. #endif // GTEST_OS_WINDOWS
  394. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  395. /* class A needs to have dll-interface to be used by clients of class B */)
  396. namespace testing {
  397. // Declares the flags.
  398. //
  399. // We don't want the users to modify this flag in the code, but want
  400. // Google Test's own unit tests to be able to access it. Therefore we
  401. // declare it here as opposed to in gtest.h.
  402. GTEST_DECLARE_bool_(death_test_use_fork);
  403. namespace internal {
  404. // The value of GetTestTypeId() as seen from within the Google Test
  405. // library. This is solely for testing GetTestTypeId().
  406. GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
  407. // Names of the flags (needed for parsing Google Test flags).
  408. const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
  409. const char kBreakOnFailureFlag[] = "break_on_failure";
  410. const char kCatchExceptionsFlag[] = "catch_exceptions";
  411. const char kColorFlag[] = "color";
  412. const char kFailFast[] = "fail_fast";
  413. const char kFilterFlag[] = "filter";
  414. const char kListTestsFlag[] = "list_tests";
  415. const char kOutputFlag[] = "output";
  416. const char kBriefFlag[] = "brief";
  417. const char kPrintTimeFlag[] = "print_time";
  418. const char kPrintUTF8Flag[] = "print_utf8";
  419. const char kRandomSeedFlag[] = "random_seed";
  420. const char kRepeatFlag[] = "repeat";
  421. const char kShuffleFlag[] = "shuffle";
  422. const char kStackTraceDepthFlag[] = "stack_trace_depth";
  423. const char kStreamResultToFlag[] = "stream_result_to";
  424. const char kThrowOnFailureFlag[] = "throw_on_failure";
  425. const char kFlagfileFlag[] = "flagfile";
  426. // A valid random seed must be in [1, kMaxRandomSeed].
  427. const int kMaxRandomSeed = 99999;
  428. // g_help_flag is true if and only if the --help flag or an equivalent form
  429. // is specified on the command line.
  430. GTEST_API_ extern bool g_help_flag;
  431. // Returns the current time in milliseconds.
  432. GTEST_API_ TimeInMillis GetTimeInMillis();
  433. // Returns true if and only if Google Test should use colors in the output.
  434. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
  435. // Formats the given time in milliseconds as seconds.
  436. GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
  437. // Converts the given time in milliseconds to a date string in the ISO 8601
  438. // format, without the timezone information. N.B.: due to the use the
  439. // non-reentrant localtime() function, this function is not thread safe. Do
  440. // not use it in any code that can be called from multiple threads.
  441. GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
  442. // Parses a string for an Int32 flag, in the form of "--flag=value".
  443. //
  444. // On success, stores the value of the flag in *value, and returns
  445. // true. On failure, returns false without changing *value.
  446. GTEST_API_ bool ParseInt32Flag(
  447. const char* str, const char* flag, int32_t* value);
  448. // Returns a random seed in range [1, kMaxRandomSeed] based on the
  449. // given --gtest_random_seed flag value.
  450. inline int GetRandomSeedFromFlag(int32_t random_seed_flag) {
  451. const unsigned int raw_seed = (random_seed_flag == 0) ?
  452. static_cast<unsigned int>(GetTimeInMillis()) :
  453. static_cast<unsigned int>(random_seed_flag);
  454. // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
  455. // it's easy to type.
  456. const int normalized_seed =
  457. static_cast<int>((raw_seed - 1U) %
  458. static_cast<unsigned int>(kMaxRandomSeed)) + 1;
  459. return normalized_seed;
  460. }
  461. // Returns the first valid random seed after 'seed'. The behavior is
  462. // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
  463. // considered to be 1.
  464. inline int GetNextRandomSeed(int seed) {
  465. GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
  466. << "Invalid random seed " << seed << " - must be in [1, "
  467. << kMaxRandomSeed << "].";
  468. const int next_seed = seed + 1;
  469. return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
  470. }
  471. // This class saves the values of all Google Test flags in its c'tor, and
  472. // restores them in its d'tor.
  473. class GTestFlagSaver {
  474. public:
  475. // The c'tor.
  476. GTestFlagSaver() {
  477. also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
  478. break_on_failure_ = GTEST_FLAG(break_on_failure);
  479. catch_exceptions_ = GTEST_FLAG(catch_exceptions);
  480. color_ = GTEST_FLAG(color);
  481. death_test_style_ = GTEST_FLAG(death_test_style);
  482. death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
  483. fail_fast_ = GTEST_FLAG(fail_fast);
  484. filter_ = GTEST_FLAG(filter);
  485. internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
  486. list_tests_ = GTEST_FLAG(list_tests);
  487. output_ = GTEST_FLAG(output);
  488. brief_ = GTEST_FLAG(brief);
  489. print_time_ = GTEST_FLAG(print_time);
  490. print_utf8_ = GTEST_FLAG(print_utf8);
  491. random_seed_ = GTEST_FLAG(random_seed);
  492. repeat_ = GTEST_FLAG(repeat);
  493. shuffle_ = GTEST_FLAG(shuffle);
  494. stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
  495. stream_result_to_ = GTEST_FLAG(stream_result_to);
  496. throw_on_failure_ = GTEST_FLAG(throw_on_failure);
  497. }
  498. // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
  499. ~GTestFlagSaver() {
  500. GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
  501. GTEST_FLAG(break_on_failure) = break_on_failure_;
  502. GTEST_FLAG(catch_exceptions) = catch_exceptions_;
  503. GTEST_FLAG(color) = color_;
  504. GTEST_FLAG(death_test_style) = death_test_style_;
  505. GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
  506. GTEST_FLAG(filter) = filter_;
  507. GTEST_FLAG(fail_fast) = fail_fast_;
  508. GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
  509. GTEST_FLAG(list_tests) = list_tests_;
  510. GTEST_FLAG(output) = output_;
  511. GTEST_FLAG(brief) = brief_;
  512. GTEST_FLAG(print_time) = print_time_;
  513. GTEST_FLAG(print_utf8) = print_utf8_;
  514. GTEST_FLAG(random_seed) = random_seed_;
  515. GTEST_FLAG(repeat) = repeat_;
  516. GTEST_FLAG(shuffle) = shuffle_;
  517. GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
  518. GTEST_FLAG(stream_result_to) = stream_result_to_;
  519. GTEST_FLAG(throw_on_failure) = throw_on_failure_;
  520. }
  521. private:
  522. // Fields for saving the original values of flags.
  523. bool also_run_disabled_tests_;
  524. bool break_on_failure_;
  525. bool catch_exceptions_;
  526. std::string color_;
  527. std::string death_test_style_;
  528. bool death_test_use_fork_;
  529. bool fail_fast_;
  530. std::string filter_;
  531. std::string internal_run_death_test_;
  532. bool list_tests_;
  533. std::string output_;
  534. bool brief_;
  535. bool print_time_;
  536. bool print_utf8_;
  537. int32_t random_seed_;
  538. int32_t repeat_;
  539. bool shuffle_;
  540. int32_t stack_trace_depth_;
  541. std::string stream_result_to_;
  542. bool throw_on_failure_;
  543. } GTEST_ATTRIBUTE_UNUSED_;
  544. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  545. // code_point parameter is of type UInt32 because wchar_t may not be
  546. // wide enough to contain a code point.
  547. // If the code_point is not a valid Unicode code point
  548. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  549. // to "(Invalid Unicode 0xXXXXXXXX)".
  550. GTEST_API_ std::string CodePointToUtf8(uint32_t code_point);
  551. // Converts a wide string to a narrow string in UTF-8 encoding.
  552. // The wide string is assumed to have the following encoding:
  553. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
  554. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  555. // Parameter str points to a null-terminated wide string.
  556. // Parameter num_chars may additionally limit the number
  557. // of wchar_t characters processed. -1 is used when the entire string
  558. // should be processed.
  559. // If the string contains code points that are not valid Unicode code points
  560. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  561. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  562. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  563. // will be encoded as individual Unicode characters from Basic Normal Plane.
  564. GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
  565. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  566. // if the variable is present. If a file already exists at this location, this
  567. // function will write over it. If the variable is present, but the file cannot
  568. // be created, prints an error and exits.
  569. void WriteToShardStatusFileIfNeeded();
  570. // Checks whether sharding is enabled by examining the relevant
  571. // environment variable values. If the variables are present,
  572. // but inconsistent (e.g., shard_index >= total_shards), prints
  573. // an error and exits. If in_subprocess_for_death_test, sharding is
  574. // disabled because it must only be applied to the original test
  575. // process. Otherwise, we could filter out death tests we intended to execute.
  576. GTEST_API_ bool ShouldShard(const char* total_shards_str,
  577. const char* shard_index_str,
  578. bool in_subprocess_for_death_test);
  579. // Parses the environment variable var as a 32-bit integer. If it is unset,
  580. // returns default_val. If it is not a 32-bit integer, prints an error and
  581. // and aborts.
  582. GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);
  583. // Given the total number of shards, the shard index, and the test id,
  584. // returns true if and only if the test should be run on this shard. The test id
  585. // is some arbitrary but unique non-negative integer assigned to each test
  586. // method. Assumes that 0 <= shard_index < total_shards.
  587. GTEST_API_ bool ShouldRunTestOnShard(
  588. int total_shards, int shard_index, int test_id);
  589. // STL container utilities.
  590. // Returns the number of elements in the given container that satisfy
  591. // the given predicate.
  592. template <class Container, typename Predicate>
  593. inline int CountIf(const Container& c, Predicate predicate) {
  594. // Implemented as an explicit loop since std::count_if() in libCstd on
  595. // Solaris has a non-standard signature.
  596. int count = 0;
  597. for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
  598. if (predicate(*it))
  599. ++count;
  600. }
  601. return count;
  602. }
  603. // Applies a function/functor to each element in the container.
  604. template <class Container, typename Functor>
  605. void ForEach(const Container& c, Functor functor) {
  606. std::for_each(c.begin(), c.end(), functor);
  607. }
  608. // Returns the i-th element of the vector, or default_value if i is not
  609. // in range [0, v.size()).
  610. template <typename E>
  611. inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
  612. return (i < 0 || i >= static_cast<int>(v.size())) ? default_value
  613. : v[static_cast<size_t>(i)];
  614. }
  615. // Performs an in-place shuffle of a range of the vector's elements.
  616. // 'begin' and 'end' are element indices as an STL-style range;
  617. // i.e. [begin, end) are shuffled, where 'end' == size() means to
  618. // shuffle to the end of the vector.
  619. template <typename E>
  620. void ShuffleRange(internal::Random* random, int begin, int end,
  621. std::vector<E>* v) {
  622. const int size = static_cast<int>(v->size());
  623. GTEST_CHECK_(0 <= begin && begin <= size)
  624. << "Invalid shuffle range start " << begin << ": must be in range [0, "
  625. << size << "].";
  626. GTEST_CHECK_(begin <= end && end <= size)
  627. << "Invalid shuffle range finish " << end << ": must be in range ["
  628. << begin << ", " << size << "].";
  629. // Fisher-Yates shuffle, from
  630. // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  631. for (int range_width = end - begin; range_width >= 2; range_width--) {
  632. const int last_in_range = begin + range_width - 1;
  633. const int selected =
  634. begin +
  635. static_cast<int>(random->Generate(static_cast<uint32_t>(range_width)));
  636. std::swap((*v)[static_cast<size_t>(selected)],
  637. (*v)[static_cast<size_t>(last_in_range)]);
  638. }
  639. }
  640. // Performs an in-place shuffle of the vector's elements.
  641. template <typename E>
  642. inline void Shuffle(internal::Random* random, std::vector<E>* v) {
  643. ShuffleRange(random, 0, static_cast<int>(v->size()), v);
  644. }
  645. // A function for deleting an object. Handy for being used as a
  646. // functor.
  647. template <typename T>
  648. static void Delete(T* x) {
  649. delete x;
  650. }
  651. // A predicate that checks the key of a TestProperty against a known key.
  652. //
  653. // TestPropertyKeyIs is copyable.
  654. class TestPropertyKeyIs {
  655. public:
  656. // Constructor.
  657. //
  658. // TestPropertyKeyIs has NO default constructor.
  659. explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
  660. // Returns true if and only if the test name of test property matches on key_.
  661. bool operator()(const TestProperty& test_property) const {
  662. return test_property.key() == key_;
  663. }
  664. private:
  665. std::string key_;
  666. };
  667. // Class UnitTestOptions.
  668. //
  669. // This class contains functions for processing options the user
  670. // specifies when running the tests. It has only static members.
  671. //
  672. // In most cases, the user can specify an option using either an
  673. // environment variable or a command line flag. E.g. you can set the
  674. // test filter using either GTEST_FILTER or --gtest_filter. If both
  675. // the variable and the flag are present, the latter overrides the
  676. // former.
  677. class GTEST_API_ UnitTestOptions {
  678. public:
  679. // Functions for processing the gtest_output flag.
  680. // Returns the output format, or "" for normal printed output.
  681. static std::string GetOutputFormat();
  682. // Returns the absolute path of the requested output file, or the
  683. // default (test_detail.xml in the original working directory) if
  684. // none was explicitly specified.
  685. static std::string GetAbsolutePathToOutputFile();
  686. // Functions for processing the gtest_filter flag.
  687. // Returns true if and only if the user-specified filter matches the test
  688. // suite name and the test name.
  689. static bool FilterMatchesTest(const std::string& test_suite_name,
  690. const std::string& test_name);
  691. #if GTEST_OS_WINDOWS
  692. // Function for supporting the gtest_catch_exception flag.
  693. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  694. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  695. // This function is useful as an __except condition.
  696. static int GTestShouldProcessSEH(DWORD exception_code);
  697. #endif // GTEST_OS_WINDOWS
  698. // Returns true if "name" matches the ':' separated list of glob-style
  699. // filters in "filter".
  700. static bool MatchesFilter(const std::string& name, const char* filter);
  701. };
  702. // Returns the current application's name, removing directory path if that
  703. // is present. Used by UnitTestOptions::GetOutputFile.
  704. GTEST_API_ FilePath GetCurrentExecutableName();
  705. // The role interface for getting the OS stack trace as a string.
  706. class OsStackTraceGetterInterface {
  707. public:
  708. OsStackTraceGetterInterface() {}
  709. virtual ~OsStackTraceGetterInterface() {}
  710. // Returns the current OS stack trace as an std::string. Parameters:
  711. //
  712. // max_depth - the maximum number of stack frames to be included
  713. // in the trace.
  714. // skip_count - the number of top frames to be skipped; doesn't count
  715. // against max_depth.
  716. virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
  717. // UponLeavingGTest() should be called immediately before Google Test calls
  718. // user code. It saves some information about the current stack that
  719. // CurrentStackTrace() will use to find and hide Google Test stack frames.
  720. virtual void UponLeavingGTest() = 0;
  721. // This string is inserted in place of stack frames that are part of
  722. // Google Test's implementation.
  723. static const char* const kElidedFramesMarker;
  724. private:
  725. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
  726. };
  727. // A working implementation of the OsStackTraceGetterInterface interface.
  728. class OsStackTraceGetter : public OsStackTraceGetterInterface {
  729. public:
  730. OsStackTraceGetter() {}
  731. std::string CurrentStackTrace(int max_depth, int skip_count) override;
  732. void UponLeavingGTest() override;
  733. private:
  734. #if GTEST_HAS_ABSL
  735. Mutex mutex_; // Protects all internal state.
  736. // We save the stack frame below the frame that calls user code.
  737. // We do this because the address of the frame immediately below
  738. // the user code changes between the call to UponLeavingGTest()
  739. // and any calls to the stack trace code from within the user code.
  740. void* caller_frame_ = nullptr;
  741. #endif // GTEST_HAS_ABSL
  742. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
  743. };
  744. // Information about a Google Test trace point.
  745. struct TraceInfo {
  746. const char* file;
  747. int line;
  748. std::string message;
  749. };
  750. // This is the default global test part result reporter used in UnitTestImpl.
  751. // This class should only be used by UnitTestImpl.
  752. class DefaultGlobalTestPartResultReporter
  753. : public TestPartResultReporterInterface {
  754. public:
  755. explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
  756. // Implements the TestPartResultReporterInterface. Reports the test part
  757. // result in the current test.
  758. void ReportTestPartResult(const TestPartResult& result) override;
  759. private:
  760. UnitTestImpl* const unit_test_;
  761. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
  762. };
  763. // This is the default per thread test part result reporter used in
  764. // UnitTestImpl. This class should only be used by UnitTestImpl.
  765. class DefaultPerThreadTestPartResultReporter
  766. : public TestPartResultReporterInterface {
  767. public:
  768. explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
  769. // Implements the TestPartResultReporterInterface. The implementation just
  770. // delegates to the current global test part result reporter of *unit_test_.
  771. void ReportTestPartResult(const TestPartResult& result) override;
  772. private:
  773. UnitTestImpl* const unit_test_;
  774. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
  775. };
  776. // The private implementation of the UnitTest class. We don't protect
  777. // the methods under a mutex, as this class is not accessible by a
  778. // user and the UnitTest class that delegates work to this class does
  779. // proper locking.
  780. class GTEST_API_ UnitTestImpl {
  781. public:
  782. explicit UnitTestImpl(UnitTest* parent);
  783. virtual ~UnitTestImpl();
  784. // There are two different ways to register your own TestPartResultReporter.
  785. // You can register your own repoter to listen either only for test results
  786. // from the current thread or for results from all threads.
  787. // By default, each per-thread test result repoter just passes a new
  788. // TestPartResult to the global test result reporter, which registers the
  789. // test part result for the currently running test.
  790. // Returns the global test part result reporter.
  791. TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
  792. // Sets the global test part result reporter.
  793. void SetGlobalTestPartResultReporter(
  794. TestPartResultReporterInterface* reporter);
  795. // Returns the test part result reporter for the current thread.
  796. TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
  797. // Sets the test part result reporter for the current thread.
  798. void SetTestPartResultReporterForCurrentThread(
  799. TestPartResultReporterInterface* reporter);
  800. // Gets the number of successful test suites.
  801. int successful_test_suite_count() const;
  802. // Gets the number of failed test suites.
  803. int failed_test_suite_count() const;
  804. // Gets the number of all test suites.
  805. int total_test_suite_count() const;
  806. // Gets the number of all test suites that contain at least one test
  807. // that should run.
  808. int test_suite_to_run_count() const;
  809. // Gets the number of successful tests.
  810. int successful_test_count() const;
  811. // Gets the number of skipped tests.
  812. int skipped_test_count() const;
  813. // Gets the number of failed tests.
  814. int failed_test_count() const;
  815. // Gets the number of disabled tests that will be reported in the XML report.
  816. int reportable_disabled_test_count() const;
  817. // Gets the number of disabled tests.
  818. int disabled_test_count() const;
  819. // Gets the number of tests to be printed in the XML report.
  820. int reportable_test_count() const;
  821. // Gets the number of all tests.
  822. int total_test_count() const;
  823. // Gets the number of tests that should run.
  824. int test_to_run_count() const;
  825. // Gets the time of the test program start, in ms from the start of the
  826. // UNIX epoch.
  827. TimeInMillis start_timestamp() const { return start_timestamp_; }
  828. // Gets the elapsed time, in milliseconds.
  829. TimeInMillis elapsed_time() const { return elapsed_time_; }
  830. // Returns true if and only if the unit test passed (i.e. all test suites
  831. // passed).
  832. bool Passed() const { return !Failed(); }
  833. // Returns true if and only if the unit test failed (i.e. some test suite
  834. // failed or something outside of all tests failed).
  835. bool Failed() const {
  836. return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();
  837. }
  838. // Gets the i-th test suite among all the test suites. i can range from 0 to
  839. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  840. const TestSuite* GetTestSuite(int i) const {
  841. const int index = GetElementOr(test_suite_indices_, i, -1);
  842. return index < 0 ? nullptr : test_suites_[static_cast<size_t>(i)];
  843. }
  844. // Legacy API is deprecated but still available
  845. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  846. const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }
  847. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  848. // Gets the i-th test suite among all the test suites. i can range from 0 to
  849. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  850. TestSuite* GetMutableSuiteCase(int i) {
  851. const int index = GetElementOr(test_suite_indices_, i, -1);
  852. return index < 0 ? nullptr : test_suites_[static_cast<size_t>(index)];
  853. }
  854. // Provides access to the event listener list.
  855. TestEventListeners* listeners() { return &listeners_; }
  856. // Returns the TestResult for the test that's currently running, or
  857. // the TestResult for the ad hoc test if no test is running.
  858. TestResult* current_test_result();
  859. // Returns the TestResult for the ad hoc test.
  860. const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
  861. // Sets the OS stack trace getter.
  862. //
  863. // Does nothing if the input and the current OS stack trace getter
  864. // are the same; otherwise, deletes the old getter and makes the
  865. // input the current getter.
  866. void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
  867. // Returns the current OS stack trace getter if it is not NULL;
  868. // otherwise, creates an OsStackTraceGetter, makes it the current
  869. // getter, and returns it.
  870. OsStackTraceGetterInterface* os_stack_trace_getter();
  871. // Returns the current OS stack trace as an std::string.
  872. //
  873. // The maximum number of stack frames to be included is specified by
  874. // the gtest_stack_trace_depth flag. The skip_count parameter
  875. // specifies the number of top frames to be skipped, which doesn't
  876. // count against the number of frames to be included.
  877. //
  878. // For example, if Foo() calls Bar(), which in turn calls
  879. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  880. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  881. std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
  882. // Finds and returns a TestSuite with the given name. If one doesn't
  883. // exist, creates one and returns it.
  884. //
  885. // Arguments:
  886. //
  887. // test_suite_name: name of the test suite
  888. // type_param: the name of the test's type parameter, or NULL if
  889. // this is not a typed or a type-parameterized test.
  890. // set_up_tc: pointer to the function that sets up the test suite
  891. // tear_down_tc: pointer to the function that tears down the test suite
  892. TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,
  893. internal::SetUpTestSuiteFunc set_up_tc,
  894. internal::TearDownTestSuiteFunc tear_down_tc);
  895. // Legacy API is deprecated but still available
  896. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  897. TestCase* GetTestCase(const char* test_case_name, const char* type_param,
  898. internal::SetUpTestSuiteFunc set_up_tc,
  899. internal::TearDownTestSuiteFunc tear_down_tc) {
  900. return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);
  901. }
  902. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  903. // Adds a TestInfo to the unit test.
  904. //
  905. // Arguments:
  906. //
  907. // set_up_tc: pointer to the function that sets up the test suite
  908. // tear_down_tc: pointer to the function that tears down the test suite
  909. // test_info: the TestInfo object
  910. void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
  911. internal::TearDownTestSuiteFunc tear_down_tc,
  912. TestInfo* test_info) {
  913. #if GTEST_HAS_DEATH_TEST
  914. // In order to support thread-safe death tests, we need to
  915. // remember the original working directory when the test program
  916. // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
  917. // the user may have changed the current directory before calling
  918. // RUN_ALL_TESTS(). Therefore we capture the current directory in
  919. // AddTestInfo(), which is called to register a TEST or TEST_F
  920. // before main() is reached.
  921. if (original_working_dir_.IsEmpty()) {
  922. original_working_dir_.Set(FilePath::GetCurrentDir());
  923. GTEST_CHECK_(!original_working_dir_.IsEmpty())
  924. << "Failed to get the current working directory.";
  925. }
  926. #endif // GTEST_HAS_DEATH_TEST
  927. GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
  928. set_up_tc, tear_down_tc)
  929. ->AddTestInfo(test_info);
  930. }
  931. // Returns ParameterizedTestSuiteRegistry object used to keep track of
  932. // value-parameterized tests and instantiate and register them.
  933. internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {
  934. return parameterized_test_registry_;
  935. }
  936. std::set<std::string>* ignored_parameterized_test_suites() {
  937. return &ignored_parameterized_test_suites_;
  938. }
  939. // Returns TypeParameterizedTestSuiteRegistry object used to keep track of
  940. // type-parameterized tests and instantiations of them.
  941. internal::TypeParameterizedTestSuiteRegistry&
  942. type_parameterized_test_registry() {
  943. return type_parameterized_test_registry_;
  944. }
  945. // Sets the TestSuite object for the test that's currently running.
  946. void set_current_test_suite(TestSuite* a_current_test_suite) {
  947. current_test_suite_ = a_current_test_suite;
  948. }
  949. // Sets the TestInfo object for the test that's currently running. If
  950. // current_test_info is NULL, the assertion results will be stored in
  951. // ad_hoc_test_result_.
  952. void set_current_test_info(TestInfo* a_current_test_info) {
  953. current_test_info_ = a_current_test_info;
  954. }
  955. // Registers all parameterized tests defined using TEST_P and
  956. // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter
  957. // combination. This method can be called more then once; it has guards
  958. // protecting from registering the tests more then once. If
  959. // value-parameterized tests are disabled, RegisterParameterizedTests is
  960. // present but does nothing.
  961. void RegisterParameterizedTests();
  962. // Runs all tests in this UnitTest object, prints the result, and
  963. // returns true if all tests are successful. If any exception is
  964. // thrown during a test, this test is considered to be failed, but
  965. // the rest of the tests will still be run.
  966. bool RunAllTests();
  967. // Clears the results of all tests, except the ad hoc tests.
  968. void ClearNonAdHocTestResult() {
  969. ForEach(test_suites_, TestSuite::ClearTestSuiteResult);
  970. }
  971. // Clears the results of ad-hoc test assertions.
  972. void ClearAdHocTestResult() {
  973. ad_hoc_test_result_.Clear();
  974. }
  975. // Adds a TestProperty to the current TestResult object when invoked in a
  976. // context of a test or a test suite, or to the global property set. If the
  977. // result already contains a property with the same key, the value will be
  978. // updated.
  979. void RecordProperty(const TestProperty& test_property);
  980. enum ReactionToSharding {
  981. HONOR_SHARDING_PROTOCOL,
  982. IGNORE_SHARDING_PROTOCOL
  983. };
  984. // Matches the full name of each test against the user-specified
  985. // filter to decide whether the test should run, then records the
  986. // result in each TestSuite and TestInfo object.
  987. // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
  988. // based on sharding variables in the environment.
  989. // Returns the number of tests that should run.
  990. int FilterTests(ReactionToSharding shard_tests);
  991. // Prints the names of the tests matching the user-specified filter flag.
  992. void ListTestsMatchingFilter();
  993. const TestSuite* current_test_suite() const { return current_test_suite_; }
  994. TestInfo* current_test_info() { return current_test_info_; }
  995. const TestInfo* current_test_info() const { return current_test_info_; }
  996. // Returns the vector of environments that need to be set-up/torn-down
  997. // before/after the tests are run.
  998. std::vector<Environment*>& environments() { return environments_; }
  999. // Getters for the per-thread Google Test trace stack.
  1000. std::vector<TraceInfo>& gtest_trace_stack() {
  1001. return *(gtest_trace_stack_.pointer());
  1002. }
  1003. const std::vector<TraceInfo>& gtest_trace_stack() const {
  1004. return gtest_trace_stack_.get();
  1005. }
  1006. #if GTEST_HAS_DEATH_TEST
  1007. void InitDeathTestSubprocessControlInfo() {
  1008. internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
  1009. }
  1010. // Returns a pointer to the parsed --gtest_internal_run_death_test
  1011. // flag, or NULL if that flag was not specified.
  1012. // This information is useful only in a death test child process.
  1013. // Must not be called before a call to InitGoogleTest.
  1014. const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
  1015. return internal_run_death_test_flag_.get();
  1016. }
  1017. // Returns a pointer to the current death test factory.
  1018. internal::DeathTestFactory* death_test_factory() {
  1019. return death_test_factory_.get();
  1020. }
  1021. void SuppressTestEventsIfInSubprocess();
  1022. friend class ReplaceDeathTestFactory;
  1023. #endif // GTEST_HAS_DEATH_TEST
  1024. // Initializes the event listener performing XML output as specified by
  1025. // UnitTestOptions. Must not be called before InitGoogleTest.
  1026. void ConfigureXmlOutput();
  1027. #if GTEST_CAN_STREAM_RESULTS_
  1028. // Initializes the event listener for streaming test results to a socket.
  1029. // Must not be called before InitGoogleTest.
  1030. void ConfigureStreamingOutput();
  1031. #endif
  1032. // Performs initialization dependent upon flag values obtained in
  1033. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  1034. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  1035. // this function is also called from RunAllTests. Since this function can be
  1036. // called more than once, it has to be idempotent.
  1037. void PostFlagParsingInit();
  1038. // Gets the random seed used at the start of the current test iteration.
  1039. int random_seed() const { return random_seed_; }
  1040. // Gets the random number generator.
  1041. internal::Random* random() { return &random_; }
  1042. // Shuffles all test suites, and the tests within each test suite,
  1043. // making sure that death tests are still run first.
  1044. void ShuffleTests();
  1045. // Restores the test suites and tests to their order before the first shuffle.
  1046. void UnshuffleTests();
  1047. // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
  1048. // UnitTest::Run() starts.
  1049. bool catch_exceptions() const { return catch_exceptions_; }
  1050. private:
  1051. friend class ::testing::UnitTest;
  1052. // Used by UnitTest::Run() to capture the state of
  1053. // GTEST_FLAG(catch_exceptions) at the moment it starts.
  1054. void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
  1055. // The UnitTest object that owns this implementation object.
  1056. UnitTest* const parent_;
  1057. // The working directory when the first TEST() or TEST_F() was
  1058. // executed.
  1059. internal::FilePath original_working_dir_;
  1060. // The default test part result reporters.
  1061. DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
  1062. DefaultPerThreadTestPartResultReporter
  1063. default_per_thread_test_part_result_reporter_;
  1064. // Points to (but doesn't own) the global test part result reporter.
  1065. TestPartResultReporterInterface* global_test_part_result_repoter_;
  1066. // Protects read and write access to global_test_part_result_reporter_.
  1067. internal::Mutex global_test_part_result_reporter_mutex_;
  1068. // Points to (but doesn't own) the per-thread test part result reporter.
  1069. internal::ThreadLocal<TestPartResultReporterInterface*>
  1070. per_thread_test_part_result_reporter_;
  1071. // The vector of environments that need to be set-up/torn-down
  1072. // before/after the tests are run.
  1073. std::vector<Environment*> environments_;
  1074. // The vector of TestSuites in their original order. It owns the
  1075. // elements in the vector.
  1076. std::vector<TestSuite*> test_suites_;
  1077. // Provides a level of indirection for the test suite list to allow
  1078. // easy shuffling and restoring the test suite order. The i-th
  1079. // element of this vector is the index of the i-th test suite in the
  1080. // shuffled order.
  1081. std::vector<int> test_suite_indices_;
  1082. // ParameterizedTestRegistry object used to register value-parameterized
  1083. // tests.
  1084. internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
  1085. internal::TypeParameterizedTestSuiteRegistry
  1086. type_parameterized_test_registry_;
  1087. // The set holding the name of parameterized
  1088. // test suites that may go uninstantiated.
  1089. std::set<std::string> ignored_parameterized_test_suites_;
  1090. // Indicates whether RegisterParameterizedTests() has been called already.
  1091. bool parameterized_tests_registered_;
  1092. // Index of the last death test suite registered. Initially -1.
  1093. int last_death_test_suite_;
  1094. // This points to the TestSuite for the currently running test. It
  1095. // changes as Google Test goes through one test suite after another.
  1096. // When no test is running, this is set to NULL and Google Test
  1097. // stores assertion results in ad_hoc_test_result_. Initially NULL.
  1098. TestSuite* current_test_suite_;
  1099. // This points to the TestInfo for the currently running test. It
  1100. // changes as Google Test goes through one test after another. When
  1101. // no test is running, this is set to NULL and Google Test stores
  1102. // assertion results in ad_hoc_test_result_. Initially NULL.
  1103. TestInfo* current_test_info_;
  1104. // Normally, a user only writes assertions inside a TEST or TEST_F,
  1105. // or inside a function called by a TEST or TEST_F. Since Google
  1106. // Test keeps track of which test is current running, it can
  1107. // associate such an assertion with the test it belongs to.
  1108. //
  1109. // If an assertion is encountered when no TEST or TEST_F is running,
  1110. // Google Test attributes the assertion result to an imaginary "ad hoc"
  1111. // test, and records the result in ad_hoc_test_result_.
  1112. TestResult ad_hoc_test_result_;
  1113. // The list of event listeners that can be used to track events inside
  1114. // Google Test.
  1115. TestEventListeners listeners_;
  1116. // The OS stack trace getter. Will be deleted when the UnitTest
  1117. // object is destructed. By default, an OsStackTraceGetter is used,
  1118. // but the user can set this field to use a custom getter if that is
  1119. // desired.
  1120. OsStackTraceGetterInterface* os_stack_trace_getter_;
  1121. // True if and only if PostFlagParsingInit() has been called.
  1122. bool post_flag_parse_init_performed_;
  1123. // The random number seed used at the beginning of the test run.
  1124. int random_seed_;
  1125. // Our random number generator.
  1126. internal::Random random_;
  1127. // The time of the test program start, in ms from the start of the
  1128. // UNIX epoch.
  1129. TimeInMillis start_timestamp_;
  1130. // How long the test took to run, in milliseconds.
  1131. TimeInMillis elapsed_time_;
  1132. #if GTEST_HAS_DEATH_TEST
  1133. // The decomposed components of the gtest_internal_run_death_test flag,
  1134. // parsed when RUN_ALL_TESTS is called.
  1135. std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
  1136. std::unique_ptr<internal::DeathTestFactory> death_test_factory_;
  1137. #endif // GTEST_HAS_DEATH_TEST
  1138. // A per-thread stack of traces created by the SCOPED_TRACE() macro.
  1139. internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
  1140. // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
  1141. // starts.
  1142. bool catch_exceptions_;
  1143. GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
  1144. }; // class UnitTestImpl
  1145. // Convenience function for accessing the global UnitTest
  1146. // implementation object.
  1147. inline UnitTestImpl* GetUnitTestImpl() {
  1148. return UnitTest::GetInstance()->impl();
  1149. }
  1150. #if GTEST_USES_SIMPLE_RE
  1151. // Internal helper functions for implementing the simple regular
  1152. // expression matcher.
  1153. GTEST_API_ bool IsInSet(char ch, const char* str);
  1154. GTEST_API_ bool IsAsciiDigit(char ch);
  1155. GTEST_API_ bool IsAsciiPunct(char ch);
  1156. GTEST_API_ bool IsRepeat(char ch);
  1157. GTEST_API_ bool IsAsciiWhiteSpace(char ch);
  1158. GTEST_API_ bool IsAsciiWordChar(char ch);
  1159. GTEST_API_ bool IsValidEscape(char ch);
  1160. GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
  1161. GTEST_API_ bool ValidateRegex(const char* regex);
  1162. GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
  1163. GTEST_API_ bool MatchRepetitionAndRegexAtHead(
  1164. bool escaped, char ch, char repeat, const char* regex, const char* str);
  1165. GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
  1166. #endif // GTEST_USES_SIMPLE_RE
  1167. // Parses the command line for Google Test flags, without initializing
  1168. // other parts of Google Test.
  1169. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
  1170. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
  1171. #if GTEST_HAS_DEATH_TEST
  1172. // Returns the message describing the last system error, regardless of the
  1173. // platform.
  1174. GTEST_API_ std::string GetLastErrnoDescription();
  1175. // Attempts to parse a string into a positive integer pointed to by the
  1176. // number parameter. Returns true if that is possible.
  1177. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
  1178. // it here.
  1179. template <typename Integer>
  1180. bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
  1181. // Fail fast if the given string does not begin with a digit;
  1182. // this bypasses strtoXXX's "optional leading whitespace and plus
  1183. // or minus sign" semantics, which are undesirable here.
  1184. if (str.empty() || !IsDigit(str[0])) {
  1185. return false;
  1186. }
  1187. errno = 0;
  1188. char* end;
  1189. // BiggestConvertible is the largest integer type that system-provided
  1190. // string-to-number conversion routines can return.
  1191. using BiggestConvertible = unsigned long long; // NOLINT
  1192. const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); // NOLINT
  1193. const bool parse_success = *end == '\0' && errno == 0;
  1194. GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
  1195. const Integer result = static_cast<Integer>(parsed);
  1196. if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
  1197. *number = result;
  1198. return true;
  1199. }
  1200. return false;
  1201. }
  1202. #endif // GTEST_HAS_DEATH_TEST
  1203. // TestResult contains some private methods that should be hidden from
  1204. // Google Test user but are required for testing. This class allow our tests
  1205. // to access them.
  1206. //
  1207. // This class is supplied only for the purpose of testing Google Test's own
  1208. // constructs. Do not use it in user tests, either directly or indirectly.
  1209. class TestResultAccessor {
  1210. public:
  1211. static void RecordProperty(TestResult* test_result,
  1212. const std::string& xml_element,
  1213. const TestProperty& property) {
  1214. test_result->RecordProperty(xml_element, property);
  1215. }
  1216. static void ClearTestPartResults(TestResult* test_result) {
  1217. test_result->ClearTestPartResults();
  1218. }
  1219. static const std::vector<testing::TestPartResult>& test_part_results(
  1220. const TestResult& test_result) {
  1221. return test_result.test_part_results();
  1222. }
  1223. };
  1224. #if GTEST_CAN_STREAM_RESULTS_
  1225. // Streams test results to the given port on the given host machine.
  1226. class StreamingListener : public EmptyTestEventListener {
  1227. public:
  1228. // Abstract base class for writing strings to a socket.
  1229. class AbstractSocketWriter {
  1230. public:
  1231. virtual ~AbstractSocketWriter() {}
  1232. // Sends a string to the socket.
  1233. virtual void Send(const std::string& message) = 0;
  1234. // Closes the socket.
  1235. virtual void CloseConnection() {}
  1236. // Sends a string and a newline to the socket.
  1237. void SendLn(const std::string& message) { Send(message + "\n"); }
  1238. };
  1239. // Concrete class for actually writing strings to a socket.
  1240. class SocketWriter : public AbstractSocketWriter {
  1241. public:
  1242. SocketWriter(const std::string& host, const std::string& port)
  1243. : sockfd_(-1), host_name_(host), port_num_(port) {
  1244. MakeConnection();
  1245. }
  1246. ~SocketWriter() override {
  1247. if (sockfd_ != -1)
  1248. CloseConnection();
  1249. }
  1250. // Sends a string to the socket.
  1251. void Send(const std::string& message) override {
  1252. GTEST_CHECK_(sockfd_ != -1)
  1253. << "Send() can be called only when there is a connection.";
  1254. const auto len = static_cast<size_t>(message.length());
  1255. if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {
  1256. GTEST_LOG_(WARNING)
  1257. << "stream_result_to: failed to stream to "
  1258. << host_name_ << ":" << port_num_;
  1259. }
  1260. }
  1261. private:
  1262. // Creates a client socket and connects to the server.
  1263. void MakeConnection();
  1264. // Closes the socket.
  1265. void CloseConnection() override {
  1266. GTEST_CHECK_(sockfd_ != -1)
  1267. << "CloseConnection() can be called only when there is a connection.";
  1268. close(sockfd_);
  1269. sockfd_ = -1;
  1270. }
  1271. int sockfd_; // socket file descriptor
  1272. const std::string host_name_;
  1273. const std::string port_num_;
  1274. GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
  1275. }; // class SocketWriter
  1276. // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
  1277. static std::string UrlEncode(const char* str);
  1278. StreamingListener(const std::string& host, const std::string& port)
  1279. : socket_writer_(new SocketWriter(host, port)) {
  1280. Start();
  1281. }
  1282. explicit StreamingListener(AbstractSocketWriter* socket_writer)
  1283. : socket_writer_(socket_writer) { Start(); }
  1284. void OnTestProgramStart(const UnitTest& /* unit_test */) override {
  1285. SendLn("event=TestProgramStart");
  1286. }
  1287. void OnTestProgramEnd(const UnitTest& unit_test) override {
  1288. // Note that Google Test current only report elapsed time for each
  1289. // test iteration, not for the entire test program.
  1290. SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
  1291. // Notify the streaming server to stop.
  1292. socket_writer_->CloseConnection();
  1293. }
  1294. void OnTestIterationStart(const UnitTest& /* unit_test */,
  1295. int iteration) override {
  1296. SendLn("event=TestIterationStart&iteration=" +
  1297. StreamableToString(iteration));
  1298. }
  1299. void OnTestIterationEnd(const UnitTest& unit_test,
  1300. int /* iteration */) override {
  1301. SendLn("event=TestIterationEnd&passed=" +
  1302. FormatBool(unit_test.Passed()) + "&elapsed_time=" +
  1303. StreamableToString(unit_test.elapsed_time()) + "ms");
  1304. }
  1305. // Note that "event=TestCaseStart" is a wire format and has to remain
  1306. // "case" for compatibility
  1307. void OnTestCaseStart(const TestCase& test_case) override {
  1308. SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
  1309. }
  1310. // Note that "event=TestCaseEnd" is a wire format and has to remain
  1311. // "case" for compatibility
  1312. void OnTestCaseEnd(const TestCase& test_case) override {
  1313. SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
  1314. "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
  1315. "ms");
  1316. }
  1317. void OnTestStart(const TestInfo& test_info) override {
  1318. SendLn(std::string("event=TestStart&name=") + test_info.name());
  1319. }
  1320. void OnTestEnd(const TestInfo& test_info) override {
  1321. SendLn("event=TestEnd&passed=" +
  1322. FormatBool((test_info.result())->Passed()) +
  1323. "&elapsed_time=" +
  1324. StreamableToString((test_info.result())->elapsed_time()) + "ms");
  1325. }
  1326. void OnTestPartResult(const TestPartResult& test_part_result) override {
  1327. const char* file_name = test_part_result.file_name();
  1328. if (file_name == nullptr) file_name = "";
  1329. SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
  1330. "&line=" + StreamableToString(test_part_result.line_number()) +
  1331. "&message=" + UrlEncode(test_part_result.message()));
  1332. }
  1333. private:
  1334. // Sends the given message and a newline to the socket.
  1335. void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
  1336. // Called at the start of streaming to notify the receiver what
  1337. // protocol we are using.
  1338. void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
  1339. std::string FormatBool(bool value) { return value ? "1" : "0"; }
  1340. const std::unique_ptr<AbstractSocketWriter> socket_writer_;
  1341. GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
  1342. }; // class StreamingListener
  1343. #endif // GTEST_CAN_STREAM_RESULTS_
  1344. } // namespace internal
  1345. } // namespace testing
  1346. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  1347. #endif // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
  1348. #if GTEST_OS_WINDOWS
  1349. # define vsnprintf _vsnprintf
  1350. #endif // GTEST_OS_WINDOWS
  1351. #if GTEST_OS_MAC
  1352. #ifndef GTEST_OS_IOS
  1353. #include <crt_externs.h>
  1354. #endif
  1355. #endif
  1356. #if GTEST_HAS_ABSL
  1357. #include "absl/debugging/failure_signal_handler.h"
  1358. #include "absl/debugging/stacktrace.h"
  1359. #include "absl/debugging/symbolize.h"
  1360. #include "absl/strings/str_cat.h"
  1361. #endif // GTEST_HAS_ABSL
  1362. namespace testing {
  1363. using internal::CountIf;
  1364. using internal::ForEach;
  1365. using internal::GetElementOr;
  1366. using internal::Shuffle;
  1367. // Constants.
  1368. // A test whose test suite name or test name matches this filter is
  1369. // disabled and not run.
  1370. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
  1371. // A test suite whose name matches this filter is considered a death
  1372. // test suite and will be run before test suites whose name doesn't
  1373. // match this filter.
  1374. static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
  1375. // A test filter that matches everything.
  1376. static const char kUniversalFilter[] = "*";
  1377. // The default output format.
  1378. static const char kDefaultOutputFormat[] = "xml";
  1379. // The default output file.
  1380. static const char kDefaultOutputFile[] = "test_detail";
  1381. // The environment variable name for the test shard index.
  1382. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
  1383. // The environment variable name for the total number of test shards.
  1384. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
  1385. // The environment variable name for the test shard status file.
  1386. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
  1387. namespace internal {
  1388. // The text used in failure messages to indicate the start of the
  1389. // stack trace.
  1390. const char kStackTraceMarker[] = "\nStack trace:\n";
  1391. // g_help_flag is true if and only if the --help flag or an equivalent form
  1392. // is specified on the command line.
  1393. bool g_help_flag = false;
  1394. // Utilty function to Open File for Writing
  1395. static FILE* OpenFileForWriting(const std::string& output_file) {
  1396. FILE* fileout = nullptr;
  1397. FilePath output_file_path(output_file);
  1398. FilePath output_dir(output_file_path.RemoveFileName());
  1399. if (output_dir.CreateDirectoriesRecursively()) {
  1400. fileout = posix::FOpen(output_file.c_str(), "w");
  1401. }
  1402. if (fileout == nullptr) {
  1403. GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
  1404. }
  1405. return fileout;
  1406. }
  1407. } // namespace internal
  1408. // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
  1409. // environment variable.
  1410. static const char* GetDefaultFilter() {
  1411. const char* const testbridge_test_only =
  1412. internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
  1413. if (testbridge_test_only != nullptr) {
  1414. return testbridge_test_only;
  1415. }
  1416. return kUniversalFilter;
  1417. }
  1418. // Bazel passes in the argument to '--test_runner_fail_fast' via the
  1419. // TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.
  1420. static bool GetDefaultFailFast() {
  1421. const char* const testbridge_test_runner_fail_fast =
  1422. internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
  1423. if (testbridge_test_runner_fail_fast != nullptr) {
  1424. return strcmp(testbridge_test_runner_fail_fast, "1") == 0;
  1425. }
  1426. return false;
  1427. }
  1428. GTEST_DEFINE_bool_(
  1429. fail_fast, internal::BoolFromGTestEnv("fail_fast", GetDefaultFailFast()),
  1430. "True if and only if a test failure should stop further test execution.");
  1431. GTEST_DEFINE_bool_(
  1432. also_run_disabled_tests,
  1433. internal::BoolFromGTestEnv("also_run_disabled_tests", false),
  1434. "Run disabled tests too, in addition to the tests normally being run.");
  1435. GTEST_DEFINE_bool_(
  1436. break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false),
  1437. "True if and only if a failed assertion should be a debugger "
  1438. "break-point.");
  1439. GTEST_DEFINE_bool_(catch_exceptions,
  1440. internal::BoolFromGTestEnv("catch_exceptions", true),
  1441. "True if and only if " GTEST_NAME_
  1442. " should catch exceptions and treat them as test failures.");
  1443. GTEST_DEFINE_string_(
  1444. color,
  1445. internal::StringFromGTestEnv("color", "auto"),
  1446. "Whether to use colors in the output. Valid values: yes, no, "
  1447. "and auto. 'auto' means to use colors if the output is "
  1448. "being sent to a terminal and the TERM environment variable "
  1449. "is set to a terminal type that supports colors.");
  1450. GTEST_DEFINE_string_(
  1451. filter,
  1452. internal::StringFromGTestEnv("filter", GetDefaultFilter()),
  1453. "A colon-separated list of glob (not regex) patterns "
  1454. "for filtering the tests to run, optionally followed by a "
  1455. "'-' and a : separated list of negative patterns (tests to "
  1456. "exclude). A test is run if it matches one of the positive "
  1457. "patterns and does not match any of the negative patterns.");
  1458. GTEST_DEFINE_bool_(
  1459. install_failure_signal_handler,
  1460. internal::BoolFromGTestEnv("install_failure_signal_handler", false),
  1461. "If true and supported on the current platform, " GTEST_NAME_ " should "
  1462. "install a signal handler that dumps debugging information when fatal "
  1463. "signals are raised.");
  1464. GTEST_DEFINE_bool_(list_tests, false,
  1465. "List all tests without running them.");
  1466. // The net priority order after flag processing is thus:
  1467. // --gtest_output command line flag
  1468. // GTEST_OUTPUT environment variable
  1469. // XML_OUTPUT_FILE environment variable
  1470. // ''
  1471. GTEST_DEFINE_string_(
  1472. output,
  1473. internal::StringFromGTestEnv("output",
  1474. internal::OutputFlagAlsoCheckEnvVar().c_str()),
  1475. "A format (defaults to \"xml\" but can be specified to be \"json\"), "
  1476. "optionally followed by a colon and an output file name or directory. "
  1477. "A directory is indicated by a trailing pathname separator. "
  1478. "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
  1479. "If a directory is specified, output files will be created "
  1480. "within that directory, with file-names based on the test "
  1481. "executable's name and, if necessary, made unique by adding "
  1482. "digits.");
  1483. GTEST_DEFINE_bool_(
  1484. brief, internal::BoolFromGTestEnv("brief", false),
  1485. "True if only test failures should be displayed in text output.");
  1486. GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true),
  1487. "True if and only if " GTEST_NAME_
  1488. " should display elapsed time in text output.");
  1489. GTEST_DEFINE_bool_(print_utf8, internal::BoolFromGTestEnv("print_utf8", true),
  1490. "True if and only if " GTEST_NAME_
  1491. " prints UTF8 characters as text.");
  1492. GTEST_DEFINE_int32_(
  1493. random_seed,
  1494. internal::Int32FromGTestEnv("random_seed", 0),
  1495. "Random number seed to use when shuffling test orders. Must be in range "
  1496. "[1, 99999], or 0 to use a seed based on the current time.");
  1497. GTEST_DEFINE_int32_(
  1498. repeat,
  1499. internal::Int32FromGTestEnv("repeat", 1),
  1500. "How many times to repeat each test. Specify a negative number "
  1501. "for repeating forever. Useful for shaking out flaky tests.");
  1502. GTEST_DEFINE_bool_(show_internal_stack_frames, false,
  1503. "True if and only if " GTEST_NAME_
  1504. " should include internal stack frames when "
  1505. "printing test failure stack traces.");
  1506. GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false),
  1507. "True if and only if " GTEST_NAME_
  1508. " should randomize tests' order on every run.");
  1509. GTEST_DEFINE_int32_(
  1510. stack_trace_depth,
  1511. internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
  1512. "The maximum number of stack frames to print when an "
  1513. "assertion fails. The valid range is 0 through 100, inclusive.");
  1514. GTEST_DEFINE_string_(
  1515. stream_result_to,
  1516. internal::StringFromGTestEnv("stream_result_to", ""),
  1517. "This flag specifies the host name and the port number on which to stream "
  1518. "test results. Example: \"localhost:555\". The flag is effective only on "
  1519. "Linux.");
  1520. GTEST_DEFINE_bool_(
  1521. throw_on_failure,
  1522. internal::BoolFromGTestEnv("throw_on_failure", false),
  1523. "When this flag is specified, a failed assertion will throw an exception "
  1524. "if exceptions are enabled or exit the program with a non-zero code "
  1525. "otherwise. For use with an external test framework.");
  1526. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  1527. GTEST_DEFINE_string_(
  1528. flagfile,
  1529. internal::StringFromGTestEnv("flagfile", ""),
  1530. "This flag specifies the flagfile to read command-line flags from.");
  1531. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  1532. namespace internal {
  1533. // Generates a random number from [0, range), using a Linear
  1534. // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
  1535. // than kMaxRange.
  1536. uint32_t Random::Generate(uint32_t range) {
  1537. // These constants are the same as are used in glibc's rand(3).
  1538. // Use wider types than necessary to prevent unsigned overflow diagnostics.
  1539. state_ = static_cast<uint32_t>(1103515245ULL*state_ + 12345U) % kMaxRange;
  1540. GTEST_CHECK_(range > 0)
  1541. << "Cannot generate a number in the range [0, 0).";
  1542. GTEST_CHECK_(range <= kMaxRange)
  1543. << "Generation of a number in [0, " << range << ") was requested, "
  1544. << "but this can only generate numbers in [0, " << kMaxRange << ").";
  1545. // Converting via modulus introduces a bit of downward bias, but
  1546. // it's simple, and a linear congruential generator isn't too good
  1547. // to begin with.
  1548. return state_ % range;
  1549. }
  1550. // GTestIsInitialized() returns true if and only if the user has initialized
  1551. // Google Test. Useful for catching the user mistake of not initializing
  1552. // Google Test before calling RUN_ALL_TESTS().
  1553. static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
  1554. // Iterates over a vector of TestSuites, keeping a running sum of the
  1555. // results of calling a given int-returning method on each.
  1556. // Returns the sum.
  1557. static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
  1558. int (TestSuite::*method)() const) {
  1559. int sum = 0;
  1560. for (size_t i = 0; i < case_list.size(); i++) {
  1561. sum += (case_list[i]->*method)();
  1562. }
  1563. return sum;
  1564. }
  1565. // Returns true if and only if the test suite passed.
  1566. static bool TestSuitePassed(const TestSuite* test_suite) {
  1567. return test_suite->should_run() && test_suite->Passed();
  1568. }
  1569. // Returns true if and only if the test suite failed.
  1570. static bool TestSuiteFailed(const TestSuite* test_suite) {
  1571. return test_suite->should_run() && test_suite->Failed();
  1572. }
  1573. // Returns true if and only if test_suite contains at least one test that
  1574. // should run.
  1575. static bool ShouldRunTestSuite(const TestSuite* test_suite) {
  1576. return test_suite->should_run();
  1577. }
  1578. // AssertHelper constructor.
  1579. AssertHelper::AssertHelper(TestPartResult::Type type,
  1580. const char* file,
  1581. int line,
  1582. const char* message)
  1583. : data_(new AssertHelperData(type, file, line, message)) {
  1584. }
  1585. AssertHelper::~AssertHelper() {
  1586. delete data_;
  1587. }
  1588. // Message assignment, for assertion streaming support.
  1589. void AssertHelper::operator=(const Message& message) const {
  1590. UnitTest::GetInstance()->
  1591. AddTestPartResult(data_->type, data_->file, data_->line,
  1592. AppendUserMessage(data_->message, message),
  1593. UnitTest::GetInstance()->impl()
  1594. ->CurrentOsStackTraceExceptTop(1)
  1595. // Skips the stack frame for this function itself.
  1596. ); // NOLINT
  1597. }
  1598. namespace {
  1599. // When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P
  1600. // to creates test cases for it, a syntetic test case is
  1601. // inserted to report ether an error or a log message.
  1602. //
  1603. // This configuration bit will likely be removed at some point.
  1604. constexpr bool kErrorOnUninstantiatedParameterizedTest = true;
  1605. constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true;
  1606. // A test that fails at a given file/line location with a given message.
  1607. class FailureTest : public Test {
  1608. public:
  1609. explicit FailureTest(const CodeLocation& loc, std::string error_message,
  1610. bool as_error)
  1611. : loc_(loc),
  1612. error_message_(std::move(error_message)),
  1613. as_error_(as_error) {}
  1614. void TestBody() override {
  1615. if (as_error_) {
  1616. AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),
  1617. loc_.line, "") = Message() << error_message_;
  1618. } else {
  1619. std::cout << error_message_ << std::endl;
  1620. }
  1621. }
  1622. private:
  1623. const CodeLocation loc_;
  1624. const std::string error_message_;
  1625. const bool as_error_;
  1626. };
  1627. } // namespace
  1628. std::set<std::string>* GetIgnoredParameterizedTestSuites() {
  1629. return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
  1630. }
  1631. // Add a given test_suit to the list of them allow to go un-instantiated.
  1632. MarkAsIgnored::MarkAsIgnored(const char* test_suite) {
  1633. GetIgnoredParameterizedTestSuites()->insert(test_suite);
  1634. }
  1635. // If this parameterized test suite has no instantiations (and that
  1636. // has not been marked as okay), emit a test case reporting that.
  1637. void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
  1638. bool has_test_p) {
  1639. const auto& ignored = *GetIgnoredParameterizedTestSuites();
  1640. if (ignored.find(name) != ignored.end()) return;
  1641. const char kMissingInstantiation[] = //
  1642. " is defined via TEST_P, but never instantiated. None of the test cases "
  1643. "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
  1644. "ones provided expand to nothing."
  1645. "\n\n"
  1646. "Ideally, TEST_P definitions should only ever be included as part of "
  1647. "binaries that intend to use them. (As opposed to, for example, being "
  1648. "placed in a library that may be linked in to get other utilities.)";
  1649. const char kMissingTestCase[] = //
  1650. " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
  1651. "defined via TEST_P . No test cases will run."
  1652. "\n\n"
  1653. "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
  1654. "code that always depend on code that provides TEST_P. Failing to do "
  1655. "so is often an indication of dead code, e.g. the last TEST_P was "
  1656. "removed but the rest got left behind.";
  1657. std::string message =
  1658. "Parameterized test suite " + name +
  1659. (has_test_p ? kMissingInstantiation : kMissingTestCase) +
  1660. "\n\n"
  1661. "To suppress this error for this test suite, insert the following line "
  1662. "(in a non-header) in the namespace it is defined in:"
  1663. "\n\n"
  1664. "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");";
  1665. std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
  1666. RegisterTest( //
  1667. "GoogleTestVerification", full_name.c_str(),
  1668. nullptr, // No type parameter.
  1669. nullptr, // No value parameter.
  1670. location.file.c_str(), location.line, [message, location] {
  1671. return new FailureTest(location, message,
  1672. kErrorOnUninstantiatedParameterizedTest);
  1673. });
  1674. }
  1675. void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
  1676. CodeLocation code_location) {
  1677. GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(
  1678. test_suite_name, code_location);
  1679. }
  1680. void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) {
  1681. GetUnitTestImpl()
  1682. ->type_parameterized_test_registry()
  1683. .RegisterInstantiation(case_name);
  1684. }
  1685. void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
  1686. const char* test_suite_name, CodeLocation code_location) {
  1687. suites_.emplace(std::string(test_suite_name),
  1688. TypeParameterizedTestSuiteInfo(code_location));
  1689. }
  1690. void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
  1691. const char* test_suite_name) {
  1692. auto it = suites_.find(std::string(test_suite_name));
  1693. if (it != suites_.end()) {
  1694. it->second.instantiated = true;
  1695. } else {
  1696. GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '"
  1697. << test_suite_name << "'";
  1698. }
  1699. }
  1700. void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
  1701. const auto& ignored = *GetIgnoredParameterizedTestSuites();
  1702. for (const auto& testcase : suites_) {
  1703. if (testcase.second.instantiated) continue;
  1704. if (ignored.find(testcase.first) != ignored.end()) continue;
  1705. std::string message =
  1706. "Type parameterized test suite " + testcase.first +
  1707. " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
  1708. "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
  1709. "\n\n"
  1710. "Ideally, TYPED_TEST_P definitions should only ever be included as "
  1711. "part of binaries that intend to use them. (As opposed to, for "
  1712. "example, being placed in a library that may be linked in to get other "
  1713. "utilities.)"
  1714. "\n\n"
  1715. "To suppress this error for this test suite, insert the following line "
  1716. "(in a non-header) in the namespace it is defined in:"
  1717. "\n\n"
  1718. "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
  1719. testcase.first + ");";
  1720. std::string full_name =
  1721. "UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">";
  1722. RegisterTest( //
  1723. "GoogleTestVerification", full_name.c_str(),
  1724. nullptr, // No type parameter.
  1725. nullptr, // No value parameter.
  1726. testcase.second.code_location.file.c_str(),
  1727. testcase.second.code_location.line, [message, testcase] {
  1728. return new FailureTest(testcase.second.code_location, message,
  1729. kErrorOnUninstantiatedTypeParameterizedTest);
  1730. });
  1731. }
  1732. }
  1733. // A copy of all command line arguments. Set by InitGoogleTest().
  1734. static ::std::vector<std::string> g_argvs;
  1735. ::std::vector<std::string> GetArgvs() {
  1736. #if defined(GTEST_CUSTOM_GET_ARGVS_)
  1737. // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
  1738. // ::string. This code converts it to the appropriate type.
  1739. const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
  1740. return ::std::vector<std::string>(custom.begin(), custom.end());
  1741. #else // defined(GTEST_CUSTOM_GET_ARGVS_)
  1742. return g_argvs;
  1743. #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
  1744. }
  1745. // Returns the current application's name, removing directory path if that
  1746. // is present.
  1747. FilePath GetCurrentExecutableName() {
  1748. FilePath result;
  1749. #if GTEST_OS_WINDOWS || GTEST_OS_OS2
  1750. result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
  1751. #else
  1752. result.Set(FilePath(GetArgvs()[0]));
  1753. #endif // GTEST_OS_WINDOWS
  1754. return result.RemoveDirectoryName();
  1755. }
  1756. // Functions for processing the gtest_output flag.
  1757. // Returns the output format, or "" for normal printed output.
  1758. std::string UnitTestOptions::GetOutputFormat() {
  1759. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1760. const char* const colon = strchr(gtest_output_flag, ':');
  1761. return (colon == nullptr)
  1762. ? std::string(gtest_output_flag)
  1763. : std::string(gtest_output_flag,
  1764. static_cast<size_t>(colon - gtest_output_flag));
  1765. }
  1766. // Returns the name of the requested output file, or the default if none
  1767. // was explicitly specified.
  1768. std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
  1769. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1770. std::string format = GetOutputFormat();
  1771. if (format.empty())
  1772. format = std::string(kDefaultOutputFormat);
  1773. const char* const colon = strchr(gtest_output_flag, ':');
  1774. if (colon == nullptr)
  1775. return internal::FilePath::MakeFileName(
  1776. internal::FilePath(
  1777. UnitTest::GetInstance()->original_working_dir()),
  1778. internal::FilePath(kDefaultOutputFile), 0,
  1779. format.c_str()).string();
  1780. internal::FilePath output_name(colon + 1);
  1781. if (!output_name.IsAbsolutePath())
  1782. output_name = internal::FilePath::ConcatPaths(
  1783. internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
  1784. internal::FilePath(colon + 1));
  1785. if (!output_name.IsDirectory())
  1786. return output_name.string();
  1787. internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
  1788. output_name, internal::GetCurrentExecutableName(),
  1789. GetOutputFormat().c_str()));
  1790. return result.string();
  1791. }
  1792. // Returns true if and only if the wildcard pattern matches the string. Each
  1793. // pattern consists of regular characters, single-character wildcards (?), and
  1794. // multi-character wildcards (*).
  1795. //
  1796. // This function implements a linear-time string globbing algorithm based on
  1797. // https://research.swtch.com/glob.
  1798. static bool PatternMatchesString(const std::string& name_str,
  1799. const char* pattern, const char* pattern_end) {
  1800. const char* name = name_str.c_str();
  1801. const char* const name_begin = name;
  1802. const char* const name_end = name + name_str.size();
  1803. const char* pattern_next = pattern;
  1804. const char* name_next = name;
  1805. while (pattern < pattern_end || name < name_end) {
  1806. if (pattern < pattern_end) {
  1807. switch (*pattern) {
  1808. default: // Match an ordinary character.
  1809. if (name < name_end && *name == *pattern) {
  1810. ++pattern;
  1811. ++name;
  1812. continue;
  1813. }
  1814. break;
  1815. case '?': // Match any single character.
  1816. if (name < name_end) {
  1817. ++pattern;
  1818. ++name;
  1819. continue;
  1820. }
  1821. break;
  1822. case '*':
  1823. // Match zero or more characters. Start by skipping over the wildcard
  1824. // and matching zero characters from name. If that fails, restart and
  1825. // match one more character than the last attempt.
  1826. pattern_next = pattern;
  1827. name_next = name + 1;
  1828. ++pattern;
  1829. continue;
  1830. }
  1831. }
  1832. // Failed to match a character. Restart if possible.
  1833. if (name_begin < name_next && name_next <= name_end) {
  1834. pattern = pattern_next;
  1835. name = name_next;
  1836. continue;
  1837. }
  1838. return false;
  1839. }
  1840. return true;
  1841. }
  1842. bool UnitTestOptions::MatchesFilter(const std::string& name_str,
  1843. const char* filter) {
  1844. // The filter is a list of patterns separated by colons (:).
  1845. const char* pattern = filter;
  1846. while (true) {
  1847. // Find the bounds of this pattern.
  1848. const char* const next_sep = strchr(pattern, ':');
  1849. const char* const pattern_end =
  1850. next_sep != nullptr ? next_sep : pattern + strlen(pattern);
  1851. // Check if this pattern matches name_str.
  1852. if (PatternMatchesString(name_str, pattern, pattern_end)) {
  1853. break;
  1854. }
  1855. // Give up on this pattern. However, if we found a pattern separator (:),
  1856. // advance to the next pattern (skipping over the separator) and restart.
  1857. if (next_sep == nullptr) {
  1858. return false;
  1859. }
  1860. pattern = next_sep + 1;
  1861. }
  1862. return true;
  1863. }
  1864. // Returns true if and only if the user-specified filter matches the test
  1865. // suite name and the test name.
  1866. bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
  1867. const std::string& test_name) {
  1868. const std::string& full_name = test_suite_name + "." + test_name.c_str();
  1869. // Split --gtest_filter at '-', if there is one, to separate into
  1870. // positive filter and negative filter portions
  1871. const char* const p = GTEST_FLAG(filter).c_str();
  1872. const char* const dash = strchr(p, '-');
  1873. std::string positive;
  1874. std::string negative;
  1875. if (dash == nullptr) {
  1876. positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
  1877. negative = "";
  1878. } else {
  1879. positive = std::string(p, dash); // Everything up to the dash
  1880. negative = std::string(dash + 1); // Everything after the dash
  1881. if (positive.empty()) {
  1882. // Treat '-test1' as the same as '*-test1'
  1883. positive = kUniversalFilter;
  1884. }
  1885. }
  1886. // A filter is a colon-separated list of patterns. It matches a
  1887. // test if any pattern in it matches the test.
  1888. return (MatchesFilter(full_name, positive.c_str()) &&
  1889. !MatchesFilter(full_name, negative.c_str()));
  1890. }
  1891. #if GTEST_HAS_SEH
  1892. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  1893. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  1894. // This function is useful as an __except condition.
  1895. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
  1896. // Google Test should handle a SEH exception if:
  1897. // 1. the user wants it to, AND
  1898. // 2. this is not a breakpoint exception, AND
  1899. // 3. this is not a C++ exception (VC++ implements them via SEH,
  1900. // apparently).
  1901. //
  1902. // SEH exception code for C++ exceptions.
  1903. // (see http://support.microsoft.com/kb/185294 for more information).
  1904. const DWORD kCxxExceptionCode = 0xe06d7363;
  1905. bool should_handle = true;
  1906. if (!GTEST_FLAG(catch_exceptions))
  1907. should_handle = false;
  1908. else if (exception_code == EXCEPTION_BREAKPOINT)
  1909. should_handle = false;
  1910. else if (exception_code == kCxxExceptionCode)
  1911. should_handle = false;
  1912. return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
  1913. }
  1914. #endif // GTEST_HAS_SEH
  1915. } // namespace internal
  1916. // The c'tor sets this object as the test part result reporter used by
  1917. // Google Test. The 'result' parameter specifies where to report the
  1918. // results. Intercepts only failures from the current thread.
  1919. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1920. TestPartResultArray* result)
  1921. : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
  1922. result_(result) {
  1923. Init();
  1924. }
  1925. // The c'tor sets this object as the test part result reporter used by
  1926. // Google Test. The 'result' parameter specifies where to report the
  1927. // results.
  1928. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1929. InterceptMode intercept_mode, TestPartResultArray* result)
  1930. : intercept_mode_(intercept_mode),
  1931. result_(result) {
  1932. Init();
  1933. }
  1934. void ScopedFakeTestPartResultReporter::Init() {
  1935. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1936. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1937. old_reporter_ = impl->GetGlobalTestPartResultReporter();
  1938. impl->SetGlobalTestPartResultReporter(this);
  1939. } else {
  1940. old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
  1941. impl->SetTestPartResultReporterForCurrentThread(this);
  1942. }
  1943. }
  1944. // The d'tor restores the test part result reporter used by Google Test
  1945. // before.
  1946. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
  1947. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1948. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1949. impl->SetGlobalTestPartResultReporter(old_reporter_);
  1950. } else {
  1951. impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
  1952. }
  1953. }
  1954. // Increments the test part result count and remembers the result.
  1955. // This method is from the TestPartResultReporterInterface interface.
  1956. void ScopedFakeTestPartResultReporter::ReportTestPartResult(
  1957. const TestPartResult& result) {
  1958. result_->Append(result);
  1959. }
  1960. namespace internal {
  1961. // Returns the type ID of ::testing::Test. We should always call this
  1962. // instead of GetTypeId< ::testing::Test>() to get the type ID of
  1963. // testing::Test. This is to work around a suspected linker bug when
  1964. // using Google Test as a framework on Mac OS X. The bug causes
  1965. // GetTypeId< ::testing::Test>() to return different values depending
  1966. // on whether the call is from the Google Test framework itself or
  1967. // from user test code. GetTestTypeId() is guaranteed to always
  1968. // return the same value, as it always calls GetTypeId<>() from the
  1969. // gtest.cc, which is within the Google Test framework.
  1970. TypeId GetTestTypeId() {
  1971. return GetTypeId<Test>();
  1972. }
  1973. // The value of GetTestTypeId() as seen from within the Google Test
  1974. // library. This is solely for testing GetTestTypeId().
  1975. extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
  1976. // This predicate-formatter checks that 'results' contains a test part
  1977. // failure of the given type and that the failure message contains the
  1978. // given substring.
  1979. static AssertionResult HasOneFailure(const char* /* results_expr */,
  1980. const char* /* type_expr */,
  1981. const char* /* substr_expr */,
  1982. const TestPartResultArray& results,
  1983. TestPartResult::Type type,
  1984. const std::string& substr) {
  1985. const std::string expected(type == TestPartResult::kFatalFailure ?
  1986. "1 fatal failure" :
  1987. "1 non-fatal failure");
  1988. Message msg;
  1989. if (results.size() != 1) {
  1990. msg << "Expected: " << expected << "\n"
  1991. << " Actual: " << results.size() << " failures";
  1992. for (int i = 0; i < results.size(); i++) {
  1993. msg << "\n" << results.GetTestPartResult(i);
  1994. }
  1995. return AssertionFailure() << msg;
  1996. }
  1997. const TestPartResult& r = results.GetTestPartResult(0);
  1998. if (r.type() != type) {
  1999. return AssertionFailure() << "Expected: " << expected << "\n"
  2000. << " Actual:\n"
  2001. << r;
  2002. }
  2003. if (strstr(r.message(), substr.c_str()) == nullptr) {
  2004. return AssertionFailure() << "Expected: " << expected << " containing \""
  2005. << substr << "\"\n"
  2006. << " Actual:\n"
  2007. << r;
  2008. }
  2009. return AssertionSuccess();
  2010. }
  2011. // The constructor of SingleFailureChecker remembers where to look up
  2012. // test part results, what type of failure we expect, and what
  2013. // substring the failure message should contain.
  2014. SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
  2015. TestPartResult::Type type,
  2016. const std::string& substr)
  2017. : results_(results), type_(type), substr_(substr) {}
  2018. // The destructor of SingleFailureChecker verifies that the given
  2019. // TestPartResultArray contains exactly one failure that has the given
  2020. // type and contains the given substring. If that's not the case, a
  2021. // non-fatal failure will be generated.
  2022. SingleFailureChecker::~SingleFailureChecker() {
  2023. EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
  2024. }
  2025. DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
  2026. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  2027. void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
  2028. const TestPartResult& result) {
  2029. unit_test_->current_test_result()->AddTestPartResult(result);
  2030. unit_test_->listeners()->repeater()->OnTestPartResult(result);
  2031. }
  2032. DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
  2033. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  2034. void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
  2035. const TestPartResult& result) {
  2036. unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
  2037. }
  2038. // Returns the global test part result reporter.
  2039. TestPartResultReporterInterface*
  2040. UnitTestImpl::GetGlobalTestPartResultReporter() {
  2041. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  2042. return global_test_part_result_repoter_;
  2043. }
  2044. // Sets the global test part result reporter.
  2045. void UnitTestImpl::SetGlobalTestPartResultReporter(
  2046. TestPartResultReporterInterface* reporter) {
  2047. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  2048. global_test_part_result_repoter_ = reporter;
  2049. }
  2050. // Returns the test part result reporter for the current thread.
  2051. TestPartResultReporterInterface*
  2052. UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
  2053. return per_thread_test_part_result_reporter_.get();
  2054. }
  2055. // Sets the test part result reporter for the current thread.
  2056. void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
  2057. TestPartResultReporterInterface* reporter) {
  2058. per_thread_test_part_result_reporter_.set(reporter);
  2059. }
  2060. // Gets the number of successful test suites.
  2061. int UnitTestImpl::successful_test_suite_count() const {
  2062. return CountIf(test_suites_, TestSuitePassed);
  2063. }
  2064. // Gets the number of failed test suites.
  2065. int UnitTestImpl::failed_test_suite_count() const {
  2066. return CountIf(test_suites_, TestSuiteFailed);
  2067. }
  2068. // Gets the number of all test suites.
  2069. int UnitTestImpl::total_test_suite_count() const {
  2070. return static_cast<int>(test_suites_.size());
  2071. }
  2072. // Gets the number of all test suites that contain at least one test
  2073. // that should run.
  2074. int UnitTestImpl::test_suite_to_run_count() const {
  2075. return CountIf(test_suites_, ShouldRunTestSuite);
  2076. }
  2077. // Gets the number of successful tests.
  2078. int UnitTestImpl::successful_test_count() const {
  2079. return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
  2080. }
  2081. // Gets the number of skipped tests.
  2082. int UnitTestImpl::skipped_test_count() const {
  2083. return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
  2084. }
  2085. // Gets the number of failed tests.
  2086. int UnitTestImpl::failed_test_count() const {
  2087. return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
  2088. }
  2089. // Gets the number of disabled tests that will be reported in the XML report.
  2090. int UnitTestImpl::reportable_disabled_test_count() const {
  2091. return SumOverTestSuiteList(test_suites_,
  2092. &TestSuite::reportable_disabled_test_count);
  2093. }
  2094. // Gets the number of disabled tests.
  2095. int UnitTestImpl::disabled_test_count() const {
  2096. return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
  2097. }
  2098. // Gets the number of tests to be printed in the XML report.
  2099. int UnitTestImpl::reportable_test_count() const {
  2100. return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
  2101. }
  2102. // Gets the number of all tests.
  2103. int UnitTestImpl::total_test_count() const {
  2104. return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
  2105. }
  2106. // Gets the number of tests that should run.
  2107. int UnitTestImpl::test_to_run_count() const {
  2108. return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
  2109. }
  2110. // Returns the current OS stack trace as an std::string.
  2111. //
  2112. // The maximum number of stack frames to be included is specified by
  2113. // the gtest_stack_trace_depth flag. The skip_count parameter
  2114. // specifies the number of top frames to be skipped, which doesn't
  2115. // count against the number of frames to be included.
  2116. //
  2117. // For example, if Foo() calls Bar(), which in turn calls
  2118. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  2119. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  2120. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
  2121. return os_stack_trace_getter()->CurrentStackTrace(
  2122. static_cast<int>(GTEST_FLAG(stack_trace_depth)),
  2123. skip_count + 1
  2124. // Skips the user-specified number of frames plus this function
  2125. // itself.
  2126. ); // NOLINT
  2127. }
  2128. // A helper class for measuring elapsed times.
  2129. class Timer {
  2130. public:
  2131. Timer() : start_(std::chrono::steady_clock::now()) {}
  2132. // Return time elapsed in milliseconds since the timer was created.
  2133. TimeInMillis Elapsed() {
  2134. return std::chrono::duration_cast<std::chrono::milliseconds>(
  2135. std::chrono::steady_clock::now() - start_)
  2136. .count();
  2137. }
  2138. private:
  2139. std::chrono::steady_clock::time_point start_;
  2140. };
  2141. // Returns a timestamp as milliseconds since the epoch. Note this time may jump
  2142. // around subject to adjustments by the system, to measure elapsed time use
  2143. // Timer instead.
  2144. TimeInMillis GetTimeInMillis() {
  2145. return std::chrono::duration_cast<std::chrono::milliseconds>(
  2146. std::chrono::system_clock::now() -
  2147. std::chrono::system_clock::from_time_t(0))
  2148. .count();
  2149. }
  2150. // Utilities
  2151. // class String.
  2152. #if GTEST_OS_WINDOWS_MOBILE
  2153. // Creates a UTF-16 wide string from the given ANSI string, allocating
  2154. // memory using new. The caller is responsible for deleting the return
  2155. // value using delete[]. Returns the wide string, or NULL if the
  2156. // input is NULL.
  2157. LPCWSTR String::AnsiToUtf16(const char* ansi) {
  2158. if (!ansi) return nullptr;
  2159. const int length = strlen(ansi);
  2160. const int unicode_length =
  2161. MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
  2162. WCHAR* unicode = new WCHAR[unicode_length + 1];
  2163. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  2164. unicode, unicode_length);
  2165. unicode[unicode_length] = 0;
  2166. return unicode;
  2167. }
  2168. // Creates an ANSI string from the given wide string, allocating
  2169. // memory using new. The caller is responsible for deleting the return
  2170. // value using delete[]. Returns the ANSI string, or NULL if the
  2171. // input is NULL.
  2172. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
  2173. if (!utf16_str) return nullptr;
  2174. const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
  2175. 0, nullptr, nullptr);
  2176. char* ansi = new char[ansi_length + 1];
  2177. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
  2178. nullptr);
  2179. ansi[ansi_length] = 0;
  2180. return ansi;
  2181. }
  2182. #endif // GTEST_OS_WINDOWS_MOBILE
  2183. // Compares two C strings. Returns true if and only if they have the same
  2184. // content.
  2185. //
  2186. // Unlike strcmp(), this function can handle NULL argument(s). A NULL
  2187. // C string is considered different to any non-NULL C string,
  2188. // including the empty string.
  2189. bool String::CStringEquals(const char * lhs, const char * rhs) {
  2190. if (lhs == nullptr) return rhs == nullptr;
  2191. if (rhs == nullptr) return false;
  2192. return strcmp(lhs, rhs) == 0;
  2193. }
  2194. #if GTEST_HAS_STD_WSTRING
  2195. // Converts an array of wide chars to a narrow string using the UTF-8
  2196. // encoding, and streams the result to the given Message object.
  2197. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
  2198. Message* msg) {
  2199. for (size_t i = 0; i != length; ) { // NOLINT
  2200. if (wstr[i] != L'\0') {
  2201. *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
  2202. while (i != length && wstr[i] != L'\0')
  2203. i++;
  2204. } else {
  2205. *msg << '\0';
  2206. i++;
  2207. }
  2208. }
  2209. }
  2210. #endif // GTEST_HAS_STD_WSTRING
  2211. void SplitString(const ::std::string& str, char delimiter,
  2212. ::std::vector< ::std::string>* dest) {
  2213. ::std::vector< ::std::string> parsed;
  2214. ::std::string::size_type pos = 0;
  2215. while (::testing::internal::AlwaysTrue()) {
  2216. const ::std::string::size_type colon = str.find(delimiter, pos);
  2217. if (colon == ::std::string::npos) {
  2218. parsed.push_back(str.substr(pos));
  2219. break;
  2220. } else {
  2221. parsed.push_back(str.substr(pos, colon - pos));
  2222. pos = colon + 1;
  2223. }
  2224. }
  2225. dest->swap(parsed);
  2226. }
  2227. } // namespace internal
  2228. // Constructs an empty Message.
  2229. // We allocate the stringstream separately because otherwise each use of
  2230. // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
  2231. // stack frame leading to huge stack frames in some cases; gcc does not reuse
  2232. // the stack space.
  2233. Message::Message() : ss_(new ::std::stringstream) {
  2234. // By default, we want there to be enough precision when printing
  2235. // a double to a Message.
  2236. *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
  2237. }
  2238. // These two overloads allow streaming a wide C string to a Message
  2239. // using the UTF-8 encoding.
  2240. Message& Message::operator <<(const wchar_t* wide_c_str) {
  2241. return *this << internal::String::ShowWideCString(wide_c_str);
  2242. }
  2243. Message& Message::operator <<(wchar_t* wide_c_str) {
  2244. return *this << internal::String::ShowWideCString(wide_c_str);
  2245. }
  2246. #if GTEST_HAS_STD_WSTRING
  2247. // Converts the given wide string to a narrow string using the UTF-8
  2248. // encoding, and streams the result to this Message object.
  2249. Message& Message::operator <<(const ::std::wstring& wstr) {
  2250. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  2251. return *this;
  2252. }
  2253. #endif // GTEST_HAS_STD_WSTRING
  2254. // Gets the text streamed to this object so far as an std::string.
  2255. // Each '\0' character in the buffer is replaced with "\\0".
  2256. std::string Message::GetString() const {
  2257. return internal::StringStreamToString(ss_.get());
  2258. }
  2259. // AssertionResult constructors.
  2260. // Used in EXPECT_TRUE/FALSE(assertion_result).
  2261. AssertionResult::AssertionResult(const AssertionResult& other)
  2262. : success_(other.success_),
  2263. message_(other.message_.get() != nullptr
  2264. ? new ::std::string(*other.message_)
  2265. : static_cast< ::std::string*>(nullptr)) {}
  2266. // Swaps two AssertionResults.
  2267. void AssertionResult::swap(AssertionResult& other) {
  2268. using std::swap;
  2269. swap(success_, other.success_);
  2270. swap(message_, other.message_);
  2271. }
  2272. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  2273. AssertionResult AssertionResult::operator!() const {
  2274. AssertionResult negation(!success_);
  2275. if (message_.get() != nullptr) negation << *message_;
  2276. return negation;
  2277. }
  2278. // Makes a successful assertion result.
  2279. AssertionResult AssertionSuccess() {
  2280. return AssertionResult(true);
  2281. }
  2282. // Makes a failed assertion result.
  2283. AssertionResult AssertionFailure() {
  2284. return AssertionResult(false);
  2285. }
  2286. // Makes a failed assertion result with the given failure message.
  2287. // Deprecated; use AssertionFailure() << message.
  2288. AssertionResult AssertionFailure(const Message& message) {
  2289. return AssertionFailure() << message;
  2290. }
  2291. namespace internal {
  2292. namespace edit_distance {
  2293. std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
  2294. const std::vector<size_t>& right) {
  2295. std::vector<std::vector<double> > costs(
  2296. left.size() + 1, std::vector<double>(right.size() + 1));
  2297. std::vector<std::vector<EditType> > best_move(
  2298. left.size() + 1, std::vector<EditType>(right.size() + 1));
  2299. // Populate for empty right.
  2300. for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
  2301. costs[l_i][0] = static_cast<double>(l_i);
  2302. best_move[l_i][0] = kRemove;
  2303. }
  2304. // Populate for empty left.
  2305. for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
  2306. costs[0][r_i] = static_cast<double>(r_i);
  2307. best_move[0][r_i] = kAdd;
  2308. }
  2309. for (size_t l_i = 0; l_i < left.size(); ++l_i) {
  2310. for (size_t r_i = 0; r_i < right.size(); ++r_i) {
  2311. if (left[l_i] == right[r_i]) {
  2312. // Found a match. Consume it.
  2313. costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
  2314. best_move[l_i + 1][r_i + 1] = kMatch;
  2315. continue;
  2316. }
  2317. const double add = costs[l_i + 1][r_i];
  2318. const double remove = costs[l_i][r_i + 1];
  2319. const double replace = costs[l_i][r_i];
  2320. if (add < remove && add < replace) {
  2321. costs[l_i + 1][r_i + 1] = add + 1;
  2322. best_move[l_i + 1][r_i + 1] = kAdd;
  2323. } else if (remove < add && remove < replace) {
  2324. costs[l_i + 1][r_i + 1] = remove + 1;
  2325. best_move[l_i + 1][r_i + 1] = kRemove;
  2326. } else {
  2327. // We make replace a little more expensive than add/remove to lower
  2328. // their priority.
  2329. costs[l_i + 1][r_i + 1] = replace + 1.00001;
  2330. best_move[l_i + 1][r_i + 1] = kReplace;
  2331. }
  2332. }
  2333. }
  2334. // Reconstruct the best path. We do it in reverse order.
  2335. std::vector<EditType> best_path;
  2336. for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
  2337. EditType move = best_move[l_i][r_i];
  2338. best_path.push_back(move);
  2339. l_i -= move != kAdd;
  2340. r_i -= move != kRemove;
  2341. }
  2342. std::reverse(best_path.begin(), best_path.end());
  2343. return best_path;
  2344. }
  2345. namespace {
  2346. // Helper class to convert string into ids with deduplication.
  2347. class InternalStrings {
  2348. public:
  2349. size_t GetId(const std::string& str) {
  2350. IdMap::iterator it = ids_.find(str);
  2351. if (it != ids_.end()) return it->second;
  2352. size_t id = ids_.size();
  2353. return ids_[str] = id;
  2354. }
  2355. private:
  2356. typedef std::map<std::string, size_t> IdMap;
  2357. IdMap ids_;
  2358. };
  2359. } // namespace
  2360. std::vector<EditType> CalculateOptimalEdits(
  2361. const std::vector<std::string>& left,
  2362. const std::vector<std::string>& right) {
  2363. std::vector<size_t> left_ids, right_ids;
  2364. {
  2365. InternalStrings intern_table;
  2366. for (size_t i = 0; i < left.size(); ++i) {
  2367. left_ids.push_back(intern_table.GetId(left[i]));
  2368. }
  2369. for (size_t i = 0; i < right.size(); ++i) {
  2370. right_ids.push_back(intern_table.GetId(right[i]));
  2371. }
  2372. }
  2373. return CalculateOptimalEdits(left_ids, right_ids);
  2374. }
  2375. namespace {
  2376. // Helper class that holds the state for one hunk and prints it out to the
  2377. // stream.
  2378. // It reorders adds/removes when possible to group all removes before all
  2379. // adds. It also adds the hunk header before printint into the stream.
  2380. class Hunk {
  2381. public:
  2382. Hunk(size_t left_start, size_t right_start)
  2383. : left_start_(left_start),
  2384. right_start_(right_start),
  2385. adds_(),
  2386. removes_(),
  2387. common_() {}
  2388. void PushLine(char edit, const char* line) {
  2389. switch (edit) {
  2390. case ' ':
  2391. ++common_;
  2392. FlushEdits();
  2393. hunk_.push_back(std::make_pair(' ', line));
  2394. break;
  2395. case '-':
  2396. ++removes_;
  2397. hunk_removes_.push_back(std::make_pair('-', line));
  2398. break;
  2399. case '+':
  2400. ++adds_;
  2401. hunk_adds_.push_back(std::make_pair('+', line));
  2402. break;
  2403. }
  2404. }
  2405. void PrintTo(std::ostream* os) {
  2406. PrintHeader(os);
  2407. FlushEdits();
  2408. for (std::list<std::pair<char, const char*> >::const_iterator it =
  2409. hunk_.begin();
  2410. it != hunk_.end(); ++it) {
  2411. *os << it->first << it->second << "\n";
  2412. }
  2413. }
  2414. bool has_edits() const { return adds_ || removes_; }
  2415. private:
  2416. void FlushEdits() {
  2417. hunk_.splice(hunk_.end(), hunk_removes_);
  2418. hunk_.splice(hunk_.end(), hunk_adds_);
  2419. }
  2420. // Print a unified diff header for one hunk.
  2421. // The format is
  2422. // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
  2423. // where the left/right parts are omitted if unnecessary.
  2424. void PrintHeader(std::ostream* ss) const {
  2425. *ss << "@@ ";
  2426. if (removes_) {
  2427. *ss << "-" << left_start_ << "," << (removes_ + common_);
  2428. }
  2429. if (removes_ && adds_) {
  2430. *ss << " ";
  2431. }
  2432. if (adds_) {
  2433. *ss << "+" << right_start_ << "," << (adds_ + common_);
  2434. }
  2435. *ss << " @@\n";
  2436. }
  2437. size_t left_start_, right_start_;
  2438. size_t adds_, removes_, common_;
  2439. std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
  2440. };
  2441. } // namespace
  2442. // Create a list of diff hunks in Unified diff format.
  2443. // Each hunk has a header generated by PrintHeader above plus a body with
  2444. // lines prefixed with ' ' for no change, '-' for deletion and '+' for
  2445. // addition.
  2446. // 'context' represents the desired unchanged prefix/suffix around the diff.
  2447. // If two hunks are close enough that their contexts overlap, then they are
  2448. // joined into one hunk.
  2449. std::string CreateUnifiedDiff(const std::vector<std::string>& left,
  2450. const std::vector<std::string>& right,
  2451. size_t context) {
  2452. const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
  2453. size_t l_i = 0, r_i = 0, edit_i = 0;
  2454. std::stringstream ss;
  2455. while (edit_i < edits.size()) {
  2456. // Find first edit.
  2457. while (edit_i < edits.size() && edits[edit_i] == kMatch) {
  2458. ++l_i;
  2459. ++r_i;
  2460. ++edit_i;
  2461. }
  2462. // Find the first line to include in the hunk.
  2463. const size_t prefix_context = std::min(l_i, context);
  2464. Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
  2465. for (size_t i = prefix_context; i > 0; --i) {
  2466. hunk.PushLine(' ', left[l_i - i].c_str());
  2467. }
  2468. // Iterate the edits until we found enough suffix for the hunk or the input
  2469. // is over.
  2470. size_t n_suffix = 0;
  2471. for (; edit_i < edits.size(); ++edit_i) {
  2472. if (n_suffix >= context) {
  2473. // Continue only if the next hunk is very close.
  2474. auto it = edits.begin() + static_cast<int>(edit_i);
  2475. while (it != edits.end() && *it == kMatch) ++it;
  2476. if (it == edits.end() ||
  2477. static_cast<size_t>(it - edits.begin()) - edit_i >= context) {
  2478. // There is no next edit or it is too far away.
  2479. break;
  2480. }
  2481. }
  2482. EditType edit = edits[edit_i];
  2483. // Reset count when a non match is found.
  2484. n_suffix = edit == kMatch ? n_suffix + 1 : 0;
  2485. if (edit == kMatch || edit == kRemove || edit == kReplace) {
  2486. hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
  2487. }
  2488. if (edit == kAdd || edit == kReplace) {
  2489. hunk.PushLine('+', right[r_i].c_str());
  2490. }
  2491. // Advance indices, depending on edit type.
  2492. l_i += edit != kAdd;
  2493. r_i += edit != kRemove;
  2494. }
  2495. if (!hunk.has_edits()) {
  2496. // We are done. We don't want this hunk.
  2497. break;
  2498. }
  2499. hunk.PrintTo(&ss);
  2500. }
  2501. return ss.str();
  2502. }
  2503. } // namespace edit_distance
  2504. namespace {
  2505. // The string representation of the values received in EqFailure() are already
  2506. // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
  2507. // characters the same.
  2508. std::vector<std::string> SplitEscapedString(const std::string& str) {
  2509. std::vector<std::string> lines;
  2510. size_t start = 0, end = str.size();
  2511. if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
  2512. ++start;
  2513. --end;
  2514. }
  2515. bool escaped = false;
  2516. for (size_t i = start; i + 1 < end; ++i) {
  2517. if (escaped) {
  2518. escaped = false;
  2519. if (str[i] == 'n') {
  2520. lines.push_back(str.substr(start, i - start - 1));
  2521. start = i + 1;
  2522. }
  2523. } else {
  2524. escaped = str[i] == '\\';
  2525. }
  2526. }
  2527. lines.push_back(str.substr(start, end - start));
  2528. return lines;
  2529. }
  2530. } // namespace
  2531. // Constructs and returns the message for an equality assertion
  2532. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  2533. //
  2534. // The first four parameters are the expressions used in the assertion
  2535. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  2536. // where foo is 5 and bar is 6, we have:
  2537. //
  2538. // lhs_expression: "foo"
  2539. // rhs_expression: "bar"
  2540. // lhs_value: "5"
  2541. // rhs_value: "6"
  2542. //
  2543. // The ignoring_case parameter is true if and only if the assertion is a
  2544. // *_STRCASEEQ*. When it's true, the string "Ignoring case" will
  2545. // be inserted into the message.
  2546. AssertionResult EqFailure(const char* lhs_expression,
  2547. const char* rhs_expression,
  2548. const std::string& lhs_value,
  2549. const std::string& rhs_value,
  2550. bool ignoring_case) {
  2551. Message msg;
  2552. msg << "Expected equality of these values:";
  2553. msg << "\n " << lhs_expression;
  2554. if (lhs_value != lhs_expression) {
  2555. msg << "\n Which is: " << lhs_value;
  2556. }
  2557. msg << "\n " << rhs_expression;
  2558. if (rhs_value != rhs_expression) {
  2559. msg << "\n Which is: " << rhs_value;
  2560. }
  2561. if (ignoring_case) {
  2562. msg << "\nIgnoring case";
  2563. }
  2564. if (!lhs_value.empty() && !rhs_value.empty()) {
  2565. const std::vector<std::string> lhs_lines =
  2566. SplitEscapedString(lhs_value);
  2567. const std::vector<std::string> rhs_lines =
  2568. SplitEscapedString(rhs_value);
  2569. if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
  2570. msg << "\nWith diff:\n"
  2571. << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
  2572. }
  2573. }
  2574. return AssertionFailure() << msg;
  2575. }
  2576. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  2577. std::string GetBoolAssertionFailureMessage(
  2578. const AssertionResult& assertion_result,
  2579. const char* expression_text,
  2580. const char* actual_predicate_value,
  2581. const char* expected_predicate_value) {
  2582. const char* actual_message = assertion_result.message();
  2583. Message msg;
  2584. msg << "Value of: " << expression_text
  2585. << "\n Actual: " << actual_predicate_value;
  2586. if (actual_message[0] != '\0')
  2587. msg << " (" << actual_message << ")";
  2588. msg << "\nExpected: " << expected_predicate_value;
  2589. return msg.GetString();
  2590. }
  2591. // Helper function for implementing ASSERT_NEAR.
  2592. AssertionResult DoubleNearPredFormat(const char* expr1,
  2593. const char* expr2,
  2594. const char* abs_error_expr,
  2595. double val1,
  2596. double val2,
  2597. double abs_error) {
  2598. const double diff = fabs(val1 - val2);
  2599. if (diff <= abs_error) return AssertionSuccess();
  2600. // Find the value which is closest to zero.
  2601. const double min_abs = std::min(fabs(val1), fabs(val2));
  2602. // Find the distance to the next double from that value.
  2603. const double epsilon =
  2604. nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
  2605. // Detect the case where abs_error is so small that EXPECT_NEAR is
  2606. // effectively the same as EXPECT_EQUAL, and give an informative error
  2607. // message so that the situation can be more easily understood without
  2608. // requiring exotic floating-point knowledge.
  2609. // Don't do an epsilon check if abs_error is zero because that implies
  2610. // that an equality check was actually intended.
  2611. if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
  2612. abs_error < epsilon) {
  2613. return AssertionFailure()
  2614. << "The difference between " << expr1 << " and " << expr2 << " is "
  2615. << diff << ", where\n"
  2616. << expr1 << " evaluates to " << val1 << ",\n"
  2617. << expr2 << " evaluates to " << val2 << ".\nThe abs_error parameter "
  2618. << abs_error_expr << " evaluates to " << abs_error
  2619. << " which is smaller than the minimum distance between doubles for "
  2620. "numbers of this magnitude which is "
  2621. << epsilon
  2622. << ", thus making this EXPECT_NEAR check equivalent to "
  2623. "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
  2624. }
  2625. return AssertionFailure()
  2626. << "The difference between " << expr1 << " and " << expr2
  2627. << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
  2628. << expr1 << " evaluates to " << val1 << ",\n"
  2629. << expr2 << " evaluates to " << val2 << ", and\n"
  2630. << abs_error_expr << " evaluates to " << abs_error << ".";
  2631. }
  2632. // Helper template for implementing FloatLE() and DoubleLE().
  2633. template <typename RawType>
  2634. AssertionResult FloatingPointLE(const char* expr1,
  2635. const char* expr2,
  2636. RawType val1,
  2637. RawType val2) {
  2638. // Returns success if val1 is less than val2,
  2639. if (val1 < val2) {
  2640. return AssertionSuccess();
  2641. }
  2642. // or if val1 is almost equal to val2.
  2643. const FloatingPoint<RawType> lhs(val1), rhs(val2);
  2644. if (lhs.AlmostEquals(rhs)) {
  2645. return AssertionSuccess();
  2646. }
  2647. // Note that the above two checks will both fail if either val1 or
  2648. // val2 is NaN, as the IEEE floating-point standard requires that
  2649. // any predicate involving a NaN must return false.
  2650. ::std::stringstream val1_ss;
  2651. val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2652. << val1;
  2653. ::std::stringstream val2_ss;
  2654. val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2655. << val2;
  2656. return AssertionFailure()
  2657. << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
  2658. << " Actual: " << StringStreamToString(&val1_ss) << " vs "
  2659. << StringStreamToString(&val2_ss);
  2660. }
  2661. } // namespace internal
  2662. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2663. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2664. AssertionResult FloatLE(const char* expr1, const char* expr2,
  2665. float val1, float val2) {
  2666. return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
  2667. }
  2668. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2669. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2670. AssertionResult DoubleLE(const char* expr1, const char* expr2,
  2671. double val1, double val2) {
  2672. return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
  2673. }
  2674. namespace internal {
  2675. // The helper function for {ASSERT|EXPECT}_STREQ.
  2676. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  2677. const char* rhs_expression,
  2678. const char* lhs,
  2679. const char* rhs) {
  2680. if (String::CStringEquals(lhs, rhs)) {
  2681. return AssertionSuccess();
  2682. }
  2683. return EqFailure(lhs_expression,
  2684. rhs_expression,
  2685. PrintToString(lhs),
  2686. PrintToString(rhs),
  2687. false);
  2688. }
  2689. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  2690. AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
  2691. const char* rhs_expression,
  2692. const char* lhs,
  2693. const char* rhs) {
  2694. if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
  2695. return AssertionSuccess();
  2696. }
  2697. return EqFailure(lhs_expression,
  2698. rhs_expression,
  2699. PrintToString(lhs),
  2700. PrintToString(rhs),
  2701. true);
  2702. }
  2703. // The helper function for {ASSERT|EXPECT}_STRNE.
  2704. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  2705. const char* s2_expression,
  2706. const char* s1,
  2707. const char* s2) {
  2708. if (!String::CStringEquals(s1, s2)) {
  2709. return AssertionSuccess();
  2710. } else {
  2711. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  2712. << s2_expression << "), actual: \""
  2713. << s1 << "\" vs \"" << s2 << "\"";
  2714. }
  2715. }
  2716. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  2717. AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  2718. const char* s2_expression,
  2719. const char* s1,
  2720. const char* s2) {
  2721. if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
  2722. return AssertionSuccess();
  2723. } else {
  2724. return AssertionFailure()
  2725. << "Expected: (" << s1_expression << ") != ("
  2726. << s2_expression << ") (ignoring case), actual: \""
  2727. << s1 << "\" vs \"" << s2 << "\"";
  2728. }
  2729. }
  2730. } // namespace internal
  2731. namespace {
  2732. // Helper functions for implementing IsSubString() and IsNotSubstring().
  2733. // This group of overloaded functions return true if and only if needle
  2734. // is a substring of haystack. NULL is considered a substring of
  2735. // itself only.
  2736. bool IsSubstringPred(const char* needle, const char* haystack) {
  2737. if (needle == nullptr || haystack == nullptr) return needle == haystack;
  2738. return strstr(haystack, needle) != nullptr;
  2739. }
  2740. bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
  2741. if (needle == nullptr || haystack == nullptr) return needle == haystack;
  2742. return wcsstr(haystack, needle) != nullptr;
  2743. }
  2744. // StringType here can be either ::std::string or ::std::wstring.
  2745. template <typename StringType>
  2746. bool IsSubstringPred(const StringType& needle,
  2747. const StringType& haystack) {
  2748. return haystack.find(needle) != StringType::npos;
  2749. }
  2750. // This function implements either IsSubstring() or IsNotSubstring(),
  2751. // depending on the value of the expected_to_be_substring parameter.
  2752. // StringType here can be const char*, const wchar_t*, ::std::string,
  2753. // or ::std::wstring.
  2754. template <typename StringType>
  2755. AssertionResult IsSubstringImpl(
  2756. bool expected_to_be_substring,
  2757. const char* needle_expr, const char* haystack_expr,
  2758. const StringType& needle, const StringType& haystack) {
  2759. if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
  2760. return AssertionSuccess();
  2761. const bool is_wide_string = sizeof(needle[0]) > 1;
  2762. const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
  2763. return AssertionFailure()
  2764. << "Value of: " << needle_expr << "\n"
  2765. << " Actual: " << begin_string_quote << needle << "\"\n"
  2766. << "Expected: " << (expected_to_be_substring ? "" : "not ")
  2767. << "a substring of " << haystack_expr << "\n"
  2768. << "Which is: " << begin_string_quote << haystack << "\"";
  2769. }
  2770. } // namespace
  2771. // IsSubstring() and IsNotSubstring() check whether needle is a
  2772. // substring of haystack (NULL is considered a substring of itself
  2773. // only), and return an appropriate error message when they fail.
  2774. AssertionResult IsSubstring(
  2775. const char* needle_expr, const char* haystack_expr,
  2776. const char* needle, const char* haystack) {
  2777. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2778. }
  2779. AssertionResult IsSubstring(
  2780. const char* needle_expr, const char* haystack_expr,
  2781. const wchar_t* needle, const wchar_t* haystack) {
  2782. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2783. }
  2784. AssertionResult IsNotSubstring(
  2785. const char* needle_expr, const char* haystack_expr,
  2786. const char* needle, const char* haystack) {
  2787. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2788. }
  2789. AssertionResult IsNotSubstring(
  2790. const char* needle_expr, const char* haystack_expr,
  2791. const wchar_t* needle, const wchar_t* haystack) {
  2792. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2793. }
  2794. AssertionResult IsSubstring(
  2795. const char* needle_expr, const char* haystack_expr,
  2796. const ::std::string& needle, const ::std::string& haystack) {
  2797. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2798. }
  2799. AssertionResult IsNotSubstring(
  2800. const char* needle_expr, const char* haystack_expr,
  2801. const ::std::string& needle, const ::std::string& haystack) {
  2802. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2803. }
  2804. #if GTEST_HAS_STD_WSTRING
  2805. AssertionResult IsSubstring(
  2806. const char* needle_expr, const char* haystack_expr,
  2807. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2808. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2809. }
  2810. AssertionResult IsNotSubstring(
  2811. const char* needle_expr, const char* haystack_expr,
  2812. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2813. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2814. }
  2815. #endif // GTEST_HAS_STD_WSTRING
  2816. namespace internal {
  2817. #if GTEST_OS_WINDOWS
  2818. namespace {
  2819. // Helper function for IsHRESULT{SuccessFailure} predicates
  2820. AssertionResult HRESULTFailureHelper(const char* expr,
  2821. const char* expected,
  2822. long hr) { // NOLINT
  2823. # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
  2824. // Windows CE doesn't support FormatMessage.
  2825. const char error_text[] = "";
  2826. # else
  2827. // Looks up the human-readable system message for the HRESULT code
  2828. // and since we're not passing any params to FormatMessage, we don't
  2829. // want inserts expanded.
  2830. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
  2831. FORMAT_MESSAGE_IGNORE_INSERTS;
  2832. const DWORD kBufSize = 4096;
  2833. // Gets the system's human readable message string for this HRESULT.
  2834. char error_text[kBufSize] = { '\0' };
  2835. DWORD message_length = ::FormatMessageA(kFlags,
  2836. 0, // no source, we're asking system
  2837. static_cast<DWORD>(hr), // the error
  2838. 0, // no line width restrictions
  2839. error_text, // output buffer
  2840. kBufSize, // buf size
  2841. nullptr); // no arguments for inserts
  2842. // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
  2843. for (; message_length && IsSpace(error_text[message_length - 1]);
  2844. --message_length) {
  2845. error_text[message_length - 1] = '\0';
  2846. }
  2847. # endif // GTEST_OS_WINDOWS_MOBILE
  2848. const std::string error_hex("0x" + String::FormatHexInt(hr));
  2849. return ::testing::AssertionFailure()
  2850. << "Expected: " << expr << " " << expected << ".\n"
  2851. << " Actual: " << error_hex << " " << error_text << "\n";
  2852. }
  2853. } // namespace
  2854. AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
  2855. if (SUCCEEDED(hr)) {
  2856. return AssertionSuccess();
  2857. }
  2858. return HRESULTFailureHelper(expr, "succeeds", hr);
  2859. }
  2860. AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
  2861. if (FAILED(hr)) {
  2862. return AssertionSuccess();
  2863. }
  2864. return HRESULTFailureHelper(expr, "fails", hr);
  2865. }
  2866. #endif // GTEST_OS_WINDOWS
  2867. // Utility functions for encoding Unicode text (wide strings) in
  2868. // UTF-8.
  2869. // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
  2870. // like this:
  2871. //
  2872. // Code-point length Encoding
  2873. // 0 - 7 bits 0xxxxxxx
  2874. // 8 - 11 bits 110xxxxx 10xxxxxx
  2875. // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
  2876. // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  2877. // The maximum code-point a one-byte UTF-8 sequence can represent.
  2878. constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1;
  2879. // The maximum code-point a two-byte UTF-8 sequence can represent.
  2880. constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1;
  2881. // The maximum code-point a three-byte UTF-8 sequence can represent.
  2882. constexpr uint32_t kMaxCodePoint3 = (static_cast<uint32_t>(1) << (4 + 2*6)) - 1;
  2883. // The maximum code-point a four-byte UTF-8 sequence can represent.
  2884. constexpr uint32_t kMaxCodePoint4 = (static_cast<uint32_t>(1) << (3 + 3*6)) - 1;
  2885. // Chops off the n lowest bits from a bit pattern. Returns the n
  2886. // lowest bits. As a side effect, the original bit pattern will be
  2887. // shifted to the right by n bits.
  2888. inline uint32_t ChopLowBits(uint32_t* bits, int n) {
  2889. const uint32_t low_bits = *bits & ((static_cast<uint32_t>(1) << n) - 1);
  2890. *bits >>= n;
  2891. return low_bits;
  2892. }
  2893. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  2894. // code_point parameter is of type uint32_t because wchar_t may not be
  2895. // wide enough to contain a code point.
  2896. // If the code_point is not a valid Unicode code point
  2897. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  2898. // to "(Invalid Unicode 0xXXXXXXXX)".
  2899. std::string CodePointToUtf8(uint32_t code_point) {
  2900. if (code_point > kMaxCodePoint4) {
  2901. return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")";
  2902. }
  2903. char str[5]; // Big enough for the largest valid code point.
  2904. if (code_point <= kMaxCodePoint1) {
  2905. str[1] = '\0';
  2906. str[0] = static_cast<char>(code_point); // 0xxxxxxx
  2907. } else if (code_point <= kMaxCodePoint2) {
  2908. str[2] = '\0';
  2909. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2910. str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
  2911. } else if (code_point <= kMaxCodePoint3) {
  2912. str[3] = '\0';
  2913. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2914. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2915. str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
  2916. } else { // code_point <= kMaxCodePoint4
  2917. str[4] = '\0';
  2918. str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2919. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2920. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2921. str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
  2922. }
  2923. return str;
  2924. }
  2925. // The following two functions only make sense if the system
  2926. // uses UTF-16 for wide string encoding. All supported systems
  2927. // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
  2928. // Determines if the arguments constitute UTF-16 surrogate pair
  2929. // and thus should be combined into a single Unicode code point
  2930. // using CreateCodePointFromUtf16SurrogatePair.
  2931. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
  2932. return sizeof(wchar_t) == 2 &&
  2933. (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
  2934. }
  2935. // Creates a Unicode code point from UTF16 surrogate pair.
  2936. inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first,
  2937. wchar_t second) {
  2938. const auto first_u = static_cast<uint32_t>(first);
  2939. const auto second_u = static_cast<uint32_t>(second);
  2940. const uint32_t mask = (1 << 10) - 1;
  2941. return (sizeof(wchar_t) == 2)
  2942. ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
  2943. :
  2944. // This function should not be called when the condition is
  2945. // false, but we provide a sensible default in case it is.
  2946. first_u;
  2947. }
  2948. // Converts a wide string to a narrow string in UTF-8 encoding.
  2949. // The wide string is assumed to have the following encoding:
  2950. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
  2951. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  2952. // Parameter str points to a null-terminated wide string.
  2953. // Parameter num_chars may additionally limit the number
  2954. // of wchar_t characters processed. -1 is used when the entire string
  2955. // should be processed.
  2956. // If the string contains code points that are not valid Unicode code points
  2957. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  2958. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  2959. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  2960. // will be encoded as individual Unicode characters from Basic Normal Plane.
  2961. std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
  2962. if (num_chars == -1)
  2963. num_chars = static_cast<int>(wcslen(str));
  2964. ::std::stringstream stream;
  2965. for (int i = 0; i < num_chars; ++i) {
  2966. uint32_t unicode_code_point;
  2967. if (str[i] == L'\0') {
  2968. break;
  2969. } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
  2970. unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
  2971. str[i + 1]);
  2972. i++;
  2973. } else {
  2974. unicode_code_point = static_cast<uint32_t>(str[i]);
  2975. }
  2976. stream << CodePointToUtf8(unicode_code_point);
  2977. }
  2978. return StringStreamToString(&stream);
  2979. }
  2980. // Converts a wide C string to an std::string using the UTF-8 encoding.
  2981. // NULL will be converted to "(null)".
  2982. std::string String::ShowWideCString(const wchar_t * wide_c_str) {
  2983. if (wide_c_str == nullptr) return "(null)";
  2984. return internal::WideStringToUtf8(wide_c_str, -1);
  2985. }
  2986. // Compares two wide C strings. Returns true if and only if they have the
  2987. // same content.
  2988. //
  2989. // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
  2990. // C string is considered different to any non-NULL C string,
  2991. // including the empty string.
  2992. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
  2993. if (lhs == nullptr) return rhs == nullptr;
  2994. if (rhs == nullptr) return false;
  2995. return wcscmp(lhs, rhs) == 0;
  2996. }
  2997. // Helper function for *_STREQ on wide strings.
  2998. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  2999. const char* rhs_expression,
  3000. const wchar_t* lhs,
  3001. const wchar_t* rhs) {
  3002. if (String::WideCStringEquals(lhs, rhs)) {
  3003. return AssertionSuccess();
  3004. }
  3005. return EqFailure(lhs_expression,
  3006. rhs_expression,
  3007. PrintToString(lhs),
  3008. PrintToString(rhs),
  3009. false);
  3010. }
  3011. // Helper function for *_STRNE on wide strings.
  3012. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  3013. const char* s2_expression,
  3014. const wchar_t* s1,
  3015. const wchar_t* s2) {
  3016. if (!String::WideCStringEquals(s1, s2)) {
  3017. return AssertionSuccess();
  3018. }
  3019. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  3020. << s2_expression << "), actual: "
  3021. << PrintToString(s1)
  3022. << " vs " << PrintToString(s2);
  3023. }
  3024. // Compares two C strings, ignoring case. Returns true if and only if they have
  3025. // the same content.
  3026. //
  3027. // Unlike strcasecmp(), this function can handle NULL argument(s). A
  3028. // NULL C string is considered different to any non-NULL C string,
  3029. // including the empty string.
  3030. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
  3031. if (lhs == nullptr) return rhs == nullptr;
  3032. if (rhs == nullptr) return false;
  3033. return posix::StrCaseCmp(lhs, rhs) == 0;
  3034. }
  3035. // Compares two wide C strings, ignoring case. Returns true if and only if they
  3036. // have the same content.
  3037. //
  3038. // Unlike wcscasecmp(), this function can handle NULL argument(s).
  3039. // A NULL C string is considered different to any non-NULL wide C string,
  3040. // including the empty string.
  3041. // NB: The implementations on different platforms slightly differ.
  3042. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  3043. // environment variable. On GNU platform this method uses wcscasecmp
  3044. // which compares according to LC_CTYPE category of the current locale.
  3045. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  3046. // current locale.
  3047. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  3048. const wchar_t* rhs) {
  3049. if (lhs == nullptr) return rhs == nullptr;
  3050. if (rhs == nullptr) return false;
  3051. #if GTEST_OS_WINDOWS
  3052. return _wcsicmp(lhs, rhs) == 0;
  3053. #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
  3054. return wcscasecmp(lhs, rhs) == 0;
  3055. #else
  3056. // Android, Mac OS X and Cygwin don't define wcscasecmp.
  3057. // Other unknown OSes may not define it either.
  3058. wint_t left, right;
  3059. do {
  3060. left = towlower(static_cast<wint_t>(*lhs++));
  3061. right = towlower(static_cast<wint_t>(*rhs++));
  3062. } while (left && left == right);
  3063. return left == right;
  3064. #endif // OS selector
  3065. }
  3066. // Returns true if and only if str ends with the given suffix, ignoring case.
  3067. // Any string is considered to end with an empty suffix.
  3068. bool String::EndsWithCaseInsensitive(
  3069. const std::string& str, const std::string& suffix) {
  3070. const size_t str_len = str.length();
  3071. const size_t suffix_len = suffix.length();
  3072. return (str_len >= suffix_len) &&
  3073. CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
  3074. suffix.c_str());
  3075. }
  3076. // Formats an int value as "%02d".
  3077. std::string String::FormatIntWidth2(int value) {
  3078. return FormatIntWidthN(value, 2);
  3079. }
  3080. // Formats an int value to given width with leading zeros.
  3081. std::string String::FormatIntWidthN(int value, int width) {
  3082. std::stringstream ss;
  3083. ss << std::setfill('0') << std::setw(width) << value;
  3084. return ss.str();
  3085. }
  3086. // Formats an int value as "%X".
  3087. std::string String::FormatHexUInt32(uint32_t value) {
  3088. std::stringstream ss;
  3089. ss << std::hex << std::uppercase << value;
  3090. return ss.str();
  3091. }
  3092. // Formats an int value as "%X".
  3093. std::string String::FormatHexInt(int value) {
  3094. return FormatHexUInt32(static_cast<uint32_t>(value));
  3095. }
  3096. // Formats a byte as "%02X".
  3097. std::string String::FormatByte(unsigned char value) {
  3098. std::stringstream ss;
  3099. ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
  3100. << static_cast<unsigned int>(value);
  3101. return ss.str();
  3102. }
  3103. // Converts the buffer in a stringstream to an std::string, converting NUL
  3104. // bytes to "\\0" along the way.
  3105. std::string StringStreamToString(::std::stringstream* ss) {
  3106. const ::std::string& str = ss->str();
  3107. const char* const start = str.c_str();
  3108. const char* const end = start + str.length();
  3109. std::string result;
  3110. result.reserve(static_cast<size_t>(2 * (end - start)));
  3111. for (const char* ch = start; ch != end; ++ch) {
  3112. if (*ch == '\0') {
  3113. result += "\\0"; // Replaces NUL with "\\0";
  3114. } else {
  3115. result += *ch;
  3116. }
  3117. }
  3118. return result;
  3119. }
  3120. // Appends the user-supplied message to the Google-Test-generated message.
  3121. std::string AppendUserMessage(const std::string& gtest_msg,
  3122. const Message& user_msg) {
  3123. // Appends the user message if it's non-empty.
  3124. const std::string user_msg_string = user_msg.GetString();
  3125. if (user_msg_string.empty()) {
  3126. return gtest_msg;
  3127. }
  3128. if (gtest_msg.empty()) {
  3129. return user_msg_string;
  3130. }
  3131. return gtest_msg + "\n" + user_msg_string;
  3132. }
  3133. } // namespace internal
  3134. // class TestResult
  3135. // Creates an empty TestResult.
  3136. TestResult::TestResult()
  3137. : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
  3138. // D'tor.
  3139. TestResult::~TestResult() {
  3140. }
  3141. // Returns the i-th test part result among all the results. i can
  3142. // range from 0 to total_part_count() - 1. If i is not in that range,
  3143. // aborts the program.
  3144. const TestPartResult& TestResult::GetTestPartResult(int i) const {
  3145. if (i < 0 || i >= total_part_count())
  3146. internal::posix::Abort();
  3147. return test_part_results_.at(static_cast<size_t>(i));
  3148. }
  3149. // Returns the i-th test property. i can range from 0 to
  3150. // test_property_count() - 1. If i is not in that range, aborts the
  3151. // program.
  3152. const TestProperty& TestResult::GetTestProperty(int i) const {
  3153. if (i < 0 || i >= test_property_count())
  3154. internal::posix::Abort();
  3155. return test_properties_.at(static_cast<size_t>(i));
  3156. }
  3157. // Clears the test part results.
  3158. void TestResult::ClearTestPartResults() {
  3159. test_part_results_.clear();
  3160. }
  3161. // Adds a test part result to the list.
  3162. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
  3163. test_part_results_.push_back(test_part_result);
  3164. }
  3165. // Adds a test property to the list. If a property with the same key as the
  3166. // supplied property is already represented, the value of this test_property
  3167. // replaces the old value for that key.
  3168. void TestResult::RecordProperty(const std::string& xml_element,
  3169. const TestProperty& test_property) {
  3170. if (!ValidateTestProperty(xml_element, test_property)) {
  3171. return;
  3172. }
  3173. internal::MutexLock lock(&test_properties_mutex_);
  3174. const std::vector<TestProperty>::iterator property_with_matching_key =
  3175. std::find_if(test_properties_.begin(), test_properties_.end(),
  3176. internal::TestPropertyKeyIs(test_property.key()));
  3177. if (property_with_matching_key == test_properties_.end()) {
  3178. test_properties_.push_back(test_property);
  3179. return;
  3180. }
  3181. property_with_matching_key->SetValue(test_property.value());
  3182. }
  3183. // The list of reserved attributes used in the <testsuites> element of XML
  3184. // output.
  3185. static const char* const kReservedTestSuitesAttributes[] = {
  3186. "disabled",
  3187. "errors",
  3188. "failures",
  3189. "name",
  3190. "random_seed",
  3191. "tests",
  3192. "time",
  3193. "timestamp"
  3194. };
  3195. // The list of reserved attributes used in the <testsuite> element of XML
  3196. // output.
  3197. static const char* const kReservedTestSuiteAttributes[] = {
  3198. "disabled", "errors", "failures", "name",
  3199. "tests", "time", "timestamp", "skipped"};
  3200. // The list of reserved attributes used in the <testcase> element of XML output.
  3201. static const char* const kReservedTestCaseAttributes[] = {
  3202. "classname", "name", "status", "time", "type_param",
  3203. "value_param", "file", "line"};
  3204. // Use a slightly different set for allowed output to ensure existing tests can
  3205. // still RecordProperty("result") or "RecordProperty(timestamp")
  3206. static const char* const kReservedOutputTestCaseAttributes[] = {
  3207. "classname", "name", "status", "time", "type_param",
  3208. "value_param", "file", "line", "result", "timestamp"};
  3209. template <size_t kSize>
  3210. std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
  3211. return std::vector<std::string>(array, array + kSize);
  3212. }
  3213. static std::vector<std::string> GetReservedAttributesForElement(
  3214. const std::string& xml_element) {
  3215. if (xml_element == "testsuites") {
  3216. return ArrayAsVector(kReservedTestSuitesAttributes);
  3217. } else if (xml_element == "testsuite") {
  3218. return ArrayAsVector(kReservedTestSuiteAttributes);
  3219. } else if (xml_element == "testcase") {
  3220. return ArrayAsVector(kReservedTestCaseAttributes);
  3221. } else {
  3222. GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
  3223. }
  3224. // This code is unreachable but some compilers may not realizes that.
  3225. return std::vector<std::string>();
  3226. }
  3227. // TODO(jdesprez): Merge the two getReserved attributes once skip is improved
  3228. static std::vector<std::string> GetReservedOutputAttributesForElement(
  3229. const std::string& xml_element) {
  3230. if (xml_element == "testsuites") {
  3231. return ArrayAsVector(kReservedTestSuitesAttributes);
  3232. } else if (xml_element == "testsuite") {
  3233. return ArrayAsVector(kReservedTestSuiteAttributes);
  3234. } else if (xml_element == "testcase") {
  3235. return ArrayAsVector(kReservedOutputTestCaseAttributes);
  3236. } else {
  3237. GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
  3238. }
  3239. // This code is unreachable but some compilers may not realizes that.
  3240. return std::vector<std::string>();
  3241. }
  3242. static std::string FormatWordList(const std::vector<std::string>& words) {
  3243. Message word_list;
  3244. for (size_t i = 0; i < words.size(); ++i) {
  3245. if (i > 0 && words.size() > 2) {
  3246. word_list << ", ";
  3247. }
  3248. if (i == words.size() - 1) {
  3249. word_list << "and ";
  3250. }
  3251. word_list << "'" << words[i] << "'";
  3252. }
  3253. return word_list.GetString();
  3254. }
  3255. static bool ValidateTestPropertyName(
  3256. const std::string& property_name,
  3257. const std::vector<std::string>& reserved_names) {
  3258. if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
  3259. reserved_names.end()) {
  3260. ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
  3261. << " (" << FormatWordList(reserved_names)
  3262. << " are reserved by " << GTEST_NAME_ << ")";
  3263. return false;
  3264. }
  3265. return true;
  3266. }
  3267. // Adds a failure if the key is a reserved attribute of the element named
  3268. // xml_element. Returns true if the property is valid.
  3269. bool TestResult::ValidateTestProperty(const std::string& xml_element,
  3270. const TestProperty& test_property) {
  3271. return ValidateTestPropertyName(test_property.key(),
  3272. GetReservedAttributesForElement(xml_element));
  3273. }
  3274. // Clears the object.
  3275. void TestResult::Clear() {
  3276. test_part_results_.clear();
  3277. test_properties_.clear();
  3278. death_test_count_ = 0;
  3279. elapsed_time_ = 0;
  3280. }
  3281. // Returns true off the test part was skipped.
  3282. static bool TestPartSkipped(const TestPartResult& result) {
  3283. return result.skipped();
  3284. }
  3285. // Returns true if and only if the test was skipped.
  3286. bool TestResult::Skipped() const {
  3287. return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
  3288. }
  3289. // Returns true if and only if the test failed.
  3290. bool TestResult::Failed() const {
  3291. for (int i = 0; i < total_part_count(); ++i) {
  3292. if (GetTestPartResult(i).failed())
  3293. return true;
  3294. }
  3295. return false;
  3296. }
  3297. // Returns true if and only if the test part fatally failed.
  3298. static bool TestPartFatallyFailed(const TestPartResult& result) {
  3299. return result.fatally_failed();
  3300. }
  3301. // Returns true if and only if the test fatally failed.
  3302. bool TestResult::HasFatalFailure() const {
  3303. return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
  3304. }
  3305. // Returns true if and only if the test part non-fatally failed.
  3306. static bool TestPartNonfatallyFailed(const TestPartResult& result) {
  3307. return result.nonfatally_failed();
  3308. }
  3309. // Returns true if and only if the test has a non-fatal failure.
  3310. bool TestResult::HasNonfatalFailure() const {
  3311. return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
  3312. }
  3313. // Gets the number of all test parts. This is the sum of the number
  3314. // of successful test parts and the number of failed test parts.
  3315. int TestResult::total_part_count() const {
  3316. return static_cast<int>(test_part_results_.size());
  3317. }
  3318. // Returns the number of the test properties.
  3319. int TestResult::test_property_count() const {
  3320. return static_cast<int>(test_properties_.size());
  3321. }
  3322. // class Test
  3323. // Creates a Test object.
  3324. // The c'tor saves the states of all flags.
  3325. Test::Test()
  3326. : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
  3327. }
  3328. // The d'tor restores the states of all flags. The actual work is
  3329. // done by the d'tor of the gtest_flag_saver_ field, and thus not
  3330. // visible here.
  3331. Test::~Test() {
  3332. }
  3333. // Sets up the test fixture.
  3334. //
  3335. // A sub-class may override this.
  3336. void Test::SetUp() {
  3337. }
  3338. // Tears down the test fixture.
  3339. //
  3340. // A sub-class may override this.
  3341. void Test::TearDown() {
  3342. }
  3343. // Allows user supplied key value pairs to be recorded for later output.
  3344. void Test::RecordProperty(const std::string& key, const std::string& value) {
  3345. UnitTest::GetInstance()->RecordProperty(key, value);
  3346. }
  3347. // Allows user supplied key value pairs to be recorded for later output.
  3348. void Test::RecordProperty(const std::string& key, int value) {
  3349. Message value_message;
  3350. value_message << value;
  3351. RecordProperty(key, value_message.GetString().c_str());
  3352. }
  3353. namespace internal {
  3354. void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  3355. const std::string& message) {
  3356. // This function is a friend of UnitTest and as such has access to
  3357. // AddTestPartResult.
  3358. UnitTest::GetInstance()->AddTestPartResult(
  3359. result_type,
  3360. nullptr, // No info about the source file where the exception occurred.
  3361. -1, // We have no info on which line caused the exception.
  3362. message,
  3363. ""); // No stack trace, either.
  3364. }
  3365. } // namespace internal
  3366. // Google Test requires all tests in the same test suite to use the same test
  3367. // fixture class. This function checks if the current test has the
  3368. // same fixture class as the first test in the current test suite. If
  3369. // yes, it returns true; otherwise it generates a Google Test failure and
  3370. // returns false.
  3371. bool Test::HasSameFixtureClass() {
  3372. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3373. const TestSuite* const test_suite = impl->current_test_suite();
  3374. // Info about the first test in the current test suite.
  3375. const TestInfo* const first_test_info = test_suite->test_info_list()[0];
  3376. const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
  3377. const char* const first_test_name = first_test_info->name();
  3378. // Info about the current test.
  3379. const TestInfo* const this_test_info = impl->current_test_info();
  3380. const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
  3381. const char* const this_test_name = this_test_info->name();
  3382. if (this_fixture_id != first_fixture_id) {
  3383. // Is the first test defined using TEST?
  3384. const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
  3385. // Is this test defined using TEST?
  3386. const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
  3387. if (first_is_TEST || this_is_TEST) {
  3388. // Both TEST and TEST_F appear in same test suite, which is incorrect.
  3389. // Tell the user how to fix this.
  3390. // Gets the name of the TEST and the name of the TEST_F. Note
  3391. // that first_is_TEST and this_is_TEST cannot both be true, as
  3392. // the fixture IDs are different for the two tests.
  3393. const char* const TEST_name =
  3394. first_is_TEST ? first_test_name : this_test_name;
  3395. const char* const TEST_F_name =
  3396. first_is_TEST ? this_test_name : first_test_name;
  3397. ADD_FAILURE()
  3398. << "All tests in the same test suite must use the same test fixture\n"
  3399. << "class, so mixing TEST_F and TEST in the same test suite is\n"
  3400. << "illegal. In test suite " << this_test_info->test_suite_name()
  3401. << ",\n"
  3402. << "test " << TEST_F_name << " is defined using TEST_F but\n"
  3403. << "test " << TEST_name << " is defined using TEST. You probably\n"
  3404. << "want to change the TEST to TEST_F or move it to another test\n"
  3405. << "case.";
  3406. } else {
  3407. // Two fixture classes with the same name appear in two different
  3408. // namespaces, which is not allowed. Tell the user how to fix this.
  3409. ADD_FAILURE()
  3410. << "All tests in the same test suite must use the same test fixture\n"
  3411. << "class. However, in test suite "
  3412. << this_test_info->test_suite_name() << ",\n"
  3413. << "you defined test " << first_test_name << " and test "
  3414. << this_test_name << "\n"
  3415. << "using two different test fixture classes. This can happen if\n"
  3416. << "the two classes are from different namespaces or translation\n"
  3417. << "units and have the same name. You should probably rename one\n"
  3418. << "of the classes to put the tests into different test suites.";
  3419. }
  3420. return false;
  3421. }
  3422. return true;
  3423. }
  3424. #if GTEST_HAS_SEH
  3425. // Adds an "exception thrown" fatal failure to the current test. This
  3426. // function returns its result via an output parameter pointer because VC++
  3427. // prohibits creation of objects with destructors on stack in functions
  3428. // using __try (see error C2712).
  3429. static std::string* FormatSehExceptionMessage(DWORD exception_code,
  3430. const char* location) {
  3431. Message message;
  3432. message << "SEH exception with code 0x" << std::setbase(16) <<
  3433. exception_code << std::setbase(10) << " thrown in " << location << ".";
  3434. return new std::string(message.GetString());
  3435. }
  3436. #endif // GTEST_HAS_SEH
  3437. namespace internal {
  3438. #if GTEST_HAS_EXCEPTIONS
  3439. // Adds an "exception thrown" fatal failure to the current test.
  3440. static std::string FormatCxxExceptionMessage(const char* description,
  3441. const char* location) {
  3442. Message message;
  3443. if (description != nullptr) {
  3444. message << "C++ exception with description \"" << description << "\"";
  3445. } else {
  3446. message << "Unknown C++ exception";
  3447. }
  3448. message << " thrown in " << location << ".";
  3449. return message.GetString();
  3450. }
  3451. static std::string PrintTestPartResultToString(
  3452. const TestPartResult& test_part_result);
  3453. GoogleTestFailureException::GoogleTestFailureException(
  3454. const TestPartResult& failure)
  3455. : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
  3456. #endif // GTEST_HAS_EXCEPTIONS
  3457. // We put these helper functions in the internal namespace as IBM's xlC
  3458. // compiler rejects the code if they were declared static.
  3459. // Runs the given method and handles SEH exceptions it throws, when
  3460. // SEH is supported; returns the 0-value for type Result in case of an
  3461. // SEH exception. (Microsoft compilers cannot handle SEH and C++
  3462. // exceptions in the same function. Therefore, we provide a separate
  3463. // wrapper function for handling SEH exceptions.)
  3464. template <class T, typename Result>
  3465. Result HandleSehExceptionsInMethodIfSupported(
  3466. T* object, Result (T::*method)(), const char* location) {
  3467. #if GTEST_HAS_SEH
  3468. __try {
  3469. return (object->*method)();
  3470. } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
  3471. GetExceptionCode())) {
  3472. // We create the exception message on the heap because VC++ prohibits
  3473. // creation of objects with destructors on stack in functions using __try
  3474. // (see error C2712).
  3475. std::string* exception_message = FormatSehExceptionMessage(
  3476. GetExceptionCode(), location);
  3477. internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
  3478. *exception_message);
  3479. delete exception_message;
  3480. return static_cast<Result>(0);
  3481. }
  3482. #else
  3483. (void)location;
  3484. return (object->*method)();
  3485. #endif // GTEST_HAS_SEH
  3486. }
  3487. // Runs the given method and catches and reports C++ and/or SEH-style
  3488. // exceptions, if they are supported; returns the 0-value for type
  3489. // Result in case of an SEH exception.
  3490. template <class T, typename Result>
  3491. Result HandleExceptionsInMethodIfSupported(
  3492. T* object, Result (T::*method)(), const char* location) {
  3493. // NOTE: The user code can affect the way in which Google Test handles
  3494. // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
  3495. // RUN_ALL_TESTS() starts. It is technically possible to check the flag
  3496. // after the exception is caught and either report or re-throw the
  3497. // exception based on the flag's value:
  3498. //
  3499. // try {
  3500. // // Perform the test method.
  3501. // } catch (...) {
  3502. // if (GTEST_FLAG(catch_exceptions))
  3503. // // Report the exception as failure.
  3504. // else
  3505. // throw; // Re-throws the original exception.
  3506. // }
  3507. //
  3508. // However, the purpose of this flag is to allow the program to drop into
  3509. // the debugger when the exception is thrown. On most platforms, once the
  3510. // control enters the catch block, the exception origin information is
  3511. // lost and the debugger will stop the program at the point of the
  3512. // re-throw in this function -- instead of at the point of the original
  3513. // throw statement in the code under test. For this reason, we perform
  3514. // the check early, sacrificing the ability to affect Google Test's
  3515. // exception handling in the method where the exception is thrown.
  3516. if (internal::GetUnitTestImpl()->catch_exceptions()) {
  3517. #if GTEST_HAS_EXCEPTIONS
  3518. try {
  3519. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  3520. } catch (const AssertionException&) { // NOLINT
  3521. // This failure was reported already.
  3522. } catch (const internal::GoogleTestFailureException&) { // NOLINT
  3523. // This exception type can only be thrown by a failed Google
  3524. // Test assertion with the intention of letting another testing
  3525. // framework catch it. Therefore we just re-throw it.
  3526. throw;
  3527. } catch (const std::exception& e) { // NOLINT
  3528. internal::ReportFailureInUnknownLocation(
  3529. TestPartResult::kFatalFailure,
  3530. FormatCxxExceptionMessage(e.what(), location));
  3531. } catch (...) { // NOLINT
  3532. internal::ReportFailureInUnknownLocation(
  3533. TestPartResult::kFatalFailure,
  3534. FormatCxxExceptionMessage(nullptr, location));
  3535. }
  3536. return static_cast<Result>(0);
  3537. #else
  3538. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  3539. #endif // GTEST_HAS_EXCEPTIONS
  3540. } else {
  3541. return (object->*method)();
  3542. }
  3543. }
  3544. } // namespace internal
  3545. // Runs the test and updates the test result.
  3546. void Test::Run() {
  3547. if (!HasSameFixtureClass()) return;
  3548. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3549. impl->os_stack_trace_getter()->UponLeavingGTest();
  3550. internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
  3551. // We will run the test only if SetUp() was successful and didn't call
  3552. // GTEST_SKIP().
  3553. if (!HasFatalFailure() && !IsSkipped()) {
  3554. impl->os_stack_trace_getter()->UponLeavingGTest();
  3555. internal::HandleExceptionsInMethodIfSupported(
  3556. this, &Test::TestBody, "the test body");
  3557. }
  3558. // However, we want to clean up as much as possible. Hence we will
  3559. // always call TearDown(), even if SetUp() or the test body has
  3560. // failed.
  3561. impl->os_stack_trace_getter()->UponLeavingGTest();
  3562. internal::HandleExceptionsInMethodIfSupported(
  3563. this, &Test::TearDown, "TearDown()");
  3564. }
  3565. // Returns true if and only if the current test has a fatal failure.
  3566. bool Test::HasFatalFailure() {
  3567. return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
  3568. }
  3569. // Returns true if and only if the current test has a non-fatal failure.
  3570. bool Test::HasNonfatalFailure() {
  3571. return internal::GetUnitTestImpl()->current_test_result()->
  3572. HasNonfatalFailure();
  3573. }
  3574. // Returns true if and only if the current test was skipped.
  3575. bool Test::IsSkipped() {
  3576. return internal::GetUnitTestImpl()->current_test_result()->Skipped();
  3577. }
  3578. // class TestInfo
  3579. // Constructs a TestInfo object. It assumes ownership of the test factory
  3580. // object.
  3581. TestInfo::TestInfo(const std::string& a_test_suite_name,
  3582. const std::string& a_name, const char* a_type_param,
  3583. const char* a_value_param,
  3584. internal::CodeLocation a_code_location,
  3585. internal::TypeId fixture_class_id,
  3586. internal::TestFactoryBase* factory)
  3587. : test_suite_name_(a_test_suite_name),
  3588. name_(a_name),
  3589. type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
  3590. value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
  3591. location_(a_code_location),
  3592. fixture_class_id_(fixture_class_id),
  3593. should_run_(false),
  3594. is_disabled_(false),
  3595. matches_filter_(false),
  3596. is_in_another_shard_(false),
  3597. factory_(factory),
  3598. result_() {}
  3599. // Destructs a TestInfo object.
  3600. TestInfo::~TestInfo() { delete factory_; }
  3601. namespace internal {
  3602. // Creates a new TestInfo object and registers it with Google Test;
  3603. // returns the created object.
  3604. //
  3605. // Arguments:
  3606. //
  3607. // test_suite_name: name of the test suite
  3608. // name: name of the test
  3609. // type_param: the name of the test's type parameter, or NULL if
  3610. // this is not a typed or a type-parameterized test.
  3611. // value_param: text representation of the test's value parameter,
  3612. // or NULL if this is not a value-parameterized test.
  3613. // code_location: code location where the test is defined
  3614. // fixture_class_id: ID of the test fixture class
  3615. // set_up_tc: pointer to the function that sets up the test suite
  3616. // tear_down_tc: pointer to the function that tears down the test suite
  3617. // factory: pointer to the factory that creates a test object.
  3618. // The newly created TestInfo instance will assume
  3619. // ownership of the factory object.
  3620. TestInfo* MakeAndRegisterTestInfo(
  3621. const char* test_suite_name, const char* name, const char* type_param,
  3622. const char* value_param, CodeLocation code_location,
  3623. TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
  3624. TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
  3625. TestInfo* const test_info =
  3626. new TestInfo(test_suite_name, name, type_param, value_param,
  3627. code_location, fixture_class_id, factory);
  3628. GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
  3629. return test_info;
  3630. }
  3631. void ReportInvalidTestSuiteType(const char* test_suite_name,
  3632. CodeLocation code_location) {
  3633. Message errors;
  3634. errors
  3635. << "Attempted redefinition of test suite " << test_suite_name << ".\n"
  3636. << "All tests in the same test suite must use the same test fixture\n"
  3637. << "class. However, in test suite " << test_suite_name << ", you tried\n"
  3638. << "to define a test using a fixture class different from the one\n"
  3639. << "used earlier. This can happen if the two fixture classes are\n"
  3640. << "from different namespaces and have the same name. You should\n"
  3641. << "probably rename one of the classes to put the tests into different\n"
  3642. << "test suites.";
  3643. GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
  3644. code_location.line)
  3645. << " " << errors.GetString();
  3646. }
  3647. } // namespace internal
  3648. namespace {
  3649. // A predicate that checks the test name of a TestInfo against a known
  3650. // value.
  3651. //
  3652. // This is used for implementation of the TestSuite class only. We put
  3653. // it in the anonymous namespace to prevent polluting the outer
  3654. // namespace.
  3655. //
  3656. // TestNameIs is copyable.
  3657. class TestNameIs {
  3658. public:
  3659. // Constructor.
  3660. //
  3661. // TestNameIs has NO default constructor.
  3662. explicit TestNameIs(const char* name)
  3663. : name_(name) {}
  3664. // Returns true if and only if the test name of test_info matches name_.
  3665. bool operator()(const TestInfo * test_info) const {
  3666. return test_info && test_info->name() == name_;
  3667. }
  3668. private:
  3669. std::string name_;
  3670. };
  3671. } // namespace
  3672. namespace internal {
  3673. // This method expands all parameterized tests registered with macros TEST_P
  3674. // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
  3675. // This will be done just once during the program runtime.
  3676. void UnitTestImpl::RegisterParameterizedTests() {
  3677. if (!parameterized_tests_registered_) {
  3678. parameterized_test_registry_.RegisterTests();
  3679. type_parameterized_test_registry_.CheckForInstantiations();
  3680. parameterized_tests_registered_ = true;
  3681. }
  3682. }
  3683. } // namespace internal
  3684. // Creates the test object, runs it, records its result, and then
  3685. // deletes it.
  3686. void TestInfo::Run() {
  3687. if (!should_run_) return;
  3688. // Tells UnitTest where to store test result.
  3689. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3690. impl->set_current_test_info(this);
  3691. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3692. // Notifies the unit test event listeners that a test is about to start.
  3693. repeater->OnTestStart(*this);
  3694. result_.set_start_timestamp(internal::GetTimeInMillis());
  3695. internal::Timer timer;
  3696. impl->os_stack_trace_getter()->UponLeavingGTest();
  3697. // Creates the test object.
  3698. Test* const test = internal::HandleExceptionsInMethodIfSupported(
  3699. factory_, &internal::TestFactoryBase::CreateTest,
  3700. "the test fixture's constructor");
  3701. // Runs the test if the constructor didn't generate a fatal failure or invoke
  3702. // GTEST_SKIP().
  3703. // Note that the object will not be null
  3704. if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
  3705. // This doesn't throw as all user code that can throw are wrapped into
  3706. // exception handling code.
  3707. test->Run();
  3708. }
  3709. if (test != nullptr) {
  3710. // Deletes the test object.
  3711. impl->os_stack_trace_getter()->UponLeavingGTest();
  3712. internal::HandleExceptionsInMethodIfSupported(
  3713. test, &Test::DeleteSelf_, "the test fixture's destructor");
  3714. }
  3715. result_.set_elapsed_time(timer.Elapsed());
  3716. // Notifies the unit test event listener that a test has just finished.
  3717. repeater->OnTestEnd(*this);
  3718. // Tells UnitTest to stop associating assertion results to this
  3719. // test.
  3720. impl->set_current_test_info(nullptr);
  3721. }
  3722. // Skip and records a skipped test result for this object.
  3723. void TestInfo::Skip() {
  3724. if (!should_run_) return;
  3725. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3726. impl->set_current_test_info(this);
  3727. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3728. // Notifies the unit test event listeners that a test is about to start.
  3729. repeater->OnTestStart(*this);
  3730. const TestPartResult test_part_result =
  3731. TestPartResult(TestPartResult::kSkip, this->file(), this->line(), "");
  3732. impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
  3733. test_part_result);
  3734. // Notifies the unit test event listener that a test has just finished.
  3735. repeater->OnTestEnd(*this);
  3736. impl->set_current_test_info(nullptr);
  3737. }
  3738. // class TestSuite
  3739. // Gets the number of successful tests in this test suite.
  3740. int TestSuite::successful_test_count() const {
  3741. return CountIf(test_info_list_, TestPassed);
  3742. }
  3743. // Gets the number of successful tests in this test suite.
  3744. int TestSuite::skipped_test_count() const {
  3745. return CountIf(test_info_list_, TestSkipped);
  3746. }
  3747. // Gets the number of failed tests in this test suite.
  3748. int TestSuite::failed_test_count() const {
  3749. return CountIf(test_info_list_, TestFailed);
  3750. }
  3751. // Gets the number of disabled tests that will be reported in the XML report.
  3752. int TestSuite::reportable_disabled_test_count() const {
  3753. return CountIf(test_info_list_, TestReportableDisabled);
  3754. }
  3755. // Gets the number of disabled tests in this test suite.
  3756. int TestSuite::disabled_test_count() const {
  3757. return CountIf(test_info_list_, TestDisabled);
  3758. }
  3759. // Gets the number of tests to be printed in the XML report.
  3760. int TestSuite::reportable_test_count() const {
  3761. return CountIf(test_info_list_, TestReportable);
  3762. }
  3763. // Get the number of tests in this test suite that should run.
  3764. int TestSuite::test_to_run_count() const {
  3765. return CountIf(test_info_list_, ShouldRunTest);
  3766. }
  3767. // Gets the number of all tests.
  3768. int TestSuite::total_test_count() const {
  3769. return static_cast<int>(test_info_list_.size());
  3770. }
  3771. // Creates a TestSuite with the given name.
  3772. //
  3773. // Arguments:
  3774. //
  3775. // a_name: name of the test suite
  3776. // a_type_param: the name of the test suite's type parameter, or NULL if
  3777. // this is not a typed or a type-parameterized test suite.
  3778. // set_up_tc: pointer to the function that sets up the test suite
  3779. // tear_down_tc: pointer to the function that tears down the test suite
  3780. TestSuite::TestSuite(const char* a_name, const char* a_type_param,
  3781. internal::SetUpTestSuiteFunc set_up_tc,
  3782. internal::TearDownTestSuiteFunc tear_down_tc)
  3783. : name_(a_name),
  3784. type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
  3785. set_up_tc_(set_up_tc),
  3786. tear_down_tc_(tear_down_tc),
  3787. should_run_(false),
  3788. start_timestamp_(0),
  3789. elapsed_time_(0) {}
  3790. // Destructor of TestSuite.
  3791. TestSuite::~TestSuite() {
  3792. // Deletes every Test in the collection.
  3793. ForEach(test_info_list_, internal::Delete<TestInfo>);
  3794. }
  3795. // Returns the i-th test among all the tests. i can range from 0 to
  3796. // total_test_count() - 1. If i is not in that range, returns NULL.
  3797. const TestInfo* TestSuite::GetTestInfo(int i) const {
  3798. const int index = GetElementOr(test_indices_, i, -1);
  3799. return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
  3800. }
  3801. // Returns the i-th test among all the tests. i can range from 0 to
  3802. // total_test_count() - 1. If i is not in that range, returns NULL.
  3803. TestInfo* TestSuite::GetMutableTestInfo(int i) {
  3804. const int index = GetElementOr(test_indices_, i, -1);
  3805. return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
  3806. }
  3807. // Adds a test to this test suite. Will delete the test upon
  3808. // destruction of the TestSuite object.
  3809. void TestSuite::AddTestInfo(TestInfo* test_info) {
  3810. test_info_list_.push_back(test_info);
  3811. test_indices_.push_back(static_cast<int>(test_indices_.size()));
  3812. }
  3813. // Runs every test in this TestSuite.
  3814. void TestSuite::Run() {
  3815. if (!should_run_) return;
  3816. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3817. impl->set_current_test_suite(this);
  3818. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3819. // Call both legacy and the new API
  3820. repeater->OnTestSuiteStart(*this);
  3821. // Legacy API is deprecated but still available
  3822. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3823. repeater->OnTestCaseStart(*this);
  3824. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3825. impl->os_stack_trace_getter()->UponLeavingGTest();
  3826. internal::HandleExceptionsInMethodIfSupported(
  3827. this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
  3828. start_timestamp_ = internal::GetTimeInMillis();
  3829. internal::Timer timer;
  3830. for (int i = 0; i < total_test_count(); i++) {
  3831. GetMutableTestInfo(i)->Run();
  3832. if (GTEST_FLAG(fail_fast) && GetMutableTestInfo(i)->result()->Failed()) {
  3833. for (int j = i + 1; j < total_test_count(); j++) {
  3834. GetMutableTestInfo(j)->Skip();
  3835. }
  3836. break;
  3837. }
  3838. }
  3839. elapsed_time_ = timer.Elapsed();
  3840. impl->os_stack_trace_getter()->UponLeavingGTest();
  3841. internal::HandleExceptionsInMethodIfSupported(
  3842. this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()");
  3843. // Call both legacy and the new API
  3844. repeater->OnTestSuiteEnd(*this);
  3845. // Legacy API is deprecated but still available
  3846. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3847. repeater->OnTestCaseEnd(*this);
  3848. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3849. impl->set_current_test_suite(nullptr);
  3850. }
  3851. // Skips all tests under this TestSuite.
  3852. void TestSuite::Skip() {
  3853. if (!should_run_) return;
  3854. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3855. impl->set_current_test_suite(this);
  3856. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3857. // Call both legacy and the new API
  3858. repeater->OnTestSuiteStart(*this);
  3859. // Legacy API is deprecated but still available
  3860. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3861. repeater->OnTestCaseStart(*this);
  3862. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3863. for (int i = 0; i < total_test_count(); i++) {
  3864. GetMutableTestInfo(i)->Skip();
  3865. }
  3866. // Call both legacy and the new API
  3867. repeater->OnTestSuiteEnd(*this);
  3868. // Legacy API is deprecated but still available
  3869. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3870. repeater->OnTestCaseEnd(*this);
  3871. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3872. impl->set_current_test_suite(nullptr);
  3873. }
  3874. // Clears the results of all tests in this test suite.
  3875. void TestSuite::ClearResult() {
  3876. ad_hoc_test_result_.Clear();
  3877. ForEach(test_info_list_, TestInfo::ClearTestResult);
  3878. }
  3879. // Shuffles the tests in this test suite.
  3880. void TestSuite::ShuffleTests(internal::Random* random) {
  3881. Shuffle(random, &test_indices_);
  3882. }
  3883. // Restores the test order to before the first shuffle.
  3884. void TestSuite::UnshuffleTests() {
  3885. for (size_t i = 0; i < test_indices_.size(); i++) {
  3886. test_indices_[i] = static_cast<int>(i);
  3887. }
  3888. }
  3889. // Formats a countable noun. Depending on its quantity, either the
  3890. // singular form or the plural form is used. e.g.
  3891. //
  3892. // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
  3893. // FormatCountableNoun(5, "book", "books") returns "5 books".
  3894. static std::string FormatCountableNoun(int count,
  3895. const char * singular_form,
  3896. const char * plural_form) {
  3897. return internal::StreamableToString(count) + " " +
  3898. (count == 1 ? singular_form : plural_form);
  3899. }
  3900. // Formats the count of tests.
  3901. static std::string FormatTestCount(int test_count) {
  3902. return FormatCountableNoun(test_count, "test", "tests");
  3903. }
  3904. // Formats the count of test suites.
  3905. static std::string FormatTestSuiteCount(int test_suite_count) {
  3906. return FormatCountableNoun(test_suite_count, "test suite", "test suites");
  3907. }
  3908. // Converts a TestPartResult::Type enum to human-friendly string
  3909. // representation. Both kNonFatalFailure and kFatalFailure are translated
  3910. // to "Failure", as the user usually doesn't care about the difference
  3911. // between the two when viewing the test result.
  3912. static const char * TestPartResultTypeToString(TestPartResult::Type type) {
  3913. switch (type) {
  3914. case TestPartResult::kSkip:
  3915. return "Skipped\n";
  3916. case TestPartResult::kSuccess:
  3917. return "Success";
  3918. case TestPartResult::kNonFatalFailure:
  3919. case TestPartResult::kFatalFailure:
  3920. #ifdef _MSC_VER
  3921. return "error: ";
  3922. #else
  3923. return "Failure\n";
  3924. #endif
  3925. default:
  3926. return "Unknown result type";
  3927. }
  3928. }
  3929. namespace internal {
  3930. namespace {
  3931. enum class GTestColor { kDefault, kRed, kGreen, kYellow };
  3932. } // namespace
  3933. // Prints a TestPartResult to an std::string.
  3934. static std::string PrintTestPartResultToString(
  3935. const TestPartResult& test_part_result) {
  3936. return (Message()
  3937. << internal::FormatFileLocation(test_part_result.file_name(),
  3938. test_part_result.line_number())
  3939. << " " << TestPartResultTypeToString(test_part_result.type())
  3940. << test_part_result.message()).GetString();
  3941. }
  3942. // Prints a TestPartResult.
  3943. static void PrintTestPartResult(const TestPartResult& test_part_result) {
  3944. const std::string& result =
  3945. PrintTestPartResultToString(test_part_result);
  3946. printf("%s\n", result.c_str());
  3947. fflush(stdout);
  3948. // If the test program runs in Visual Studio or a debugger, the
  3949. // following statements add the test part result message to the Output
  3950. // window such that the user can double-click on it to jump to the
  3951. // corresponding source code location; otherwise they do nothing.
  3952. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3953. // We don't call OutputDebugString*() on Windows Mobile, as printing
  3954. // to stdout is done by OutputDebugString() there already - we don't
  3955. // want the same message printed twice.
  3956. ::OutputDebugStringA(result.c_str());
  3957. ::OutputDebugStringA("\n");
  3958. #endif
  3959. }
  3960. // class PrettyUnitTestResultPrinter
  3961. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
  3962. !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  3963. // Returns the character attribute for the given color.
  3964. static WORD GetColorAttribute(GTestColor color) {
  3965. switch (color) {
  3966. case GTestColor::kRed:
  3967. return FOREGROUND_RED;
  3968. case GTestColor::kGreen:
  3969. return FOREGROUND_GREEN;
  3970. case GTestColor::kYellow:
  3971. return FOREGROUND_RED | FOREGROUND_GREEN;
  3972. default: return 0;
  3973. }
  3974. }
  3975. static int GetBitOffset(WORD color_mask) {
  3976. if (color_mask == 0) return 0;
  3977. int bitOffset = 0;
  3978. while ((color_mask & 1) == 0) {
  3979. color_mask >>= 1;
  3980. ++bitOffset;
  3981. }
  3982. return bitOffset;
  3983. }
  3984. static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
  3985. // Let's reuse the BG
  3986. static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
  3987. BACKGROUND_RED | BACKGROUND_INTENSITY;
  3988. static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
  3989. FOREGROUND_RED | FOREGROUND_INTENSITY;
  3990. const WORD existing_bg = old_color_attrs & background_mask;
  3991. WORD new_color =
  3992. GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
  3993. static const int bg_bitOffset = GetBitOffset(background_mask);
  3994. static const int fg_bitOffset = GetBitOffset(foreground_mask);
  3995. if (((new_color & background_mask) >> bg_bitOffset) ==
  3996. ((new_color & foreground_mask) >> fg_bitOffset)) {
  3997. new_color ^= FOREGROUND_INTENSITY; // invert intensity
  3998. }
  3999. return new_color;
  4000. }
  4001. #else
  4002. // Returns the ANSI color code for the given color. GTestColor::kDefault is
  4003. // an invalid input.
  4004. static const char* GetAnsiColorCode(GTestColor color) {
  4005. switch (color) {
  4006. case GTestColor::kRed:
  4007. return "1";
  4008. case GTestColor::kGreen:
  4009. return "2";
  4010. case GTestColor::kYellow:
  4011. return "3";
  4012. default:
  4013. return nullptr;
  4014. }
  4015. }
  4016. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  4017. // Returns true if and only if Google Test should use colors in the output.
  4018. bool ShouldUseColor(bool stdout_is_tty) {
  4019. const char* const gtest_color = GTEST_FLAG(color).c_str();
  4020. if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
  4021. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
  4022. // On Windows the TERM variable is usually not set, but the
  4023. // console there does support colors.
  4024. return stdout_is_tty;
  4025. #else
  4026. // On non-Windows platforms, we rely on the TERM variable.
  4027. const char* const term = posix::GetEnv("TERM");
  4028. const bool term_supports_color =
  4029. String::CStringEquals(term, "xterm") ||
  4030. String::CStringEquals(term, "xterm-color") ||
  4031. String::CStringEquals(term, "xterm-256color") ||
  4032. String::CStringEquals(term, "screen") ||
  4033. String::CStringEquals(term, "screen-256color") ||
  4034. String::CStringEquals(term, "tmux") ||
  4035. String::CStringEquals(term, "tmux-256color") ||
  4036. String::CStringEquals(term, "rxvt-unicode") ||
  4037. String::CStringEquals(term, "rxvt-unicode-256color") ||
  4038. String::CStringEquals(term, "linux") ||
  4039. String::CStringEquals(term, "cygwin");
  4040. return stdout_is_tty && term_supports_color;
  4041. #endif // GTEST_OS_WINDOWS
  4042. }
  4043. return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
  4044. String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
  4045. String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
  4046. String::CStringEquals(gtest_color, "1");
  4047. // We take "yes", "true", "t", and "1" as meaning "yes". If the
  4048. // value is neither one of these nor "auto", we treat it as "no" to
  4049. // be conservative.
  4050. }
  4051. // Helpers for printing colored strings to stdout. Note that on Windows, we
  4052. // cannot simply emit special characters and have the terminal change colors.
  4053. // This routine must actually emit the characters rather than return a string
  4054. // that would be colored when printed, as can be done on Linux.
  4055. GTEST_ATTRIBUTE_PRINTF_(2, 3)
  4056. static void ColoredPrintf(GTestColor color, const char *fmt, ...) {
  4057. va_list args;
  4058. va_start(args, fmt);
  4059. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
  4060. GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)
  4061. const bool use_color = AlwaysFalse();
  4062. #else
  4063. static const bool in_color_mode =
  4064. ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
  4065. const bool use_color = in_color_mode && (color != GTestColor::kDefault);
  4066. #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
  4067. if (!use_color) {
  4068. vprintf(fmt, args);
  4069. va_end(args);
  4070. return;
  4071. }
  4072. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
  4073. !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  4074. const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  4075. // Gets the current text color.
  4076. CONSOLE_SCREEN_BUFFER_INFO buffer_info;
  4077. GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
  4078. const WORD old_color_attrs = buffer_info.wAttributes;
  4079. const WORD new_color = GetNewColor(color, old_color_attrs);
  4080. // We need to flush the stream buffers into the console before each
  4081. // SetConsoleTextAttribute call lest it affect the text that is already
  4082. // printed but has not yet reached the console.
  4083. fflush(stdout);
  4084. SetConsoleTextAttribute(stdout_handle, new_color);
  4085. vprintf(fmt, args);
  4086. fflush(stdout);
  4087. // Restores the text color.
  4088. SetConsoleTextAttribute(stdout_handle, old_color_attrs);
  4089. #else
  4090. printf("\033[0;3%sm", GetAnsiColorCode(color));
  4091. vprintf(fmt, args);
  4092. printf("\033[m"); // Resets the terminal to default.
  4093. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  4094. va_end(args);
  4095. }
  4096. // Text printed in Google Test's text output and --gtest_list_tests
  4097. // output to label the type parameter and value parameter for a test.
  4098. static const char kTypeParamLabel[] = "TypeParam";
  4099. static const char kValueParamLabel[] = "GetParam()";
  4100. static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
  4101. const char* const type_param = test_info.type_param();
  4102. const char* const value_param = test_info.value_param();
  4103. if (type_param != nullptr || value_param != nullptr) {
  4104. printf(", where ");
  4105. if (type_param != nullptr) {
  4106. printf("%s = %s", kTypeParamLabel, type_param);
  4107. if (value_param != nullptr) printf(" and ");
  4108. }
  4109. if (value_param != nullptr) {
  4110. printf("%s = %s", kValueParamLabel, value_param);
  4111. }
  4112. }
  4113. }
  4114. // This class implements the TestEventListener interface.
  4115. //
  4116. // Class PrettyUnitTestResultPrinter is copyable.
  4117. class PrettyUnitTestResultPrinter : public TestEventListener {
  4118. public:
  4119. PrettyUnitTestResultPrinter() {}
  4120. static void PrintTestName(const char* test_suite, const char* test) {
  4121. printf("%s.%s", test_suite, test);
  4122. }
  4123. // The following methods override what's in the TestEventListener class.
  4124. void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
  4125. void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
  4126. void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
  4127. void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
  4128. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4129. void OnTestCaseStart(const TestCase& test_case) override;
  4130. #else
  4131. void OnTestSuiteStart(const TestSuite& test_suite) override;
  4132. #endif // OnTestCaseStart
  4133. void OnTestStart(const TestInfo& test_info) override;
  4134. void OnTestPartResult(const TestPartResult& result) override;
  4135. void OnTestEnd(const TestInfo& test_info) override;
  4136. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4137. void OnTestCaseEnd(const TestCase& test_case) override;
  4138. #else
  4139. void OnTestSuiteEnd(const TestSuite& test_suite) override;
  4140. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4141. void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
  4142. void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
  4143. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  4144. void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
  4145. private:
  4146. static void PrintFailedTests(const UnitTest& unit_test);
  4147. static void PrintFailedTestSuites(const UnitTest& unit_test);
  4148. static void PrintSkippedTests(const UnitTest& unit_test);
  4149. };
  4150. // Fired before each iteration of tests starts.
  4151. void PrettyUnitTestResultPrinter::OnTestIterationStart(
  4152. const UnitTest& unit_test, int iteration) {
  4153. if (GTEST_FLAG(repeat) != 1)
  4154. printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
  4155. const char* const filter = GTEST_FLAG(filter).c_str();
  4156. // Prints the filter if it's not *. This reminds the user that some
  4157. // tests may be skipped.
  4158. if (!String::CStringEquals(filter, kUniversalFilter)) {
  4159. ColoredPrintf(GTestColor::kYellow, "Note: %s filter = %s\n", GTEST_NAME_,
  4160. filter);
  4161. }
  4162. if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
  4163. const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
  4164. ColoredPrintf(GTestColor::kYellow, "Note: This is test shard %d of %s.\n",
  4165. static_cast<int>(shard_index) + 1,
  4166. internal::posix::GetEnv(kTestTotalShards));
  4167. }
  4168. if (GTEST_FLAG(shuffle)) {
  4169. ColoredPrintf(GTestColor::kYellow,
  4170. "Note: Randomizing tests' orders with a seed of %d .\n",
  4171. unit_test.random_seed());
  4172. }
  4173. ColoredPrintf(GTestColor::kGreen, "[==========] ");
  4174. printf("Running %s from %s.\n",
  4175. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  4176. FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
  4177. fflush(stdout);
  4178. }
  4179. void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
  4180. const UnitTest& /*unit_test*/) {
  4181. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  4182. printf("Global test environment set-up.\n");
  4183. fflush(stdout);
  4184. }
  4185. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4186. void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
  4187. const std::string counts =
  4188. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  4189. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  4190. printf("%s from %s", counts.c_str(), test_case.name());
  4191. if (test_case.type_param() == nullptr) {
  4192. printf("\n");
  4193. } else {
  4194. printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
  4195. }
  4196. fflush(stdout);
  4197. }
  4198. #else
  4199. void PrettyUnitTestResultPrinter::OnTestSuiteStart(
  4200. const TestSuite& test_suite) {
  4201. const std::string counts =
  4202. FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
  4203. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  4204. printf("%s from %s", counts.c_str(), test_suite.name());
  4205. if (test_suite.type_param() == nullptr) {
  4206. printf("\n");
  4207. } else {
  4208. printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
  4209. }
  4210. fflush(stdout);
  4211. }
  4212. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4213. void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
  4214. ColoredPrintf(GTestColor::kGreen, "[ RUN ] ");
  4215. PrintTestName(test_info.test_suite_name(), test_info.name());
  4216. printf("\n");
  4217. fflush(stdout);
  4218. }
  4219. // Called after an assertion failure.
  4220. void PrettyUnitTestResultPrinter::OnTestPartResult(
  4221. const TestPartResult& result) {
  4222. switch (result.type()) {
  4223. // If the test part succeeded, we don't need to do anything.
  4224. case TestPartResult::kSuccess:
  4225. return;
  4226. default:
  4227. // Print failure message from the assertion
  4228. // (e.g. expected this and got that).
  4229. PrintTestPartResult(result);
  4230. fflush(stdout);
  4231. }
  4232. }
  4233. void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  4234. if (test_info.result()->Passed()) {
  4235. ColoredPrintf(GTestColor::kGreen, "[ OK ] ");
  4236. } else if (test_info.result()->Skipped()) {
  4237. ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
  4238. } else {
  4239. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  4240. }
  4241. PrintTestName(test_info.test_suite_name(), test_info.name());
  4242. if (test_info.result()->Failed())
  4243. PrintFullTestCommentIfPresent(test_info);
  4244. if (GTEST_FLAG(print_time)) {
  4245. printf(" (%s ms)\n", internal::StreamableToString(
  4246. test_info.result()->elapsed_time()).c_str());
  4247. } else {
  4248. printf("\n");
  4249. }
  4250. fflush(stdout);
  4251. }
  4252. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4253. void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
  4254. if (!GTEST_FLAG(print_time)) return;
  4255. const std::string counts =
  4256. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  4257. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  4258. printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
  4259. internal::StreamableToString(test_case.elapsed_time()).c_str());
  4260. fflush(stdout);
  4261. }
  4262. #else
  4263. void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
  4264. if (!GTEST_FLAG(print_time)) return;
  4265. const std::string counts =
  4266. FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
  4267. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  4268. printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
  4269. internal::StreamableToString(test_suite.elapsed_time()).c_str());
  4270. fflush(stdout);
  4271. }
  4272. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4273. void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
  4274. const UnitTest& /*unit_test*/) {
  4275. ColoredPrintf(GTestColor::kGreen, "[----------] ");
  4276. printf("Global test environment tear-down\n");
  4277. fflush(stdout);
  4278. }
  4279. // Internal helper for printing the list of failed tests.
  4280. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
  4281. const int failed_test_count = unit_test.failed_test_count();
  4282. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  4283. printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
  4284. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  4285. const TestSuite& test_suite = *unit_test.GetTestSuite(i);
  4286. if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
  4287. continue;
  4288. }
  4289. for (int j = 0; j < test_suite.total_test_count(); ++j) {
  4290. const TestInfo& test_info = *test_suite.GetTestInfo(j);
  4291. if (!test_info.should_run() || !test_info.result()->Failed()) {
  4292. continue;
  4293. }
  4294. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  4295. printf("%s.%s", test_suite.name(), test_info.name());
  4296. PrintFullTestCommentIfPresent(test_info);
  4297. printf("\n");
  4298. }
  4299. }
  4300. printf("\n%2d FAILED %s\n", failed_test_count,
  4301. failed_test_count == 1 ? "TEST" : "TESTS");
  4302. }
  4303. // Internal helper for printing the list of test suite failures not covered by
  4304. // PrintFailedTests.
  4305. void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
  4306. const UnitTest& unit_test) {
  4307. int suite_failure_count = 0;
  4308. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  4309. const TestSuite& test_suite = *unit_test.GetTestSuite(i);
  4310. if (!test_suite.should_run()) {
  4311. continue;
  4312. }
  4313. if (test_suite.ad_hoc_test_result().Failed()) {
  4314. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  4315. printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
  4316. ++suite_failure_count;
  4317. }
  4318. }
  4319. if (suite_failure_count > 0) {
  4320. printf("\n%2d FAILED TEST %s\n", suite_failure_count,
  4321. suite_failure_count == 1 ? "SUITE" : "SUITES");
  4322. }
  4323. }
  4324. // Internal helper for printing the list of skipped tests.
  4325. void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
  4326. const int skipped_test_count = unit_test.skipped_test_count();
  4327. if (skipped_test_count == 0) {
  4328. return;
  4329. }
  4330. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  4331. const TestSuite& test_suite = *unit_test.GetTestSuite(i);
  4332. if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
  4333. continue;
  4334. }
  4335. for (int j = 0; j < test_suite.total_test_count(); ++j) {
  4336. const TestInfo& test_info = *test_suite.GetTestInfo(j);
  4337. if (!test_info.should_run() || !test_info.result()->Skipped()) {
  4338. continue;
  4339. }
  4340. ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
  4341. printf("%s.%s", test_suite.name(), test_info.name());
  4342. printf("\n");
  4343. }
  4344. }
  4345. }
  4346. void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4347. int /*iteration*/) {
  4348. ColoredPrintf(GTestColor::kGreen, "[==========] ");
  4349. printf("%s from %s ran.",
  4350. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  4351. FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
  4352. if (GTEST_FLAG(print_time)) {
  4353. printf(" (%s ms total)",
  4354. internal::StreamableToString(unit_test.elapsed_time()).c_str());
  4355. }
  4356. printf("\n");
  4357. ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
  4358. printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  4359. const int skipped_test_count = unit_test.skipped_test_count();
  4360. if (skipped_test_count > 0) {
  4361. ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
  4362. printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
  4363. PrintSkippedTests(unit_test);
  4364. }
  4365. if (!unit_test.Passed()) {
  4366. PrintFailedTests(unit_test);
  4367. PrintFailedTestSuites(unit_test);
  4368. }
  4369. int num_disabled = unit_test.reportable_disabled_test_count();
  4370. if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
  4371. if (unit_test.Passed()) {
  4372. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
  4373. }
  4374. ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
  4375. num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
  4376. }
  4377. // Ensure that Google Test output is printed before, e.g., heapchecker output.
  4378. fflush(stdout);
  4379. }
  4380. // End PrettyUnitTestResultPrinter
  4381. // This class implements the TestEventListener interface.
  4382. //
  4383. // Class BriefUnitTestResultPrinter is copyable.
  4384. class BriefUnitTestResultPrinter : public TestEventListener {
  4385. public:
  4386. BriefUnitTestResultPrinter() {}
  4387. static void PrintTestName(const char* test_suite, const char* test) {
  4388. printf("%s.%s", test_suite, test);
  4389. }
  4390. // The following methods override what's in the TestEventListener class.
  4391. void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
  4392. void OnTestIterationStart(const UnitTest& /*unit_test*/,
  4393. int /*iteration*/) override {}
  4394. void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
  4395. void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
  4396. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4397. void OnTestCaseStart(const TestCase& /*test_case*/) override {}
  4398. #else
  4399. void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
  4400. #endif // OnTestCaseStart
  4401. void OnTestStart(const TestInfo& /*test_info*/) override {}
  4402. void OnTestPartResult(const TestPartResult& result) override;
  4403. void OnTestEnd(const TestInfo& test_info) override;
  4404. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4405. void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
  4406. #else
  4407. void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
  4408. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4409. void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
  4410. void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
  4411. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  4412. void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
  4413. };
  4414. // Called after an assertion failure.
  4415. void BriefUnitTestResultPrinter::OnTestPartResult(
  4416. const TestPartResult& result) {
  4417. switch (result.type()) {
  4418. // If the test part succeeded, we don't need to do anything.
  4419. case TestPartResult::kSuccess:
  4420. return;
  4421. default:
  4422. // Print failure message from the assertion
  4423. // (e.g. expected this and got that).
  4424. PrintTestPartResult(result);
  4425. fflush(stdout);
  4426. }
  4427. }
  4428. void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  4429. if (test_info.result()->Failed()) {
  4430. ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
  4431. PrintTestName(test_info.test_suite_name(), test_info.name());
  4432. PrintFullTestCommentIfPresent(test_info);
  4433. if (GTEST_FLAG(print_time)) {
  4434. printf(" (%s ms)\n",
  4435. internal::StreamableToString(test_info.result()->elapsed_time())
  4436. .c_str());
  4437. } else {
  4438. printf("\n");
  4439. }
  4440. fflush(stdout);
  4441. }
  4442. }
  4443. void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4444. int /*iteration*/) {
  4445. ColoredPrintf(GTestColor::kGreen, "[==========] ");
  4446. printf("%s from %s ran.",
  4447. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  4448. FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
  4449. if (GTEST_FLAG(print_time)) {
  4450. printf(" (%s ms total)",
  4451. internal::StreamableToString(unit_test.elapsed_time()).c_str());
  4452. }
  4453. printf("\n");
  4454. ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
  4455. printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  4456. const int skipped_test_count = unit_test.skipped_test_count();
  4457. if (skipped_test_count > 0) {
  4458. ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
  4459. printf("%s.\n", FormatTestCount(skipped_test_count).c_str());
  4460. }
  4461. int num_disabled = unit_test.reportable_disabled_test_count();
  4462. if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
  4463. if (unit_test.Passed()) {
  4464. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
  4465. }
  4466. ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
  4467. num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
  4468. }
  4469. // Ensure that Google Test output is printed before, e.g., heapchecker output.
  4470. fflush(stdout);
  4471. }
  4472. // End BriefUnitTestResultPrinter
  4473. // class TestEventRepeater
  4474. //
  4475. // This class forwards events to other event listeners.
  4476. class TestEventRepeater : public TestEventListener {
  4477. public:
  4478. TestEventRepeater() : forwarding_enabled_(true) {}
  4479. ~TestEventRepeater() override;
  4480. void Append(TestEventListener *listener);
  4481. TestEventListener* Release(TestEventListener* listener);
  4482. // Controls whether events will be forwarded to listeners_. Set to false
  4483. // in death test child processes.
  4484. bool forwarding_enabled() const { return forwarding_enabled_; }
  4485. void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
  4486. void OnTestProgramStart(const UnitTest& unit_test) override;
  4487. void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
  4488. void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
  4489. void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
  4490. // Legacy API is deprecated but still available
  4491. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4492. void OnTestCaseStart(const TestSuite& parameter) override;
  4493. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4494. void OnTestSuiteStart(const TestSuite& parameter) override;
  4495. void OnTestStart(const TestInfo& test_info) override;
  4496. void OnTestPartResult(const TestPartResult& result) override;
  4497. void OnTestEnd(const TestInfo& test_info) override;
  4498. // Legacy API is deprecated but still available
  4499. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4500. void OnTestCaseEnd(const TestCase& parameter) override;
  4501. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4502. void OnTestSuiteEnd(const TestSuite& parameter) override;
  4503. void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
  4504. void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
  4505. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  4506. void OnTestProgramEnd(const UnitTest& unit_test) override;
  4507. private:
  4508. // Controls whether events will be forwarded to listeners_. Set to false
  4509. // in death test child processes.
  4510. bool forwarding_enabled_;
  4511. // The list of listeners that receive events.
  4512. std::vector<TestEventListener*> listeners_;
  4513. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
  4514. };
  4515. TestEventRepeater::~TestEventRepeater() {
  4516. ForEach(listeners_, Delete<TestEventListener>);
  4517. }
  4518. void TestEventRepeater::Append(TestEventListener *listener) {
  4519. listeners_.push_back(listener);
  4520. }
  4521. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
  4522. for (size_t i = 0; i < listeners_.size(); ++i) {
  4523. if (listeners_[i] == listener) {
  4524. listeners_.erase(listeners_.begin() + static_cast<int>(i));
  4525. return listener;
  4526. }
  4527. }
  4528. return nullptr;
  4529. }
  4530. // Since most methods are very similar, use macros to reduce boilerplate.
  4531. // This defines a member that forwards the call to all listeners.
  4532. #define GTEST_REPEATER_METHOD_(Name, Type) \
  4533. void TestEventRepeater::Name(const Type& parameter) { \
  4534. if (forwarding_enabled_) { \
  4535. for (size_t i = 0; i < listeners_.size(); i++) { \
  4536. listeners_[i]->Name(parameter); \
  4537. } \
  4538. } \
  4539. }
  4540. // This defines a member that forwards the call to all listeners in reverse
  4541. // order.
  4542. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
  4543. void TestEventRepeater::Name(const Type& parameter) { \
  4544. if (forwarding_enabled_) { \
  4545. for (size_t i = listeners_.size(); i != 0; i--) { \
  4546. listeners_[i - 1]->Name(parameter); \
  4547. } \
  4548. } \
  4549. }
  4550. GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
  4551. GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
  4552. // Legacy API is deprecated but still available
  4553. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4554. GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
  4555. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4556. GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
  4557. GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
  4558. GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
  4559. GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
  4560. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
  4561. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
  4562. GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
  4563. // Legacy API is deprecated but still available
  4564. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4565. GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
  4566. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4567. GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
  4568. GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
  4569. #undef GTEST_REPEATER_METHOD_
  4570. #undef GTEST_REVERSE_REPEATER_METHOD_
  4571. void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
  4572. int iteration) {
  4573. if (forwarding_enabled_) {
  4574. for (size_t i = 0; i < listeners_.size(); i++) {
  4575. listeners_[i]->OnTestIterationStart(unit_test, iteration);
  4576. }
  4577. }
  4578. }
  4579. void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
  4580. int iteration) {
  4581. if (forwarding_enabled_) {
  4582. for (size_t i = listeners_.size(); i > 0; i--) {
  4583. listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration);
  4584. }
  4585. }
  4586. }
  4587. // End TestEventRepeater
  4588. // This class generates an XML output file.
  4589. class XmlUnitTestResultPrinter : public EmptyTestEventListener {
  4590. public:
  4591. explicit XmlUnitTestResultPrinter(const char* output_file);
  4592. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  4593. void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);
  4594. // Prints an XML summary of all unit tests.
  4595. static void PrintXmlTestsList(std::ostream* stream,
  4596. const std::vector<TestSuite*>& test_suites);
  4597. private:
  4598. // Is c a whitespace character that is normalized to a space character
  4599. // when it appears in an XML attribute value?
  4600. static bool IsNormalizableWhitespace(char c) {
  4601. return c == 0x9 || c == 0xA || c == 0xD;
  4602. }
  4603. // May c appear in a well-formed XML document?
  4604. static bool IsValidXmlCharacter(char c) {
  4605. return IsNormalizableWhitespace(c) || c >= 0x20;
  4606. }
  4607. // Returns an XML-escaped copy of the input string str. If
  4608. // is_attribute is true, the text is meant to appear as an attribute
  4609. // value, and normalizable whitespace is preserved by replacing it
  4610. // with character references.
  4611. static std::string EscapeXml(const std::string& str, bool is_attribute);
  4612. // Returns the given string with all characters invalid in XML removed.
  4613. static std::string RemoveInvalidXmlCharacters(const std::string& str);
  4614. // Convenience wrapper around EscapeXml when str is an attribute value.
  4615. static std::string EscapeXmlAttribute(const std::string& str) {
  4616. return EscapeXml(str, true);
  4617. }
  4618. // Convenience wrapper around EscapeXml when str is not an attribute value.
  4619. static std::string EscapeXmlText(const char* str) {
  4620. return EscapeXml(str, false);
  4621. }
  4622. // Verifies that the given attribute belongs to the given element and
  4623. // streams the attribute as XML.
  4624. static void OutputXmlAttribute(std::ostream* stream,
  4625. const std::string& element_name,
  4626. const std::string& name,
  4627. const std::string& value);
  4628. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  4629. static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
  4630. // Streams a test suite XML stanza containing the given test result.
  4631. //
  4632. // Requires: result.Failed()
  4633. static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
  4634. const TestResult& result);
  4635. // Streams an XML representation of a TestResult object.
  4636. static void OutputXmlTestResult(::std::ostream* stream,
  4637. const TestResult& result);
  4638. // Streams an XML representation of a TestInfo object.
  4639. static void OutputXmlTestInfo(::std::ostream* stream,
  4640. const char* test_suite_name,
  4641. const TestInfo& test_info);
  4642. // Prints an XML representation of a TestSuite object
  4643. static void PrintXmlTestSuite(::std::ostream* stream,
  4644. const TestSuite& test_suite);
  4645. // Prints an XML summary of unit_test to output stream out.
  4646. static void PrintXmlUnitTest(::std::ostream* stream,
  4647. const UnitTest& unit_test);
  4648. // Produces a string representing the test properties in a result as space
  4649. // delimited XML attributes based on the property key="value" pairs.
  4650. // When the std::string is not empty, it includes a space at the beginning,
  4651. // to delimit this attribute from prior attributes.
  4652. static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
  4653. // Streams an XML representation of the test properties of a TestResult
  4654. // object.
  4655. static void OutputXmlTestProperties(std::ostream* stream,
  4656. const TestResult& result);
  4657. // The output file.
  4658. const std::string output_file_;
  4659. GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
  4660. };
  4661. // Creates a new XmlUnitTestResultPrinter.
  4662. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
  4663. : output_file_(output_file) {
  4664. if (output_file_.empty()) {
  4665. GTEST_LOG_(FATAL) << "XML output file may not be null";
  4666. }
  4667. }
  4668. // Called after the unit test ends.
  4669. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4670. int /*iteration*/) {
  4671. FILE* xmlout = OpenFileForWriting(output_file_);
  4672. std::stringstream stream;
  4673. PrintXmlUnitTest(&stream, unit_test);
  4674. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  4675. fclose(xmlout);
  4676. }
  4677. void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
  4678. const std::vector<TestSuite*>& test_suites) {
  4679. FILE* xmlout = OpenFileForWriting(output_file_);
  4680. std::stringstream stream;
  4681. PrintXmlTestsList(&stream, test_suites);
  4682. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  4683. fclose(xmlout);
  4684. }
  4685. // Returns an XML-escaped copy of the input string str. If is_attribute
  4686. // is true, the text is meant to appear as an attribute value, and
  4687. // normalizable whitespace is preserved by replacing it with character
  4688. // references.
  4689. //
  4690. // Invalid XML characters in str, if any, are stripped from the output.
  4691. // It is expected that most, if not all, of the text processed by this
  4692. // module will consist of ordinary English text.
  4693. // If this module is ever modified to produce version 1.1 XML output,
  4694. // most invalid characters can be retained using character references.
  4695. std::string XmlUnitTestResultPrinter::EscapeXml(
  4696. const std::string& str, bool is_attribute) {
  4697. Message m;
  4698. for (size_t i = 0; i < str.size(); ++i) {
  4699. const char ch = str[i];
  4700. switch (ch) {
  4701. case '<':
  4702. m << "&lt;";
  4703. break;
  4704. case '>':
  4705. m << "&gt;";
  4706. break;
  4707. case '&':
  4708. m << "&amp;";
  4709. break;
  4710. case '\'':
  4711. if (is_attribute)
  4712. m << "&apos;";
  4713. else
  4714. m << '\'';
  4715. break;
  4716. case '"':
  4717. if (is_attribute)
  4718. m << "&quot;";
  4719. else
  4720. m << '"';
  4721. break;
  4722. default:
  4723. if (IsValidXmlCharacter(ch)) {
  4724. if (is_attribute && IsNormalizableWhitespace(ch))
  4725. m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
  4726. << ";";
  4727. else
  4728. m << ch;
  4729. }
  4730. break;
  4731. }
  4732. }
  4733. return m.GetString();
  4734. }
  4735. // Returns the given string with all characters invalid in XML removed.
  4736. // Currently invalid characters are dropped from the string. An
  4737. // alternative is to replace them with certain characters such as . or ?.
  4738. std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
  4739. const std::string& str) {
  4740. std::string output;
  4741. output.reserve(str.size());
  4742. for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
  4743. if (IsValidXmlCharacter(*it))
  4744. output.push_back(*it);
  4745. return output;
  4746. }
  4747. // The following routines generate an XML representation of a UnitTest
  4748. // object.
  4749. // GOOGLETEST_CM0009 DO NOT DELETE
  4750. //
  4751. // This is how Google Test concepts map to the DTD:
  4752. //
  4753. // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
  4754. // <testsuite name="testcase-name"> <-- corresponds to a TestSuite object
  4755. // <testcase name="test-name"> <-- corresponds to a TestInfo object
  4756. // <failure message="...">...</failure>
  4757. // <failure message="...">...</failure>
  4758. // <failure message="...">...</failure>
  4759. // <-- individual assertion failures
  4760. // </testcase>
  4761. // </testsuite>
  4762. // </testsuites>
  4763. // Formats the given time in milliseconds as seconds.
  4764. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
  4765. ::std::stringstream ss;
  4766. ss << (static_cast<double>(ms) * 1e-3);
  4767. return ss.str();
  4768. }
  4769. static bool PortableLocaltime(time_t seconds, struct tm* out) {
  4770. #if defined(_MSC_VER)
  4771. return localtime_s(out, &seconds) == 0;
  4772. #elif defined(__MINGW32__) || defined(__MINGW64__)
  4773. // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
  4774. // Windows' localtime(), which has a thread-local tm buffer.
  4775. struct tm* tm_ptr = localtime(&seconds); // NOLINT
  4776. if (tm_ptr == nullptr) return false;
  4777. *out = *tm_ptr;
  4778. return true;
  4779. #elif defined(__STDC_LIB_EXT1__)
  4780. // Uses localtime_s when available as localtime_r is only available from
  4781. // C23 standard.
  4782. return localtime_s(&seconds, out) != nullptr;
  4783. #else
  4784. return localtime_r(&seconds, out) != nullptr;
  4785. #endif
  4786. }
  4787. // Converts the given epoch time in milliseconds to a date string in the ISO
  4788. // 8601 format, without the timezone information.
  4789. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
  4790. struct tm time_struct;
  4791. if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  4792. return "";
  4793. // YYYY-MM-DDThh:mm:ss.sss
  4794. return StreamableToString(time_struct.tm_year + 1900) + "-" +
  4795. String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  4796. String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  4797. String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  4798. String::FormatIntWidth2(time_struct.tm_min) + ":" +
  4799. String::FormatIntWidth2(time_struct.tm_sec) + "." +
  4800. String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);
  4801. }
  4802. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  4803. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
  4804. const char* data) {
  4805. const char* segment = data;
  4806. *stream << "<![CDATA[";
  4807. for (;;) {
  4808. const char* const next_segment = strstr(segment, "]]>");
  4809. if (next_segment != nullptr) {
  4810. stream->write(
  4811. segment, static_cast<std::streamsize>(next_segment - segment));
  4812. *stream << "]]>]]&gt;<![CDATA[";
  4813. segment = next_segment + strlen("]]>");
  4814. } else {
  4815. *stream << segment;
  4816. break;
  4817. }
  4818. }
  4819. *stream << "]]>";
  4820. }
  4821. void XmlUnitTestResultPrinter::OutputXmlAttribute(
  4822. std::ostream* stream,
  4823. const std::string& element_name,
  4824. const std::string& name,
  4825. const std::string& value) {
  4826. const std::vector<std::string>& allowed_names =
  4827. GetReservedOutputAttributesForElement(element_name);
  4828. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4829. allowed_names.end())
  4830. << "Attribute " << name << " is not allowed for element <" << element_name
  4831. << ">.";
  4832. *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
  4833. }
  4834. // Streams a test suite XML stanza containing the given test result.
  4835. void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
  4836. ::std::ostream* stream, const TestResult& result) {
  4837. // Output the boilerplate for a minimal test suite with one test.
  4838. *stream << " <testsuite";
  4839. OutputXmlAttribute(stream, "testsuite", "name", "NonTestSuiteFailure");
  4840. OutputXmlAttribute(stream, "testsuite", "tests", "1");
  4841. OutputXmlAttribute(stream, "testsuite", "failures", "1");
  4842. OutputXmlAttribute(stream, "testsuite", "disabled", "0");
  4843. OutputXmlAttribute(stream, "testsuite", "skipped", "0");
  4844. OutputXmlAttribute(stream, "testsuite", "errors", "0");
  4845. OutputXmlAttribute(stream, "testsuite", "time",
  4846. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  4847. OutputXmlAttribute(
  4848. stream, "testsuite", "timestamp",
  4849. FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
  4850. *stream << ">";
  4851. // Output the boilerplate for a minimal test case with a single test.
  4852. *stream << " <testcase";
  4853. OutputXmlAttribute(stream, "testcase", "name", "");
  4854. OutputXmlAttribute(stream, "testcase", "status", "run");
  4855. OutputXmlAttribute(stream, "testcase", "result", "completed");
  4856. OutputXmlAttribute(stream, "testcase", "classname", "");
  4857. OutputXmlAttribute(stream, "testcase", "time",
  4858. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  4859. OutputXmlAttribute(
  4860. stream, "testcase", "timestamp",
  4861. FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
  4862. // Output the actual test result.
  4863. OutputXmlTestResult(stream, result);
  4864. // Complete the test suite.
  4865. *stream << " </testsuite>\n";
  4866. }
  4867. // Prints an XML representation of a TestInfo object.
  4868. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
  4869. const char* test_suite_name,
  4870. const TestInfo& test_info) {
  4871. const TestResult& result = *test_info.result();
  4872. const std::string kTestsuite = "testcase";
  4873. if (test_info.is_in_another_shard()) {
  4874. return;
  4875. }
  4876. *stream << " <testcase";
  4877. OutputXmlAttribute(stream, kTestsuite, "name", test_info.name());
  4878. if (test_info.value_param() != nullptr) {
  4879. OutputXmlAttribute(stream, kTestsuite, "value_param",
  4880. test_info.value_param());
  4881. }
  4882. if (test_info.type_param() != nullptr) {
  4883. OutputXmlAttribute(stream, kTestsuite, "type_param",
  4884. test_info.type_param());
  4885. }
  4886. if (GTEST_FLAG(list_tests)) {
  4887. OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
  4888. OutputXmlAttribute(stream, kTestsuite, "line",
  4889. StreamableToString(test_info.line()));
  4890. *stream << " />\n";
  4891. return;
  4892. }
  4893. OutputXmlAttribute(stream, kTestsuite, "status",
  4894. test_info.should_run() ? "run" : "notrun");
  4895. OutputXmlAttribute(stream, kTestsuite, "result",
  4896. test_info.should_run()
  4897. ? (result.Skipped() ? "skipped" : "completed")
  4898. : "suppressed");
  4899. OutputXmlAttribute(stream, kTestsuite, "time",
  4900. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  4901. OutputXmlAttribute(
  4902. stream, kTestsuite, "timestamp",
  4903. FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
  4904. OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
  4905. OutputXmlTestResult(stream, result);
  4906. }
  4907. void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
  4908. const TestResult& result) {
  4909. int failures = 0;
  4910. int skips = 0;
  4911. for (int i = 0; i < result.total_part_count(); ++i) {
  4912. const TestPartResult& part = result.GetTestPartResult(i);
  4913. if (part.failed()) {
  4914. if (++failures == 1 && skips == 0) {
  4915. *stream << ">\n";
  4916. }
  4917. const std::string location =
  4918. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  4919. part.line_number());
  4920. const std::string summary = location + "\n" + part.summary();
  4921. *stream << " <failure message=\""
  4922. << EscapeXmlAttribute(summary)
  4923. << "\" type=\"\">";
  4924. const std::string detail = location + "\n" + part.message();
  4925. OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
  4926. *stream << "</failure>\n";
  4927. } else if (part.skipped()) {
  4928. if (++skips == 1 && failures == 0) {
  4929. *stream << ">\n";
  4930. }
  4931. const std::string location =
  4932. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  4933. part.line_number());
  4934. const std::string summary = location + "\n" + part.summary();
  4935. *stream << " <skipped message=\""
  4936. << EscapeXmlAttribute(summary.c_str()) << "\">";
  4937. const std::string detail = location + "\n" + part.message();
  4938. OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
  4939. *stream << "</skipped>\n";
  4940. }
  4941. }
  4942. if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
  4943. *stream << " />\n";
  4944. } else {
  4945. if (failures == 0 && skips == 0) {
  4946. *stream << ">\n";
  4947. }
  4948. OutputXmlTestProperties(stream, result);
  4949. *stream << " </testcase>\n";
  4950. }
  4951. }
  4952. // Prints an XML representation of a TestSuite object
  4953. void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
  4954. const TestSuite& test_suite) {
  4955. const std::string kTestsuite = "testsuite";
  4956. *stream << " <" << kTestsuite;
  4957. OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
  4958. OutputXmlAttribute(stream, kTestsuite, "tests",
  4959. StreamableToString(test_suite.reportable_test_count()));
  4960. if (!GTEST_FLAG(list_tests)) {
  4961. OutputXmlAttribute(stream, kTestsuite, "failures",
  4962. StreamableToString(test_suite.failed_test_count()));
  4963. OutputXmlAttribute(
  4964. stream, kTestsuite, "disabled",
  4965. StreamableToString(test_suite.reportable_disabled_test_count()));
  4966. OutputXmlAttribute(stream, kTestsuite, "skipped",
  4967. StreamableToString(test_suite.skipped_test_count()));
  4968. OutputXmlAttribute(stream, kTestsuite, "errors", "0");
  4969. OutputXmlAttribute(stream, kTestsuite, "time",
  4970. FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
  4971. OutputXmlAttribute(
  4972. stream, kTestsuite, "timestamp",
  4973. FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp()));
  4974. *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
  4975. }
  4976. *stream << ">\n";
  4977. for (int i = 0; i < test_suite.total_test_count(); ++i) {
  4978. if (test_suite.GetTestInfo(i)->is_reportable())
  4979. OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
  4980. }
  4981. *stream << " </" << kTestsuite << ">\n";
  4982. }
  4983. // Prints an XML summary of unit_test to output stream out.
  4984. void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
  4985. const UnitTest& unit_test) {
  4986. const std::string kTestsuites = "testsuites";
  4987. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  4988. *stream << "<" << kTestsuites;
  4989. OutputXmlAttribute(stream, kTestsuites, "tests",
  4990. StreamableToString(unit_test.reportable_test_count()));
  4991. OutputXmlAttribute(stream, kTestsuites, "failures",
  4992. StreamableToString(unit_test.failed_test_count()));
  4993. OutputXmlAttribute(
  4994. stream, kTestsuites, "disabled",
  4995. StreamableToString(unit_test.reportable_disabled_test_count()));
  4996. OutputXmlAttribute(stream, kTestsuites, "errors", "0");
  4997. OutputXmlAttribute(stream, kTestsuites, "time",
  4998. FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
  4999. OutputXmlAttribute(
  5000. stream, kTestsuites, "timestamp",
  5001. FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
  5002. if (GTEST_FLAG(shuffle)) {
  5003. OutputXmlAttribute(stream, kTestsuites, "random_seed",
  5004. StreamableToString(unit_test.random_seed()));
  5005. }
  5006. *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
  5007. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  5008. *stream << ">\n";
  5009. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  5010. if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
  5011. PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
  5012. }
  5013. // If there was a test failure outside of one of the test suites (like in a
  5014. // test environment) include that in the output.
  5015. if (unit_test.ad_hoc_test_result().Failed()) {
  5016. OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
  5017. }
  5018. *stream << "</" << kTestsuites << ">\n";
  5019. }
  5020. void XmlUnitTestResultPrinter::PrintXmlTestsList(
  5021. std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
  5022. const std::string kTestsuites = "testsuites";
  5023. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  5024. *stream << "<" << kTestsuites;
  5025. int total_tests = 0;
  5026. for (auto test_suite : test_suites) {
  5027. total_tests += test_suite->total_test_count();
  5028. }
  5029. OutputXmlAttribute(stream, kTestsuites, "tests",
  5030. StreamableToString(total_tests));
  5031. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  5032. *stream << ">\n";
  5033. for (auto test_suite : test_suites) {
  5034. PrintXmlTestSuite(stream, *test_suite);
  5035. }
  5036. *stream << "</" << kTestsuites << ">\n";
  5037. }
  5038. // Produces a string representing the test properties in a result as space
  5039. // delimited XML attributes based on the property key="value" pairs.
  5040. std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
  5041. const TestResult& result) {
  5042. Message attributes;
  5043. for (int i = 0; i < result.test_property_count(); ++i) {
  5044. const TestProperty& property = result.GetTestProperty(i);
  5045. attributes << " " << property.key() << "="
  5046. << "\"" << EscapeXmlAttribute(property.value()) << "\"";
  5047. }
  5048. return attributes.GetString();
  5049. }
  5050. void XmlUnitTestResultPrinter::OutputXmlTestProperties(
  5051. std::ostream* stream, const TestResult& result) {
  5052. const std::string kProperties = "properties";
  5053. const std::string kProperty = "property";
  5054. if (result.test_property_count() <= 0) {
  5055. return;
  5056. }
  5057. *stream << "<" << kProperties << ">\n";
  5058. for (int i = 0; i < result.test_property_count(); ++i) {
  5059. const TestProperty& property = result.GetTestProperty(i);
  5060. *stream << "<" << kProperty;
  5061. *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
  5062. *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
  5063. *stream << "/>\n";
  5064. }
  5065. *stream << "</" << kProperties << ">\n";
  5066. }
  5067. // End XmlUnitTestResultPrinter
  5068. // This class generates an JSON output file.
  5069. class JsonUnitTestResultPrinter : public EmptyTestEventListener {
  5070. public:
  5071. explicit JsonUnitTestResultPrinter(const char* output_file);
  5072. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  5073. // Prints an JSON summary of all unit tests.
  5074. static void PrintJsonTestList(::std::ostream* stream,
  5075. const std::vector<TestSuite*>& test_suites);
  5076. private:
  5077. // Returns an JSON-escaped copy of the input string str.
  5078. static std::string EscapeJson(const std::string& str);
  5079. //// Verifies that the given attribute belongs to the given element and
  5080. //// streams the attribute as JSON.
  5081. static void OutputJsonKey(std::ostream* stream,
  5082. const std::string& element_name,
  5083. const std::string& name,
  5084. const std::string& value,
  5085. const std::string& indent,
  5086. bool comma = true);
  5087. static void OutputJsonKey(std::ostream* stream,
  5088. const std::string& element_name,
  5089. const std::string& name,
  5090. int value,
  5091. const std::string& indent,
  5092. bool comma = true);
  5093. // Streams a test suite JSON stanza containing the given test result.
  5094. //
  5095. // Requires: result.Failed()
  5096. static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
  5097. const TestResult& result);
  5098. // Streams a JSON representation of a TestResult object.
  5099. static void OutputJsonTestResult(::std::ostream* stream,
  5100. const TestResult& result);
  5101. // Streams a JSON representation of a TestInfo object.
  5102. static void OutputJsonTestInfo(::std::ostream* stream,
  5103. const char* test_suite_name,
  5104. const TestInfo& test_info);
  5105. // Prints a JSON representation of a TestSuite object
  5106. static void PrintJsonTestSuite(::std::ostream* stream,
  5107. const TestSuite& test_suite);
  5108. // Prints a JSON summary of unit_test to output stream out.
  5109. static void PrintJsonUnitTest(::std::ostream* stream,
  5110. const UnitTest& unit_test);
  5111. // Produces a string representing the test properties in a result as
  5112. // a JSON dictionary.
  5113. static std::string TestPropertiesAsJson(const TestResult& result,
  5114. const std::string& indent);
  5115. // The output file.
  5116. const std::string output_file_;
  5117. GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
  5118. };
  5119. // Creates a new JsonUnitTestResultPrinter.
  5120. JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
  5121. : output_file_(output_file) {
  5122. if (output_file_.empty()) {
  5123. GTEST_LOG_(FATAL) << "JSON output file may not be null";
  5124. }
  5125. }
  5126. void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  5127. int /*iteration*/) {
  5128. FILE* jsonout = OpenFileForWriting(output_file_);
  5129. std::stringstream stream;
  5130. PrintJsonUnitTest(&stream, unit_test);
  5131. fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
  5132. fclose(jsonout);
  5133. }
  5134. // Returns an JSON-escaped copy of the input string str.
  5135. std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
  5136. Message m;
  5137. for (size_t i = 0; i < str.size(); ++i) {
  5138. const char ch = str[i];
  5139. switch (ch) {
  5140. case '\\':
  5141. case '"':
  5142. case '/':
  5143. m << '\\' << ch;
  5144. break;
  5145. case '\b':
  5146. m << "\\b";
  5147. break;
  5148. case '\t':
  5149. m << "\\t";
  5150. break;
  5151. case '\n':
  5152. m << "\\n";
  5153. break;
  5154. case '\f':
  5155. m << "\\f";
  5156. break;
  5157. case '\r':
  5158. m << "\\r";
  5159. break;
  5160. default:
  5161. if (ch < ' ') {
  5162. m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
  5163. } else {
  5164. m << ch;
  5165. }
  5166. break;
  5167. }
  5168. }
  5169. return m.GetString();
  5170. }
  5171. // The following routines generate an JSON representation of a UnitTest
  5172. // object.
  5173. // Formats the given time in milliseconds as seconds.
  5174. static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
  5175. ::std::stringstream ss;
  5176. ss << (static_cast<double>(ms) * 1e-3) << "s";
  5177. return ss.str();
  5178. }
  5179. // Converts the given epoch time in milliseconds to a date string in the
  5180. // RFC3339 format, without the timezone information.
  5181. static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
  5182. struct tm time_struct;
  5183. if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  5184. return "";
  5185. // YYYY-MM-DDThh:mm:ss
  5186. return StreamableToString(time_struct.tm_year + 1900) + "-" +
  5187. String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  5188. String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  5189. String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  5190. String::FormatIntWidth2(time_struct.tm_min) + ":" +
  5191. String::FormatIntWidth2(time_struct.tm_sec) + "Z";
  5192. }
  5193. static inline std::string Indent(size_t width) {
  5194. return std::string(width, ' ');
  5195. }
  5196. void JsonUnitTestResultPrinter::OutputJsonKey(
  5197. std::ostream* stream,
  5198. const std::string& element_name,
  5199. const std::string& name,
  5200. const std::string& value,
  5201. const std::string& indent,
  5202. bool comma) {
  5203. const std::vector<std::string>& allowed_names =
  5204. GetReservedOutputAttributesForElement(element_name);
  5205. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  5206. allowed_names.end())
  5207. << "Key \"" << name << "\" is not allowed for value \"" << element_name
  5208. << "\".";
  5209. *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
  5210. if (comma)
  5211. *stream << ",\n";
  5212. }
  5213. void JsonUnitTestResultPrinter::OutputJsonKey(
  5214. std::ostream* stream,
  5215. const std::string& element_name,
  5216. const std::string& name,
  5217. int value,
  5218. const std::string& indent,
  5219. bool comma) {
  5220. const std::vector<std::string>& allowed_names =
  5221. GetReservedOutputAttributesForElement(element_name);
  5222. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  5223. allowed_names.end())
  5224. << "Key \"" << name << "\" is not allowed for value \"" << element_name
  5225. << "\".";
  5226. *stream << indent << "\"" << name << "\": " << StreamableToString(value);
  5227. if (comma)
  5228. *stream << ",\n";
  5229. }
  5230. // Streams a test suite JSON stanza containing the given test result.
  5231. void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
  5232. ::std::ostream* stream, const TestResult& result) {
  5233. // Output the boilerplate for a new test suite.
  5234. *stream << Indent(4) << "{\n";
  5235. OutputJsonKey(stream, "testsuite", "name", "NonTestSuiteFailure", Indent(6));
  5236. OutputJsonKey(stream, "testsuite", "tests", 1, Indent(6));
  5237. if (!GTEST_FLAG(list_tests)) {
  5238. OutputJsonKey(stream, "testsuite", "failures", 1, Indent(6));
  5239. OutputJsonKey(stream, "testsuite", "disabled", 0, Indent(6));
  5240. OutputJsonKey(stream, "testsuite", "skipped", 0, Indent(6));
  5241. OutputJsonKey(stream, "testsuite", "errors", 0, Indent(6));
  5242. OutputJsonKey(stream, "testsuite", "time",
  5243. FormatTimeInMillisAsDuration(result.elapsed_time()),
  5244. Indent(6));
  5245. OutputJsonKey(stream, "testsuite", "timestamp",
  5246. FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
  5247. Indent(6));
  5248. }
  5249. *stream << Indent(6) << "\"testsuite\": [\n";
  5250. // Output the boilerplate for a new test case.
  5251. *stream << Indent(8) << "{\n";
  5252. OutputJsonKey(stream, "testcase", "name", "", Indent(10));
  5253. OutputJsonKey(stream, "testcase", "status", "RUN", Indent(10));
  5254. OutputJsonKey(stream, "testcase", "result", "COMPLETED", Indent(10));
  5255. OutputJsonKey(stream, "testcase", "timestamp",
  5256. FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
  5257. Indent(10));
  5258. OutputJsonKey(stream, "testcase", "time",
  5259. FormatTimeInMillisAsDuration(result.elapsed_time()),
  5260. Indent(10));
  5261. OutputJsonKey(stream, "testcase", "classname", "", Indent(10), false);
  5262. *stream << TestPropertiesAsJson(result, Indent(10));
  5263. // Output the actual test result.
  5264. OutputJsonTestResult(stream, result);
  5265. // Finish the test suite.
  5266. *stream << "\n" << Indent(6) << "]\n" << Indent(4) << "}";
  5267. }
  5268. // Prints a JSON representation of a TestInfo object.
  5269. void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
  5270. const char* test_suite_name,
  5271. const TestInfo& test_info) {
  5272. const TestResult& result = *test_info.result();
  5273. const std::string kTestsuite = "testcase";
  5274. const std::string kIndent = Indent(10);
  5275. *stream << Indent(8) << "{\n";
  5276. OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent);
  5277. if (test_info.value_param() != nullptr) {
  5278. OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(),
  5279. kIndent);
  5280. }
  5281. if (test_info.type_param() != nullptr) {
  5282. OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
  5283. kIndent);
  5284. }
  5285. if (GTEST_FLAG(list_tests)) {
  5286. OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
  5287. OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
  5288. *stream << "\n" << Indent(8) << "}";
  5289. return;
  5290. }
  5291. OutputJsonKey(stream, kTestsuite, "status",
  5292. test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
  5293. OutputJsonKey(stream, kTestsuite, "result",
  5294. test_info.should_run()
  5295. ? (result.Skipped() ? "SKIPPED" : "COMPLETED")
  5296. : "SUPPRESSED",
  5297. kIndent);
  5298. OutputJsonKey(stream, kTestsuite, "timestamp",
  5299. FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
  5300. kIndent);
  5301. OutputJsonKey(stream, kTestsuite, "time",
  5302. FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
  5303. OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent,
  5304. false);
  5305. *stream << TestPropertiesAsJson(result, kIndent);
  5306. OutputJsonTestResult(stream, result);
  5307. }
  5308. void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
  5309. const TestResult& result) {
  5310. const std::string kIndent = Indent(10);
  5311. int failures = 0;
  5312. for (int i = 0; i < result.total_part_count(); ++i) {
  5313. const TestPartResult& part = result.GetTestPartResult(i);
  5314. if (part.failed()) {
  5315. *stream << ",\n";
  5316. if (++failures == 1) {
  5317. *stream << kIndent << "\"" << "failures" << "\": [\n";
  5318. }
  5319. const std::string location =
  5320. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  5321. part.line_number());
  5322. const std::string message = EscapeJson(location + "\n" + part.message());
  5323. *stream << kIndent << " {\n"
  5324. << kIndent << " \"failure\": \"" << message << "\",\n"
  5325. << kIndent << " \"type\": \"\"\n"
  5326. << kIndent << " }";
  5327. }
  5328. }
  5329. if (failures > 0)
  5330. *stream << "\n" << kIndent << "]";
  5331. *stream << "\n" << Indent(8) << "}";
  5332. }
  5333. // Prints an JSON representation of a TestSuite object
  5334. void JsonUnitTestResultPrinter::PrintJsonTestSuite(
  5335. std::ostream* stream, const TestSuite& test_suite) {
  5336. const std::string kTestsuite = "testsuite";
  5337. const std::string kIndent = Indent(6);
  5338. *stream << Indent(4) << "{\n";
  5339. OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
  5340. OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
  5341. kIndent);
  5342. if (!GTEST_FLAG(list_tests)) {
  5343. OutputJsonKey(stream, kTestsuite, "failures",
  5344. test_suite.failed_test_count(), kIndent);
  5345. OutputJsonKey(stream, kTestsuite, "disabled",
  5346. test_suite.reportable_disabled_test_count(), kIndent);
  5347. OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
  5348. OutputJsonKey(
  5349. stream, kTestsuite, "timestamp",
  5350. FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()),
  5351. kIndent);
  5352. OutputJsonKey(stream, kTestsuite, "time",
  5353. FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
  5354. kIndent, false);
  5355. *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
  5356. << ",\n";
  5357. }
  5358. *stream << kIndent << "\"" << kTestsuite << "\": [\n";
  5359. bool comma = false;
  5360. for (int i = 0; i < test_suite.total_test_count(); ++i) {
  5361. if (test_suite.GetTestInfo(i)->is_reportable()) {
  5362. if (comma) {
  5363. *stream << ",\n";
  5364. } else {
  5365. comma = true;
  5366. }
  5367. OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
  5368. }
  5369. }
  5370. *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
  5371. }
  5372. // Prints a JSON summary of unit_test to output stream out.
  5373. void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
  5374. const UnitTest& unit_test) {
  5375. const std::string kTestsuites = "testsuites";
  5376. const std::string kIndent = Indent(2);
  5377. *stream << "{\n";
  5378. OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
  5379. kIndent);
  5380. OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
  5381. kIndent);
  5382. OutputJsonKey(stream, kTestsuites, "disabled",
  5383. unit_test.reportable_disabled_test_count(), kIndent);
  5384. OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
  5385. if (GTEST_FLAG(shuffle)) {
  5386. OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
  5387. kIndent);
  5388. }
  5389. OutputJsonKey(stream, kTestsuites, "timestamp",
  5390. FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
  5391. kIndent);
  5392. OutputJsonKey(stream, kTestsuites, "time",
  5393. FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
  5394. false);
  5395. *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
  5396. << ",\n";
  5397. OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  5398. *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  5399. bool comma = false;
  5400. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  5401. if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
  5402. if (comma) {
  5403. *stream << ",\n";
  5404. } else {
  5405. comma = true;
  5406. }
  5407. PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
  5408. }
  5409. }
  5410. // If there was a test failure outside of one of the test suites (like in a
  5411. // test environment) include that in the output.
  5412. if (unit_test.ad_hoc_test_result().Failed()) {
  5413. OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
  5414. }
  5415. *stream << "\n" << kIndent << "]\n" << "}\n";
  5416. }
  5417. void JsonUnitTestResultPrinter::PrintJsonTestList(
  5418. std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
  5419. const std::string kTestsuites = "testsuites";
  5420. const std::string kIndent = Indent(2);
  5421. *stream << "{\n";
  5422. int total_tests = 0;
  5423. for (auto test_suite : test_suites) {
  5424. total_tests += test_suite->total_test_count();
  5425. }
  5426. OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
  5427. OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  5428. *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  5429. for (size_t i = 0; i < test_suites.size(); ++i) {
  5430. if (i != 0) {
  5431. *stream << ",\n";
  5432. }
  5433. PrintJsonTestSuite(stream, *test_suites[i]);
  5434. }
  5435. *stream << "\n"
  5436. << kIndent << "]\n"
  5437. << "}\n";
  5438. }
  5439. // Produces a string representing the test properties in a result as
  5440. // a JSON dictionary.
  5441. std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
  5442. const TestResult& result, const std::string& indent) {
  5443. Message attributes;
  5444. for (int i = 0; i < result.test_property_count(); ++i) {
  5445. const TestProperty& property = result.GetTestProperty(i);
  5446. attributes << ",\n" << indent << "\"" << property.key() << "\": "
  5447. << "\"" << EscapeJson(property.value()) << "\"";
  5448. }
  5449. return attributes.GetString();
  5450. }
  5451. // End JsonUnitTestResultPrinter
  5452. #if GTEST_CAN_STREAM_RESULTS_
  5453. // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
  5454. // replaces them by "%xx" where xx is their hexadecimal value. For
  5455. // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
  5456. // in both time and space -- important as the input str may contain an
  5457. // arbitrarily long test failure message and stack trace.
  5458. std::string StreamingListener::UrlEncode(const char* str) {
  5459. std::string result;
  5460. result.reserve(strlen(str) + 1);
  5461. for (char ch = *str; ch != '\0'; ch = *++str) {
  5462. switch (ch) {
  5463. case '%':
  5464. case '=':
  5465. case '&':
  5466. case '\n':
  5467. result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
  5468. break;
  5469. default:
  5470. result.push_back(ch);
  5471. break;
  5472. }
  5473. }
  5474. return result;
  5475. }
  5476. void StreamingListener::SocketWriter::MakeConnection() {
  5477. GTEST_CHECK_(sockfd_ == -1)
  5478. << "MakeConnection() can't be called when there is already a connection.";
  5479. addrinfo hints;
  5480. memset(&hints, 0, sizeof(hints));
  5481. hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
  5482. hints.ai_socktype = SOCK_STREAM;
  5483. addrinfo* servinfo = nullptr;
  5484. // Use the getaddrinfo() to get a linked list of IP addresses for
  5485. // the given host name.
  5486. const int error_num = getaddrinfo(
  5487. host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
  5488. if (error_num != 0) {
  5489. GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
  5490. << gai_strerror(error_num);
  5491. }
  5492. // Loop through all the results and connect to the first we can.
  5493. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
  5494. cur_addr = cur_addr->ai_next) {
  5495. sockfd_ = socket(
  5496. cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
  5497. if (sockfd_ != -1) {
  5498. // Connect the client socket to the server socket.
  5499. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
  5500. close(sockfd_);
  5501. sockfd_ = -1;
  5502. }
  5503. }
  5504. }
  5505. freeaddrinfo(servinfo); // all done with this structure
  5506. if (sockfd_ == -1) {
  5507. GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
  5508. << host_name_ << ":" << port_num_;
  5509. }
  5510. }
  5511. // End of class Streaming Listener
  5512. #endif // GTEST_CAN_STREAM_RESULTS__
  5513. // class OsStackTraceGetter
  5514. const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
  5515. "... " GTEST_NAME_ " internal frames ...";
  5516. std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
  5517. GTEST_LOCK_EXCLUDED_(mutex_) {
  5518. #if GTEST_HAS_ABSL
  5519. std::string result;
  5520. if (max_depth <= 0) {
  5521. return result;
  5522. }
  5523. max_depth = std::min(max_depth, kMaxStackTraceDepth);
  5524. std::vector<void*> raw_stack(max_depth);
  5525. // Skips the frames requested by the caller, plus this function.
  5526. const int raw_stack_size =
  5527. absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
  5528. void* caller_frame = nullptr;
  5529. {
  5530. MutexLock lock(&mutex_);
  5531. caller_frame = caller_frame_;
  5532. }
  5533. for (int i = 0; i < raw_stack_size; ++i) {
  5534. if (raw_stack[i] == caller_frame &&
  5535. !GTEST_FLAG(show_internal_stack_frames)) {
  5536. // Add a marker to the trace and stop adding frames.
  5537. absl::StrAppend(&result, kElidedFramesMarker, "\n");
  5538. break;
  5539. }
  5540. char tmp[1024];
  5541. const char* symbol = "(unknown)";
  5542. if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
  5543. symbol = tmp;
  5544. }
  5545. char line[1024];
  5546. snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
  5547. result += line;
  5548. }
  5549. return result;
  5550. #else // !GTEST_HAS_ABSL
  5551. static_cast<void>(max_depth);
  5552. static_cast<void>(skip_count);
  5553. return "";
  5554. #endif // GTEST_HAS_ABSL
  5555. }
  5556. void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
  5557. #if GTEST_HAS_ABSL
  5558. void* caller_frame = nullptr;
  5559. if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
  5560. caller_frame = nullptr;
  5561. }
  5562. MutexLock lock(&mutex_);
  5563. caller_frame_ = caller_frame;
  5564. #endif // GTEST_HAS_ABSL
  5565. }
  5566. // A helper class that creates the premature-exit file in its
  5567. // constructor and deletes the file in its destructor.
  5568. class ScopedPrematureExitFile {
  5569. public:
  5570. explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
  5571. : premature_exit_filepath_(premature_exit_filepath ?
  5572. premature_exit_filepath : "") {
  5573. // If a path to the premature-exit file is specified...
  5574. if (!premature_exit_filepath_.empty()) {
  5575. // create the file with a single "0" character in it. I/O
  5576. // errors are ignored as there's nothing better we can do and we
  5577. // don't want to fail the test because of this.
  5578. FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
  5579. fwrite("0", 1, 1, pfile);
  5580. fclose(pfile);
  5581. }
  5582. }
  5583. ~ScopedPrematureExitFile() {
  5584. #if !defined GTEST_OS_ESP8266
  5585. if (!premature_exit_filepath_.empty()) {
  5586. int retval = remove(premature_exit_filepath_.c_str());
  5587. if (retval) {
  5588. GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
  5589. << premature_exit_filepath_ << "\" with error "
  5590. << retval;
  5591. }
  5592. }
  5593. #endif
  5594. }
  5595. private:
  5596. const std::string premature_exit_filepath_;
  5597. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
  5598. };
  5599. } // namespace internal
  5600. // class TestEventListeners
  5601. TestEventListeners::TestEventListeners()
  5602. : repeater_(new internal::TestEventRepeater()),
  5603. default_result_printer_(nullptr),
  5604. default_xml_generator_(nullptr) {}
  5605. TestEventListeners::~TestEventListeners() { delete repeater_; }
  5606. // Returns the standard listener responsible for the default console
  5607. // output. Can be removed from the listeners list to shut down default
  5608. // console output. Note that removing this object from the listener list
  5609. // with Release transfers its ownership to the user.
  5610. void TestEventListeners::Append(TestEventListener* listener) {
  5611. repeater_->Append(listener);
  5612. }
  5613. // Removes the given event listener from the list and returns it. It then
  5614. // becomes the caller's responsibility to delete the listener. Returns
  5615. // NULL if the listener is not found in the list.
  5616. TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
  5617. if (listener == default_result_printer_)
  5618. default_result_printer_ = nullptr;
  5619. else if (listener == default_xml_generator_)
  5620. default_xml_generator_ = nullptr;
  5621. return repeater_->Release(listener);
  5622. }
  5623. // Returns repeater that broadcasts the TestEventListener events to all
  5624. // subscribers.
  5625. TestEventListener* TestEventListeners::repeater() { return repeater_; }
  5626. // Sets the default_result_printer attribute to the provided listener.
  5627. // The listener is also added to the listener list and previous
  5628. // default_result_printer is removed from it and deleted. The listener can
  5629. // also be NULL in which case it will not be added to the list. Does
  5630. // nothing if the previous and the current listener objects are the same.
  5631. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
  5632. if (default_result_printer_ != listener) {
  5633. // It is an error to pass this method a listener that is already in the
  5634. // list.
  5635. delete Release(default_result_printer_);
  5636. default_result_printer_ = listener;
  5637. if (listener != nullptr) Append(listener);
  5638. }
  5639. }
  5640. // Sets the default_xml_generator attribute to the provided listener. The
  5641. // listener is also added to the listener list and previous
  5642. // default_xml_generator is removed from it and deleted. The listener can
  5643. // also be NULL in which case it will not be added to the list. Does
  5644. // nothing if the previous and the current listener objects are the same.
  5645. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
  5646. if (default_xml_generator_ != listener) {
  5647. // It is an error to pass this method a listener that is already in the
  5648. // list.
  5649. delete Release(default_xml_generator_);
  5650. default_xml_generator_ = listener;
  5651. if (listener != nullptr) Append(listener);
  5652. }
  5653. }
  5654. // Controls whether events will be forwarded by the repeater to the
  5655. // listeners in the list.
  5656. bool TestEventListeners::EventForwardingEnabled() const {
  5657. return repeater_->forwarding_enabled();
  5658. }
  5659. void TestEventListeners::SuppressEventForwarding() {
  5660. repeater_->set_forwarding_enabled(false);
  5661. }
  5662. // class UnitTest
  5663. // Gets the singleton UnitTest object. The first time this method is
  5664. // called, a UnitTest object is constructed and returned. Consecutive
  5665. // calls will return the same object.
  5666. //
  5667. // We don't protect this under mutex_ as a user is not supposed to
  5668. // call this before main() starts, from which point on the return
  5669. // value will never change.
  5670. UnitTest* UnitTest::GetInstance() {
  5671. // CodeGear C++Builder insists on a public destructor for the
  5672. // default implementation. Use this implementation to keep good OO
  5673. // design with private destructor.
  5674. #if defined(__BORLANDC__)
  5675. static UnitTest* const instance = new UnitTest;
  5676. return instance;
  5677. #else
  5678. static UnitTest instance;
  5679. return &instance;
  5680. #endif // defined(__BORLANDC__)
  5681. }
  5682. // Gets the number of successful test suites.
  5683. int UnitTest::successful_test_suite_count() const {
  5684. return impl()->successful_test_suite_count();
  5685. }
  5686. // Gets the number of failed test suites.
  5687. int UnitTest::failed_test_suite_count() const {
  5688. return impl()->failed_test_suite_count();
  5689. }
  5690. // Gets the number of all test suites.
  5691. int UnitTest::total_test_suite_count() const {
  5692. return impl()->total_test_suite_count();
  5693. }
  5694. // Gets the number of all test suites that contain at least one test
  5695. // that should run.
  5696. int UnitTest::test_suite_to_run_count() const {
  5697. return impl()->test_suite_to_run_count();
  5698. }
  5699. // Legacy API is deprecated but still available
  5700. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5701. int UnitTest::successful_test_case_count() const {
  5702. return impl()->successful_test_suite_count();
  5703. }
  5704. int UnitTest::failed_test_case_count() const {
  5705. return impl()->failed_test_suite_count();
  5706. }
  5707. int UnitTest::total_test_case_count() const {
  5708. return impl()->total_test_suite_count();
  5709. }
  5710. int UnitTest::test_case_to_run_count() const {
  5711. return impl()->test_suite_to_run_count();
  5712. }
  5713. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5714. // Gets the number of successful tests.
  5715. int UnitTest::successful_test_count() const {
  5716. return impl()->successful_test_count();
  5717. }
  5718. // Gets the number of skipped tests.
  5719. int UnitTest::skipped_test_count() const {
  5720. return impl()->skipped_test_count();
  5721. }
  5722. // Gets the number of failed tests.
  5723. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
  5724. // Gets the number of disabled tests that will be reported in the XML report.
  5725. int UnitTest::reportable_disabled_test_count() const {
  5726. return impl()->reportable_disabled_test_count();
  5727. }
  5728. // Gets the number of disabled tests.
  5729. int UnitTest::disabled_test_count() const {
  5730. return impl()->disabled_test_count();
  5731. }
  5732. // Gets the number of tests to be printed in the XML report.
  5733. int UnitTest::reportable_test_count() const {
  5734. return impl()->reportable_test_count();
  5735. }
  5736. // Gets the number of all tests.
  5737. int UnitTest::total_test_count() const { return impl()->total_test_count(); }
  5738. // Gets the number of tests that should run.
  5739. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
  5740. // Gets the time of the test program start, in ms from the start of the
  5741. // UNIX epoch.
  5742. internal::TimeInMillis UnitTest::start_timestamp() const {
  5743. return impl()->start_timestamp();
  5744. }
  5745. // Gets the elapsed time, in milliseconds.
  5746. internal::TimeInMillis UnitTest::elapsed_time() const {
  5747. return impl()->elapsed_time();
  5748. }
  5749. // Returns true if and only if the unit test passed (i.e. all test suites
  5750. // passed).
  5751. bool UnitTest::Passed() const { return impl()->Passed(); }
  5752. // Returns true if and only if the unit test failed (i.e. some test suite
  5753. // failed or something outside of all tests failed).
  5754. bool UnitTest::Failed() const { return impl()->Failed(); }
  5755. // Gets the i-th test suite among all the test suites. i can range from 0 to
  5756. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  5757. const TestSuite* UnitTest::GetTestSuite(int i) const {
  5758. return impl()->GetTestSuite(i);
  5759. }
  5760. // Legacy API is deprecated but still available
  5761. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5762. const TestCase* UnitTest::GetTestCase(int i) const {
  5763. return impl()->GetTestCase(i);
  5764. }
  5765. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5766. // Returns the TestResult containing information on test failures and
  5767. // properties logged outside of individual test suites.
  5768. const TestResult& UnitTest::ad_hoc_test_result() const {
  5769. return *impl()->ad_hoc_test_result();
  5770. }
  5771. // Gets the i-th test suite among all the test suites. i can range from 0 to
  5772. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  5773. TestSuite* UnitTest::GetMutableTestSuite(int i) {
  5774. return impl()->GetMutableSuiteCase(i);
  5775. }
  5776. // Returns the list of event listeners that can be used to track events
  5777. // inside Google Test.
  5778. TestEventListeners& UnitTest::listeners() {
  5779. return *impl()->listeners();
  5780. }
  5781. // Registers and returns a global test environment. When a test
  5782. // program is run, all global test environments will be set-up in the
  5783. // order they were registered. After all tests in the program have
  5784. // finished, all global test environments will be torn-down in the
  5785. // *reverse* order they were registered.
  5786. //
  5787. // The UnitTest object takes ownership of the given environment.
  5788. //
  5789. // We don't protect this under mutex_, as we only support calling it
  5790. // from the main thread.
  5791. Environment* UnitTest::AddEnvironment(Environment* env) {
  5792. if (env == nullptr) {
  5793. return nullptr;
  5794. }
  5795. impl_->environments().push_back(env);
  5796. return env;
  5797. }
  5798. // Adds a TestPartResult to the current TestResult object. All Google Test
  5799. // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
  5800. // this to report their results. The user code should use the
  5801. // assertion macros instead of calling this directly.
  5802. void UnitTest::AddTestPartResult(
  5803. TestPartResult::Type result_type,
  5804. const char* file_name,
  5805. int line_number,
  5806. const std::string& message,
  5807. const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
  5808. Message msg;
  5809. msg << message;
  5810. internal::MutexLock lock(&mutex_);
  5811. if (impl_->gtest_trace_stack().size() > 0) {
  5812. msg << "\n" << GTEST_NAME_ << " trace:";
  5813. for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
  5814. const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
  5815. msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
  5816. << " " << trace.message;
  5817. }
  5818. }
  5819. if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
  5820. msg << internal::kStackTraceMarker << os_stack_trace;
  5821. }
  5822. const TestPartResult result = TestPartResult(
  5823. result_type, file_name, line_number, msg.GetString().c_str());
  5824. impl_->GetTestPartResultReporterForCurrentThread()->
  5825. ReportTestPartResult(result);
  5826. if (result_type != TestPartResult::kSuccess &&
  5827. result_type != TestPartResult::kSkip) {
  5828. // gtest_break_on_failure takes precedence over
  5829. // gtest_throw_on_failure. This allows a user to set the latter
  5830. // in the code (perhaps in order to use Google Test assertions
  5831. // with another testing framework) and specify the former on the
  5832. // command line for debugging.
  5833. if (GTEST_FLAG(break_on_failure)) {
  5834. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  5835. // Using DebugBreak on Windows allows gtest to still break into a debugger
  5836. // when a failure happens and both the --gtest_break_on_failure and
  5837. // the --gtest_catch_exceptions flags are specified.
  5838. DebugBreak();
  5839. #elif (!defined(__native_client__)) && \
  5840. ((defined(__clang__) || defined(__GNUC__)) && \
  5841. (defined(__x86_64__) || defined(__i386__)))
  5842. // with clang/gcc we can achieve the same effect on x86 by invoking int3
  5843. asm("int3");
  5844. #else
  5845. // Dereference nullptr through a volatile pointer to prevent the compiler
  5846. // from removing. We use this rather than abort() or __builtin_trap() for
  5847. // portability: some debuggers don't correctly trap abort().
  5848. *static_cast<volatile int*>(nullptr) = 1;
  5849. #endif // GTEST_OS_WINDOWS
  5850. } else if (GTEST_FLAG(throw_on_failure)) {
  5851. #if GTEST_HAS_EXCEPTIONS
  5852. throw internal::GoogleTestFailureException(result);
  5853. #else
  5854. // We cannot call abort() as it generates a pop-up in debug mode
  5855. // that cannot be suppressed in VC 7.1 or below.
  5856. exit(1);
  5857. #endif
  5858. }
  5859. }
  5860. }
  5861. // Adds a TestProperty to the current TestResult object when invoked from
  5862. // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
  5863. // from SetUpTestSuite or TearDownTestSuite, or to the global property set
  5864. // when invoked elsewhere. If the result already contains a property with
  5865. // the same key, the value will be updated.
  5866. void UnitTest::RecordProperty(const std::string& key,
  5867. const std::string& value) {
  5868. impl_->RecordProperty(TestProperty(key, value));
  5869. }
  5870. // Runs all tests in this UnitTest object and prints the result.
  5871. // Returns 0 if successful, or 1 otherwise.
  5872. //
  5873. // We don't protect this under mutex_, as we only support calling it
  5874. // from the main thread.
  5875. int UnitTest::Run() {
  5876. const bool in_death_test_child_process =
  5877. internal::GTEST_FLAG(internal_run_death_test).length() > 0;
  5878. // Google Test implements this protocol for catching that a test
  5879. // program exits before returning control to Google Test:
  5880. //
  5881. // 1. Upon start, Google Test creates a file whose absolute path
  5882. // is specified by the environment variable
  5883. // TEST_PREMATURE_EXIT_FILE.
  5884. // 2. When Google Test has finished its work, it deletes the file.
  5885. //
  5886. // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
  5887. // running a Google-Test-based test program and check the existence
  5888. // of the file at the end of the test execution to see if it has
  5889. // exited prematurely.
  5890. // If we are in the child process of a death test, don't
  5891. // create/delete the premature exit file, as doing so is unnecessary
  5892. // and will confuse the parent process. Otherwise, create/delete
  5893. // the file upon entering/leaving this function. If the program
  5894. // somehow exits before this function has a chance to return, the
  5895. // premature-exit file will be left undeleted, causing a test runner
  5896. // that understands the premature-exit-file protocol to report the
  5897. // test as having failed.
  5898. const internal::ScopedPrematureExitFile premature_exit_file(
  5899. in_death_test_child_process
  5900. ? nullptr
  5901. : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
  5902. // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
  5903. // used for the duration of the program.
  5904. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
  5905. #if GTEST_OS_WINDOWS
  5906. // Either the user wants Google Test to catch exceptions thrown by the
  5907. // tests or this is executing in the context of death test child
  5908. // process. In either case the user does not want to see pop-up dialogs
  5909. // about crashes - they are expected.
  5910. if (impl()->catch_exceptions() || in_death_test_child_process) {
  5911. # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  5912. // SetErrorMode doesn't exist on CE.
  5913. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
  5914. SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
  5915. # endif // !GTEST_OS_WINDOWS_MOBILE
  5916. # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
  5917. // Death test children can be terminated with _abort(). On Windows,
  5918. // _abort() can show a dialog with a warning message. This forces the
  5919. // abort message to go to stderr instead.
  5920. _set_error_mode(_OUT_TO_STDERR);
  5921. # endif
  5922. # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
  5923. // In the debug version, Visual Studio pops up a separate dialog
  5924. // offering a choice to debug the aborted program. We need to suppress
  5925. // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
  5926. // executed. Google Test will notify the user of any unexpected
  5927. // failure via stderr.
  5928. if (!GTEST_FLAG(break_on_failure))
  5929. _set_abort_behavior(
  5930. 0x0, // Clear the following flags:
  5931. _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
  5932. // In debug mode, the Windows CRT can crash with an assertion over invalid
  5933. // input (e.g. passing an invalid file descriptor). The default handling
  5934. // for these assertions is to pop up a dialog and wait for user input.
  5935. // Instead ask the CRT to dump such assertions to stderr non-interactively.
  5936. if (!IsDebuggerPresent()) {
  5937. (void)_CrtSetReportMode(_CRT_ASSERT,
  5938. _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  5939. (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
  5940. }
  5941. # endif
  5942. }
  5943. #endif // GTEST_OS_WINDOWS
  5944. return internal::HandleExceptionsInMethodIfSupported(
  5945. impl(),
  5946. &internal::UnitTestImpl::RunAllTests,
  5947. "auxiliary test code (environments or event listeners)") ? 0 : 1;
  5948. }
  5949. // Returns the working directory when the first TEST() or TEST_F() was
  5950. // executed.
  5951. const char* UnitTest::original_working_dir() const {
  5952. return impl_->original_working_dir_.c_str();
  5953. }
  5954. // Returns the TestSuite object for the test that's currently running,
  5955. // or NULL if no test is running.
  5956. const TestSuite* UnitTest::current_test_suite() const
  5957. GTEST_LOCK_EXCLUDED_(mutex_) {
  5958. internal::MutexLock lock(&mutex_);
  5959. return impl_->current_test_suite();
  5960. }
  5961. // Legacy API is still available but deprecated
  5962. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5963. const TestCase* UnitTest::current_test_case() const
  5964. GTEST_LOCK_EXCLUDED_(mutex_) {
  5965. internal::MutexLock lock(&mutex_);
  5966. return impl_->current_test_suite();
  5967. }
  5968. #endif
  5969. // Returns the TestInfo object for the test that's currently running,
  5970. // or NULL if no test is running.
  5971. const TestInfo* UnitTest::current_test_info() const
  5972. GTEST_LOCK_EXCLUDED_(mutex_) {
  5973. internal::MutexLock lock(&mutex_);
  5974. return impl_->current_test_info();
  5975. }
  5976. // Returns the random seed used at the start of the current test run.
  5977. int UnitTest::random_seed() const { return impl_->random_seed(); }
  5978. // Returns ParameterizedTestSuiteRegistry object used to keep track of
  5979. // value-parameterized tests and instantiate and register them.
  5980. internal::ParameterizedTestSuiteRegistry&
  5981. UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
  5982. return impl_->parameterized_test_registry();
  5983. }
  5984. // Creates an empty UnitTest.
  5985. UnitTest::UnitTest() {
  5986. impl_ = new internal::UnitTestImpl(this);
  5987. }
  5988. // Destructor of UnitTest.
  5989. UnitTest::~UnitTest() {
  5990. delete impl_;
  5991. }
  5992. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  5993. // Google Test trace stack.
  5994. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
  5995. GTEST_LOCK_EXCLUDED_(mutex_) {
  5996. internal::MutexLock lock(&mutex_);
  5997. impl_->gtest_trace_stack().push_back(trace);
  5998. }
  5999. // Pops a trace from the per-thread Google Test trace stack.
  6000. void UnitTest::PopGTestTrace()
  6001. GTEST_LOCK_EXCLUDED_(mutex_) {
  6002. internal::MutexLock lock(&mutex_);
  6003. impl_->gtest_trace_stack().pop_back();
  6004. }
  6005. namespace internal {
  6006. UnitTestImpl::UnitTestImpl(UnitTest* parent)
  6007. : parent_(parent),
  6008. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
  6009. default_global_test_part_result_reporter_(this),
  6010. default_per_thread_test_part_result_reporter_(this),
  6011. GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
  6012. &default_global_test_part_result_reporter_),
  6013. per_thread_test_part_result_reporter_(
  6014. &default_per_thread_test_part_result_reporter_),
  6015. parameterized_test_registry_(),
  6016. parameterized_tests_registered_(false),
  6017. last_death_test_suite_(-1),
  6018. current_test_suite_(nullptr),
  6019. current_test_info_(nullptr),
  6020. ad_hoc_test_result_(),
  6021. os_stack_trace_getter_(nullptr),
  6022. post_flag_parse_init_performed_(false),
  6023. random_seed_(0), // Will be overridden by the flag before first use.
  6024. random_(0), // Will be reseeded before first use.
  6025. start_timestamp_(0),
  6026. elapsed_time_(0),
  6027. #if GTEST_HAS_DEATH_TEST
  6028. death_test_factory_(new DefaultDeathTestFactory),
  6029. #endif
  6030. // Will be overridden by the flag before first use.
  6031. catch_exceptions_(false) {
  6032. listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
  6033. }
  6034. UnitTestImpl::~UnitTestImpl() {
  6035. // Deletes every TestSuite.
  6036. ForEach(test_suites_, internal::Delete<TestSuite>);
  6037. // Deletes every Environment.
  6038. ForEach(environments_, internal::Delete<Environment>);
  6039. delete os_stack_trace_getter_;
  6040. }
  6041. // Adds a TestProperty to the current TestResult object when invoked in a
  6042. // context of a test, to current test suite's ad_hoc_test_result when invoke
  6043. // from SetUpTestSuite/TearDownTestSuite, or to the global property set
  6044. // otherwise. If the result already contains a property with the same key,
  6045. // the value will be updated.
  6046. void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
  6047. std::string xml_element;
  6048. TestResult* test_result; // TestResult appropriate for property recording.
  6049. if (current_test_info_ != nullptr) {
  6050. xml_element = "testcase";
  6051. test_result = &(current_test_info_->result_);
  6052. } else if (current_test_suite_ != nullptr) {
  6053. xml_element = "testsuite";
  6054. test_result = &(current_test_suite_->ad_hoc_test_result_);
  6055. } else {
  6056. xml_element = "testsuites";
  6057. test_result = &ad_hoc_test_result_;
  6058. }
  6059. test_result->RecordProperty(xml_element, test_property);
  6060. }
  6061. #if GTEST_HAS_DEATH_TEST
  6062. // Disables event forwarding if the control is currently in a death test
  6063. // subprocess. Must not be called before InitGoogleTest.
  6064. void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
  6065. if (internal_run_death_test_flag_.get() != nullptr)
  6066. listeners()->SuppressEventForwarding();
  6067. }
  6068. #endif // GTEST_HAS_DEATH_TEST
  6069. // Initializes event listeners performing XML output as specified by
  6070. // UnitTestOptions. Must not be called before InitGoogleTest.
  6071. void UnitTestImpl::ConfigureXmlOutput() {
  6072. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  6073. if (output_format == "xml") {
  6074. listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
  6075. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  6076. } else if (output_format == "json") {
  6077. listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
  6078. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  6079. } else if (output_format != "") {
  6080. GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
  6081. << output_format << "\" ignored.";
  6082. }
  6083. }
  6084. #if GTEST_CAN_STREAM_RESULTS_
  6085. // Initializes event listeners for streaming test results in string form.
  6086. // Must not be called before InitGoogleTest.
  6087. void UnitTestImpl::ConfigureStreamingOutput() {
  6088. const std::string& target = GTEST_FLAG(stream_result_to);
  6089. if (!target.empty()) {
  6090. const size_t pos = target.find(':');
  6091. if (pos != std::string::npos) {
  6092. listeners()->Append(new StreamingListener(target.substr(0, pos),
  6093. target.substr(pos+1)));
  6094. } else {
  6095. GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
  6096. << "\" ignored.";
  6097. }
  6098. }
  6099. }
  6100. #endif // GTEST_CAN_STREAM_RESULTS_
  6101. // Performs initialization dependent upon flag values obtained in
  6102. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  6103. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  6104. // this function is also called from RunAllTests. Since this function can be
  6105. // called more than once, it has to be idempotent.
  6106. void UnitTestImpl::PostFlagParsingInit() {
  6107. // Ensures that this function does not execute more than once.
  6108. if (!post_flag_parse_init_performed_) {
  6109. post_flag_parse_init_performed_ = true;
  6110. #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  6111. // Register to send notifications about key process state changes.
  6112. listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
  6113. #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  6114. #if GTEST_HAS_DEATH_TEST
  6115. InitDeathTestSubprocessControlInfo();
  6116. SuppressTestEventsIfInSubprocess();
  6117. #endif // GTEST_HAS_DEATH_TEST
  6118. // Registers parameterized tests. This makes parameterized tests
  6119. // available to the UnitTest reflection API without running
  6120. // RUN_ALL_TESTS.
  6121. RegisterParameterizedTests();
  6122. // Configures listeners for XML output. This makes it possible for users
  6123. // to shut down the default XML output before invoking RUN_ALL_TESTS.
  6124. ConfigureXmlOutput();
  6125. if (GTEST_FLAG(brief)) {
  6126. listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter);
  6127. }
  6128. #if GTEST_CAN_STREAM_RESULTS_
  6129. // Configures listeners for streaming test results to the specified server.
  6130. ConfigureStreamingOutput();
  6131. #endif // GTEST_CAN_STREAM_RESULTS_
  6132. #if GTEST_HAS_ABSL
  6133. if (GTEST_FLAG(install_failure_signal_handler)) {
  6134. absl::FailureSignalHandlerOptions options;
  6135. absl::InstallFailureSignalHandler(options);
  6136. }
  6137. #endif // GTEST_HAS_ABSL
  6138. }
  6139. }
  6140. // A predicate that checks the name of a TestSuite against a known
  6141. // value.
  6142. //
  6143. // This is used for implementation of the UnitTest class only. We put
  6144. // it in the anonymous namespace to prevent polluting the outer
  6145. // namespace.
  6146. //
  6147. // TestSuiteNameIs is copyable.
  6148. class TestSuiteNameIs {
  6149. public:
  6150. // Constructor.
  6151. explicit TestSuiteNameIs(const std::string& name) : name_(name) {}
  6152. // Returns true if and only if the name of test_suite matches name_.
  6153. bool operator()(const TestSuite* test_suite) const {
  6154. return test_suite != nullptr &&
  6155. strcmp(test_suite->name(), name_.c_str()) == 0;
  6156. }
  6157. private:
  6158. std::string name_;
  6159. };
  6160. // Finds and returns a TestSuite with the given name. If one doesn't
  6161. // exist, creates one and returns it. It's the CALLER'S
  6162. // RESPONSIBILITY to ensure that this function is only called WHEN THE
  6163. // TESTS ARE NOT SHUFFLED.
  6164. //
  6165. // Arguments:
  6166. //
  6167. // test_suite_name: name of the test suite
  6168. // type_param: the name of the test suite's type parameter, or NULL if
  6169. // this is not a typed or a type-parameterized test suite.
  6170. // set_up_tc: pointer to the function that sets up the test suite
  6171. // tear_down_tc: pointer to the function that tears down the test suite
  6172. TestSuite* UnitTestImpl::GetTestSuite(
  6173. const char* test_suite_name, const char* type_param,
  6174. internal::SetUpTestSuiteFunc set_up_tc,
  6175. internal::TearDownTestSuiteFunc tear_down_tc) {
  6176. // Can we find a TestSuite with the given name?
  6177. const auto test_suite =
  6178. std::find_if(test_suites_.rbegin(), test_suites_.rend(),
  6179. TestSuiteNameIs(test_suite_name));
  6180. if (test_suite != test_suites_.rend()) return *test_suite;
  6181. // No. Let's create one.
  6182. auto* const new_test_suite =
  6183. new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
  6184. // Is this a death test suite?
  6185. if (internal::UnitTestOptions::MatchesFilter(test_suite_name,
  6186. kDeathTestSuiteFilter)) {
  6187. // Yes. Inserts the test suite after the last death test suite
  6188. // defined so far. This only works when the test suites haven't
  6189. // been shuffled. Otherwise we may end up running a death test
  6190. // after a non-death test.
  6191. ++last_death_test_suite_;
  6192. test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
  6193. new_test_suite);
  6194. } else {
  6195. // No. Appends to the end of the list.
  6196. test_suites_.push_back(new_test_suite);
  6197. }
  6198. test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
  6199. return new_test_suite;
  6200. }
  6201. // Helpers for setting up / tearing down the given environment. They
  6202. // are for use in the ForEach() function.
  6203. static void SetUpEnvironment(Environment* env) { env->SetUp(); }
  6204. static void TearDownEnvironment(Environment* env) { env->TearDown(); }
  6205. // Runs all tests in this UnitTest object, prints the result, and
  6206. // returns true if all tests are successful. If any exception is
  6207. // thrown during a test, the test is considered to be failed, but the
  6208. // rest of the tests will still be run.
  6209. //
  6210. // When parameterized tests are enabled, it expands and registers
  6211. // parameterized tests first in RegisterParameterizedTests().
  6212. // All other functions called from RunAllTests() may safely assume that
  6213. // parameterized tests are ready to be counted and run.
  6214. bool UnitTestImpl::RunAllTests() {
  6215. // True if and only if Google Test is initialized before RUN_ALL_TESTS() is
  6216. // called.
  6217. const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
  6218. // Do not run any test if the --help flag was specified.
  6219. if (g_help_flag)
  6220. return true;
  6221. // Repeats the call to the post-flag parsing initialization in case the
  6222. // user didn't call InitGoogleTest.
  6223. PostFlagParsingInit();
  6224. // Even if sharding is not on, test runners may want to use the
  6225. // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
  6226. // protocol.
  6227. internal::WriteToShardStatusFileIfNeeded();
  6228. // True if and only if we are in a subprocess for running a thread-safe-style
  6229. // death test.
  6230. bool in_subprocess_for_death_test = false;
  6231. #if GTEST_HAS_DEATH_TEST
  6232. in_subprocess_for_death_test =
  6233. (internal_run_death_test_flag_.get() != nullptr);
  6234. # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  6235. if (in_subprocess_for_death_test) {
  6236. GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
  6237. }
  6238. # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  6239. #endif // GTEST_HAS_DEATH_TEST
  6240. const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
  6241. in_subprocess_for_death_test);
  6242. // Compares the full test names with the filter to decide which
  6243. // tests to run.
  6244. const bool has_tests_to_run = FilterTests(should_shard
  6245. ? HONOR_SHARDING_PROTOCOL
  6246. : IGNORE_SHARDING_PROTOCOL) > 0;
  6247. // Lists the tests and exits if the --gtest_list_tests flag was specified.
  6248. if (GTEST_FLAG(list_tests)) {
  6249. // This must be called *after* FilterTests() has been called.
  6250. ListTestsMatchingFilter();
  6251. return true;
  6252. }
  6253. random_seed_ = GTEST_FLAG(shuffle) ?
  6254. GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
  6255. // True if and only if at least one test has failed.
  6256. bool failed = false;
  6257. TestEventListener* repeater = listeners()->repeater();
  6258. start_timestamp_ = GetTimeInMillis();
  6259. repeater->OnTestProgramStart(*parent_);
  6260. // How many times to repeat the tests? We don't want to repeat them
  6261. // when we are inside the subprocess of a death test.
  6262. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
  6263. // Repeats forever if the repeat count is negative.
  6264. const bool gtest_repeat_forever = repeat < 0;
  6265. for (int i = 0; gtest_repeat_forever || i != repeat; i++) {
  6266. // We want to preserve failures generated by ad-hoc test
  6267. // assertions executed before RUN_ALL_TESTS().
  6268. ClearNonAdHocTestResult();
  6269. Timer timer;
  6270. // Shuffles test suites and tests if requested.
  6271. if (has_tests_to_run && GTEST_FLAG(shuffle)) {
  6272. random()->Reseed(static_cast<uint32_t>(random_seed_));
  6273. // This should be done before calling OnTestIterationStart(),
  6274. // such that a test event listener can see the actual test order
  6275. // in the event.
  6276. ShuffleTests();
  6277. }
  6278. // Tells the unit test event listeners that the tests are about to start.
  6279. repeater->OnTestIterationStart(*parent_, i);
  6280. // Runs each test suite if there is at least one test to run.
  6281. if (has_tests_to_run) {
  6282. // Sets up all environments beforehand.
  6283. repeater->OnEnvironmentsSetUpStart(*parent_);
  6284. ForEach(environments_, SetUpEnvironment);
  6285. repeater->OnEnvironmentsSetUpEnd(*parent_);
  6286. // Runs the tests only if there was no fatal failure or skip triggered
  6287. // during global set-up.
  6288. if (Test::IsSkipped()) {
  6289. // Emit diagnostics when global set-up calls skip, as it will not be
  6290. // emitted by default.
  6291. TestResult& test_result =
  6292. *internal::GetUnitTestImpl()->current_test_result();
  6293. for (int j = 0; j < test_result.total_part_count(); ++j) {
  6294. const TestPartResult& test_part_result =
  6295. test_result.GetTestPartResult(j);
  6296. if (test_part_result.type() == TestPartResult::kSkip) {
  6297. const std::string& result = test_part_result.message();
  6298. printf("%s\n", result.c_str());
  6299. }
  6300. }
  6301. fflush(stdout);
  6302. } else if (!Test::HasFatalFailure()) {
  6303. for (int test_index = 0; test_index < total_test_suite_count();
  6304. test_index++) {
  6305. GetMutableSuiteCase(test_index)->Run();
  6306. if (GTEST_FLAG(fail_fast) &&
  6307. GetMutableSuiteCase(test_index)->Failed()) {
  6308. for (int j = test_index + 1; j < total_test_suite_count(); j++) {
  6309. GetMutableSuiteCase(j)->Skip();
  6310. }
  6311. break;
  6312. }
  6313. }
  6314. } else if (Test::HasFatalFailure()) {
  6315. // If there was a fatal failure during the global setup then we know we
  6316. // aren't going to run any tests. Explicitly mark all of the tests as
  6317. // skipped to make this obvious in the output.
  6318. for (int test_index = 0; test_index < total_test_suite_count();
  6319. test_index++) {
  6320. GetMutableSuiteCase(test_index)->Skip();
  6321. }
  6322. }
  6323. // Tears down all environments in reverse order afterwards.
  6324. repeater->OnEnvironmentsTearDownStart(*parent_);
  6325. std::for_each(environments_.rbegin(), environments_.rend(),
  6326. TearDownEnvironment);
  6327. repeater->OnEnvironmentsTearDownEnd(*parent_);
  6328. }
  6329. elapsed_time_ = timer.Elapsed();
  6330. // Tells the unit test event listener that the tests have just finished.
  6331. repeater->OnTestIterationEnd(*parent_, i);
  6332. // Gets the result and clears it.
  6333. if (!Passed()) {
  6334. failed = true;
  6335. }
  6336. // Restores the original test order after the iteration. This
  6337. // allows the user to quickly repro a failure that happens in the
  6338. // N-th iteration without repeating the first (N - 1) iterations.
  6339. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
  6340. // case the user somehow changes the value of the flag somewhere
  6341. // (it's always safe to unshuffle the tests).
  6342. UnshuffleTests();
  6343. if (GTEST_FLAG(shuffle)) {
  6344. // Picks a new random seed for each iteration.
  6345. random_seed_ = GetNextRandomSeed(random_seed_);
  6346. }
  6347. }
  6348. repeater->OnTestProgramEnd(*parent_);
  6349. if (!gtest_is_initialized_before_run_all_tests) {
  6350. ColoredPrintf(
  6351. GTestColor::kRed,
  6352. "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
  6353. "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
  6354. "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
  6355. " will start to enforce the valid usage. "
  6356. "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
  6357. #if GTEST_FOR_GOOGLE_
  6358. ColoredPrintf(GTestColor::kRed,
  6359. "For more details, see http://wiki/Main/ValidGUnitMain.\n");
  6360. #endif // GTEST_FOR_GOOGLE_
  6361. }
  6362. return !failed;
  6363. }
  6364. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  6365. // if the variable is present. If a file already exists at this location, this
  6366. // function will write over it. If the variable is present, but the file cannot
  6367. // be created, prints an error and exits.
  6368. void WriteToShardStatusFileIfNeeded() {
  6369. const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
  6370. if (test_shard_file != nullptr) {
  6371. FILE* const file = posix::FOpen(test_shard_file, "w");
  6372. if (file == nullptr) {
  6373. ColoredPrintf(GTestColor::kRed,
  6374. "Could not write to the test shard status file \"%s\" "
  6375. "specified by the %s environment variable.\n",
  6376. test_shard_file, kTestShardStatusFile);
  6377. fflush(stdout);
  6378. exit(EXIT_FAILURE);
  6379. }
  6380. fclose(file);
  6381. }
  6382. }
  6383. // Checks whether sharding is enabled by examining the relevant
  6384. // environment variable values. If the variables are present,
  6385. // but inconsistent (i.e., shard_index >= total_shards), prints
  6386. // an error and exits. If in_subprocess_for_death_test, sharding is
  6387. // disabled because it must only be applied to the original test
  6388. // process. Otherwise, we could filter out death tests we intended to execute.
  6389. bool ShouldShard(const char* total_shards_env,
  6390. const char* shard_index_env,
  6391. bool in_subprocess_for_death_test) {
  6392. if (in_subprocess_for_death_test) {
  6393. return false;
  6394. }
  6395. const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1);
  6396. const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1);
  6397. if (total_shards == -1 && shard_index == -1) {
  6398. return false;
  6399. } else if (total_shards == -1 && shard_index != -1) {
  6400. const Message msg = Message()
  6401. << "Invalid environment variables: you have "
  6402. << kTestShardIndex << " = " << shard_index
  6403. << ", but have left " << kTestTotalShards << " unset.\n";
  6404. ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
  6405. fflush(stdout);
  6406. exit(EXIT_FAILURE);
  6407. } else if (total_shards != -1 && shard_index == -1) {
  6408. const Message msg = Message()
  6409. << "Invalid environment variables: you have "
  6410. << kTestTotalShards << " = " << total_shards
  6411. << ", but have left " << kTestShardIndex << " unset.\n";
  6412. ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
  6413. fflush(stdout);
  6414. exit(EXIT_FAILURE);
  6415. } else if (shard_index < 0 || shard_index >= total_shards) {
  6416. const Message msg = Message()
  6417. << "Invalid environment variables: we require 0 <= "
  6418. << kTestShardIndex << " < " << kTestTotalShards
  6419. << ", but you have " << kTestShardIndex << "=" << shard_index
  6420. << ", " << kTestTotalShards << "=" << total_shards << ".\n";
  6421. ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
  6422. fflush(stdout);
  6423. exit(EXIT_FAILURE);
  6424. }
  6425. return total_shards > 1;
  6426. }
  6427. // Parses the environment variable var as an Int32. If it is unset,
  6428. // returns default_val. If it is not an Int32, prints an error
  6429. // and aborts.
  6430. int32_t Int32FromEnvOrDie(const char* var, int32_t default_val) {
  6431. const char* str_val = posix::GetEnv(var);
  6432. if (str_val == nullptr) {
  6433. return default_val;
  6434. }
  6435. int32_t result;
  6436. if (!ParseInt32(Message() << "The value of environment variable " << var,
  6437. str_val, &result)) {
  6438. exit(EXIT_FAILURE);
  6439. }
  6440. return result;
  6441. }
  6442. // Given the total number of shards, the shard index, and the test id,
  6443. // returns true if and only if the test should be run on this shard. The test id
  6444. // is some arbitrary but unique non-negative integer assigned to each test
  6445. // method. Assumes that 0 <= shard_index < total_shards.
  6446. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
  6447. return (test_id % total_shards) == shard_index;
  6448. }
  6449. // Compares the name of each test with the user-specified filter to
  6450. // decide whether the test should be run, then records the result in
  6451. // each TestSuite and TestInfo object.
  6452. // If shard_tests == true, further filters tests based on sharding
  6453. // variables in the environment - see
  6454. // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
  6455. // . Returns the number of tests that should run.
  6456. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
  6457. const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
  6458. Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
  6459. const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
  6460. Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
  6461. // num_runnable_tests are the number of tests that will
  6462. // run across all shards (i.e., match filter and are not disabled).
  6463. // num_selected_tests are the number of tests to be run on
  6464. // this shard.
  6465. int num_runnable_tests = 0;
  6466. int num_selected_tests = 0;
  6467. for (auto* test_suite : test_suites_) {
  6468. const std::string& test_suite_name = test_suite->name();
  6469. test_suite->set_should_run(false);
  6470. for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
  6471. TestInfo* const test_info = test_suite->test_info_list()[j];
  6472. const std::string test_name(test_info->name());
  6473. // A test is disabled if test suite name or test name matches
  6474. // kDisableTestFilter.
  6475. const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
  6476. test_suite_name, kDisableTestFilter) ||
  6477. internal::UnitTestOptions::MatchesFilter(
  6478. test_name, kDisableTestFilter);
  6479. test_info->is_disabled_ = is_disabled;
  6480. const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
  6481. test_suite_name, test_name);
  6482. test_info->matches_filter_ = matches_filter;
  6483. const bool is_runnable =
  6484. (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
  6485. matches_filter;
  6486. const bool is_in_another_shard =
  6487. shard_tests != IGNORE_SHARDING_PROTOCOL &&
  6488. !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
  6489. test_info->is_in_another_shard_ = is_in_another_shard;
  6490. const bool is_selected = is_runnable && !is_in_another_shard;
  6491. num_runnable_tests += is_runnable;
  6492. num_selected_tests += is_selected;
  6493. test_info->should_run_ = is_selected;
  6494. test_suite->set_should_run(test_suite->should_run() || is_selected);
  6495. }
  6496. }
  6497. return num_selected_tests;
  6498. }
  6499. // Prints the given C-string on a single line by replacing all '\n'
  6500. // characters with string "\\n". If the output takes more than
  6501. // max_length characters, only prints the first max_length characters
  6502. // and "...".
  6503. static void PrintOnOneLine(const char* str, int max_length) {
  6504. if (str != nullptr) {
  6505. for (int i = 0; *str != '\0'; ++str) {
  6506. if (i >= max_length) {
  6507. printf("...");
  6508. break;
  6509. }
  6510. if (*str == '\n') {
  6511. printf("\\n");
  6512. i += 2;
  6513. } else {
  6514. printf("%c", *str);
  6515. ++i;
  6516. }
  6517. }
  6518. }
  6519. }
  6520. // Prints the names of the tests matching the user-specified filter flag.
  6521. void UnitTestImpl::ListTestsMatchingFilter() {
  6522. // Print at most this many characters for each type/value parameter.
  6523. const int kMaxParamLength = 250;
  6524. for (auto* test_suite : test_suites_) {
  6525. bool printed_test_suite_name = false;
  6526. for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
  6527. const TestInfo* const test_info = test_suite->test_info_list()[j];
  6528. if (test_info->matches_filter_) {
  6529. if (!printed_test_suite_name) {
  6530. printed_test_suite_name = true;
  6531. printf("%s.", test_suite->name());
  6532. if (test_suite->type_param() != nullptr) {
  6533. printf(" # %s = ", kTypeParamLabel);
  6534. // We print the type parameter on a single line to make
  6535. // the output easy to parse by a program.
  6536. PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
  6537. }
  6538. printf("\n");
  6539. }
  6540. printf(" %s", test_info->name());
  6541. if (test_info->value_param() != nullptr) {
  6542. printf(" # %s = ", kValueParamLabel);
  6543. // We print the value parameter on a single line to make the
  6544. // output easy to parse by a program.
  6545. PrintOnOneLine(test_info->value_param(), kMaxParamLength);
  6546. }
  6547. printf("\n");
  6548. }
  6549. }
  6550. }
  6551. fflush(stdout);
  6552. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  6553. if (output_format == "xml" || output_format == "json") {
  6554. FILE* fileout = OpenFileForWriting(
  6555. UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
  6556. std::stringstream stream;
  6557. if (output_format == "xml") {
  6558. XmlUnitTestResultPrinter(
  6559. UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  6560. .PrintXmlTestsList(&stream, test_suites_);
  6561. } else if (output_format == "json") {
  6562. JsonUnitTestResultPrinter(
  6563. UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  6564. .PrintJsonTestList(&stream, test_suites_);
  6565. }
  6566. fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
  6567. fclose(fileout);
  6568. }
  6569. }
  6570. // Sets the OS stack trace getter.
  6571. //
  6572. // Does nothing if the input and the current OS stack trace getter are
  6573. // the same; otherwise, deletes the old getter and makes the input the
  6574. // current getter.
  6575. void UnitTestImpl::set_os_stack_trace_getter(
  6576. OsStackTraceGetterInterface* getter) {
  6577. if (os_stack_trace_getter_ != getter) {
  6578. delete os_stack_trace_getter_;
  6579. os_stack_trace_getter_ = getter;
  6580. }
  6581. }
  6582. // Returns the current OS stack trace getter if it is not NULL;
  6583. // otherwise, creates an OsStackTraceGetter, makes it the current
  6584. // getter, and returns it.
  6585. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
  6586. if (os_stack_trace_getter_ == nullptr) {
  6587. #ifdef GTEST_OS_STACK_TRACE_GETTER_
  6588. os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
  6589. #else
  6590. os_stack_trace_getter_ = new OsStackTraceGetter;
  6591. #endif // GTEST_OS_STACK_TRACE_GETTER_
  6592. }
  6593. return os_stack_trace_getter_;
  6594. }
  6595. // Returns the most specific TestResult currently running.
  6596. TestResult* UnitTestImpl::current_test_result() {
  6597. if (current_test_info_ != nullptr) {
  6598. return &current_test_info_->result_;
  6599. }
  6600. if (current_test_suite_ != nullptr) {
  6601. return &current_test_suite_->ad_hoc_test_result_;
  6602. }
  6603. return &ad_hoc_test_result_;
  6604. }
  6605. // Shuffles all test suites, and the tests within each test suite,
  6606. // making sure that death tests are still run first.
  6607. void UnitTestImpl::ShuffleTests() {
  6608. // Shuffles the death test suites.
  6609. ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
  6610. // Shuffles the non-death test suites.
  6611. ShuffleRange(random(), last_death_test_suite_ + 1,
  6612. static_cast<int>(test_suites_.size()), &test_suite_indices_);
  6613. // Shuffles the tests inside each test suite.
  6614. for (auto& test_suite : test_suites_) {
  6615. test_suite->ShuffleTests(random());
  6616. }
  6617. }
  6618. // Restores the test suites and tests to their order before the first shuffle.
  6619. void UnitTestImpl::UnshuffleTests() {
  6620. for (size_t i = 0; i < test_suites_.size(); i++) {
  6621. // Unshuffles the tests in each test suite.
  6622. test_suites_[i]->UnshuffleTests();
  6623. // Resets the index of each test suite.
  6624. test_suite_indices_[i] = static_cast<int>(i);
  6625. }
  6626. }
  6627. // Returns the current OS stack trace as an std::string.
  6628. //
  6629. // The maximum number of stack frames to be included is specified by
  6630. // the gtest_stack_trace_depth flag. The skip_count parameter
  6631. // specifies the number of top frames to be skipped, which doesn't
  6632. // count against the number of frames to be included.
  6633. //
  6634. // For example, if Foo() calls Bar(), which in turn calls
  6635. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  6636. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  6637. std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
  6638. int skip_count) {
  6639. // We pass skip_count + 1 to skip this wrapper function in addition
  6640. // to what the user really wants to skip.
  6641. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
  6642. }
  6643. // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
  6644. // suppress unreachable code warnings.
  6645. namespace {
  6646. class ClassUniqueToAlwaysTrue {};
  6647. }
  6648. bool IsTrue(bool condition) { return condition; }
  6649. bool AlwaysTrue() {
  6650. #if GTEST_HAS_EXCEPTIONS
  6651. // This condition is always false so AlwaysTrue() never actually throws,
  6652. // but it makes the compiler think that it may throw.
  6653. if (IsTrue(false))
  6654. throw ClassUniqueToAlwaysTrue();
  6655. #endif // GTEST_HAS_EXCEPTIONS
  6656. return true;
  6657. }
  6658. // If *pstr starts with the given prefix, modifies *pstr to be right
  6659. // past the prefix and returns true; otherwise leaves *pstr unchanged
  6660. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  6661. bool SkipPrefix(const char* prefix, const char** pstr) {
  6662. const size_t prefix_len = strlen(prefix);
  6663. if (strncmp(*pstr, prefix, prefix_len) == 0) {
  6664. *pstr += prefix_len;
  6665. return true;
  6666. }
  6667. return false;
  6668. }
  6669. // Parses a string as a command line flag. The string should have
  6670. // the format "--flag=value". When def_optional is true, the "=value"
  6671. // part can be omitted.
  6672. //
  6673. // Returns the value of the flag, or NULL if the parsing failed.
  6674. static const char* ParseFlagValue(const char* str, const char* flag,
  6675. bool def_optional) {
  6676. // str and flag must not be NULL.
  6677. if (str == nullptr || flag == nullptr) return nullptr;
  6678. // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
  6679. const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
  6680. const size_t flag_len = flag_str.length();
  6681. if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
  6682. // Skips the flag name.
  6683. const char* flag_end = str + flag_len;
  6684. // When def_optional is true, it's OK to not have a "=value" part.
  6685. if (def_optional && (flag_end[0] == '\0')) {
  6686. return flag_end;
  6687. }
  6688. // If def_optional is true and there are more characters after the
  6689. // flag name, or if def_optional is false, there must be a '=' after
  6690. // the flag name.
  6691. if (flag_end[0] != '=') return nullptr;
  6692. // Returns the string after "=".
  6693. return flag_end + 1;
  6694. }
  6695. // Parses a string for a bool flag, in the form of either
  6696. // "--flag=value" or "--flag".
  6697. //
  6698. // In the former case, the value is taken as true as long as it does
  6699. // not start with '0', 'f', or 'F'.
  6700. //
  6701. // In the latter case, the value is taken as true.
  6702. //
  6703. // On success, stores the value of the flag in *value, and returns
  6704. // true. On failure, returns false without changing *value.
  6705. static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
  6706. // Gets the value of the flag as a string.
  6707. const char* const value_str = ParseFlagValue(str, flag, true);
  6708. // Aborts if the parsing failed.
  6709. if (value_str == nullptr) return false;
  6710. // Converts the string value to a bool.
  6711. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  6712. return true;
  6713. }
  6714. // Parses a string for an int32_t flag, in the form of "--flag=value".
  6715. //
  6716. // On success, stores the value of the flag in *value, and returns
  6717. // true. On failure, returns false without changing *value.
  6718. bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) {
  6719. // Gets the value of the flag as a string.
  6720. const char* const value_str = ParseFlagValue(str, flag, false);
  6721. // Aborts if the parsing failed.
  6722. if (value_str == nullptr) return false;
  6723. // Sets *value to the value of the flag.
  6724. return ParseInt32(Message() << "The value of flag --" << flag,
  6725. value_str, value);
  6726. }
  6727. // Parses a string for a string flag, in the form of "--flag=value".
  6728. //
  6729. // On success, stores the value of the flag in *value, and returns
  6730. // true. On failure, returns false without changing *value.
  6731. template <typename String>
  6732. static bool ParseStringFlag(const char* str, const char* flag, String* value) {
  6733. // Gets the value of the flag as a string.
  6734. const char* const value_str = ParseFlagValue(str, flag, false);
  6735. // Aborts if the parsing failed.
  6736. if (value_str == nullptr) return false;
  6737. // Sets *value to the value of the flag.
  6738. *value = value_str;
  6739. return true;
  6740. }
  6741. // Determines whether a string has a prefix that Google Test uses for its
  6742. // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
  6743. // If Google Test detects that a command line flag has its prefix but is not
  6744. // recognized, it will print its help message. Flags starting with
  6745. // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
  6746. // internal flags and do not trigger the help message.
  6747. static bool HasGoogleTestFlagPrefix(const char* str) {
  6748. return (SkipPrefix("--", &str) ||
  6749. SkipPrefix("-", &str) ||
  6750. SkipPrefix("/", &str)) &&
  6751. !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
  6752. (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
  6753. SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
  6754. }
  6755. // Prints a string containing code-encoded text. The following escape
  6756. // sequences can be used in the string to control the text color:
  6757. //
  6758. // @@ prints a single '@' character.
  6759. // @R changes the color to red.
  6760. // @G changes the color to green.
  6761. // @Y changes the color to yellow.
  6762. // @D changes to the default terminal text color.
  6763. //
  6764. static void PrintColorEncoded(const char* str) {
  6765. GTestColor color = GTestColor::kDefault; // The current color.
  6766. // Conceptually, we split the string into segments divided by escape
  6767. // sequences. Then we print one segment at a time. At the end of
  6768. // each iteration, the str pointer advances to the beginning of the
  6769. // next segment.
  6770. for (;;) {
  6771. const char* p = strchr(str, '@');
  6772. if (p == nullptr) {
  6773. ColoredPrintf(color, "%s", str);
  6774. return;
  6775. }
  6776. ColoredPrintf(color, "%s", std::string(str, p).c_str());
  6777. const char ch = p[1];
  6778. str = p + 2;
  6779. if (ch == '@') {
  6780. ColoredPrintf(color, "@");
  6781. } else if (ch == 'D') {
  6782. color = GTestColor::kDefault;
  6783. } else if (ch == 'R') {
  6784. color = GTestColor::kRed;
  6785. } else if (ch == 'G') {
  6786. color = GTestColor::kGreen;
  6787. } else if (ch == 'Y') {
  6788. color = GTestColor::kYellow;
  6789. } else {
  6790. --str;
  6791. }
  6792. }
  6793. }
  6794. static const char kColorEncodedHelpMessage[] =
  6795. "This program contains tests written using " GTEST_NAME_
  6796. ". You can use the\n"
  6797. "following command line flags to control its behavior:\n"
  6798. "\n"
  6799. "Test Selection:\n"
  6800. " @G--" GTEST_FLAG_PREFIX_
  6801. "list_tests@D\n"
  6802. " List the names of all tests instead of running them. The name of\n"
  6803. " TEST(Foo, Bar) is \"Foo.Bar\".\n"
  6804. " @G--" GTEST_FLAG_PREFIX_
  6805. "filter=@YPOSITIVE_PATTERNS"
  6806. "[@G-@YNEGATIVE_PATTERNS]@D\n"
  6807. " Run only the tests whose name matches one of the positive patterns "
  6808. "but\n"
  6809. " none of the negative patterns. '?' matches any single character; "
  6810. "'*'\n"
  6811. " matches any substring; ':' separates two patterns.\n"
  6812. " @G--" GTEST_FLAG_PREFIX_
  6813. "also_run_disabled_tests@D\n"
  6814. " Run all disabled tests too.\n"
  6815. "\n"
  6816. "Test Execution:\n"
  6817. " @G--" GTEST_FLAG_PREFIX_
  6818. "repeat=@Y[COUNT]@D\n"
  6819. " Run the tests repeatedly; use a negative count to repeat forever.\n"
  6820. " @G--" GTEST_FLAG_PREFIX_
  6821. "shuffle@D\n"
  6822. " Randomize tests' orders on every iteration.\n"
  6823. " @G--" GTEST_FLAG_PREFIX_
  6824. "random_seed=@Y[NUMBER]@D\n"
  6825. " Random number seed to use for shuffling test orders (between 1 and\n"
  6826. " 99999, or 0 to use a seed based on the current time).\n"
  6827. "\n"
  6828. "Test Output:\n"
  6829. " @G--" GTEST_FLAG_PREFIX_
  6830. "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
  6831. " Enable/disable colored output. The default is @Gauto@D.\n"
  6832. " @G--" GTEST_FLAG_PREFIX_
  6833. "brief=1@D\n"
  6834. " Only print test failures.\n"
  6835. " @G--" GTEST_FLAG_PREFIX_
  6836. "print_time=0@D\n"
  6837. " Don't print the elapsed time of each test.\n"
  6838. " @G--" GTEST_FLAG_PREFIX_
  6839. "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
  6840. "@Y|@G:@YFILE_PATH]@D\n"
  6841. " Generate a JSON or XML report in the given directory or with the "
  6842. "given\n"
  6843. " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
  6844. # if GTEST_CAN_STREAM_RESULTS_
  6845. " @G--" GTEST_FLAG_PREFIX_
  6846. "stream_result_to=@YHOST@G:@YPORT@D\n"
  6847. " Stream test results to the given server.\n"
  6848. # endif // GTEST_CAN_STREAM_RESULTS_
  6849. "\n"
  6850. "Assertion Behavior:\n"
  6851. # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  6852. " @G--" GTEST_FLAG_PREFIX_
  6853. "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
  6854. " Set the default death test style.\n"
  6855. # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  6856. " @G--" GTEST_FLAG_PREFIX_
  6857. "break_on_failure@D\n"
  6858. " Turn assertion failures into debugger break-points.\n"
  6859. " @G--" GTEST_FLAG_PREFIX_
  6860. "throw_on_failure@D\n"
  6861. " Turn assertion failures into C++ exceptions for use by an external\n"
  6862. " test framework.\n"
  6863. " @G--" GTEST_FLAG_PREFIX_
  6864. "catch_exceptions=0@D\n"
  6865. " Do not report exceptions as test failures. Instead, allow them\n"
  6866. " to crash the program or throw a pop-up (on Windows).\n"
  6867. "\n"
  6868. "Except for @G--" GTEST_FLAG_PREFIX_
  6869. "list_tests@D, you can alternatively set "
  6870. "the corresponding\n"
  6871. "environment variable of a flag (all letters in upper-case). For example, "
  6872. "to\n"
  6873. "disable colored text output, you can either specify "
  6874. "@G--" GTEST_FLAG_PREFIX_
  6875. "color=no@D or set\n"
  6876. "the @G" GTEST_FLAG_PREFIX_UPPER_
  6877. "COLOR@D environment variable to @Gno@D.\n"
  6878. "\n"
  6879. "For more information, please read the " GTEST_NAME_
  6880. " documentation at\n"
  6881. "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_
  6882. "\n"
  6883. "(not one in your own code or tests), please report it to\n"
  6884. "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
  6885. static bool ParseGoogleTestFlag(const char* const arg) {
  6886. return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
  6887. &GTEST_FLAG(also_run_disabled_tests)) ||
  6888. ParseBoolFlag(arg, kBreakOnFailureFlag,
  6889. &GTEST_FLAG(break_on_failure)) ||
  6890. ParseBoolFlag(arg, kCatchExceptionsFlag,
  6891. &GTEST_FLAG(catch_exceptions)) ||
  6892. ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
  6893. ParseStringFlag(arg, kDeathTestStyleFlag,
  6894. &GTEST_FLAG(death_test_style)) ||
  6895. ParseBoolFlag(arg, kDeathTestUseFork,
  6896. &GTEST_FLAG(death_test_use_fork)) ||
  6897. ParseBoolFlag(arg, kFailFast, &GTEST_FLAG(fail_fast)) ||
  6898. ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
  6899. ParseStringFlag(arg, kInternalRunDeathTestFlag,
  6900. &GTEST_FLAG(internal_run_death_test)) ||
  6901. ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
  6902. ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
  6903. ParseBoolFlag(arg, kBriefFlag, &GTEST_FLAG(brief)) ||
  6904. ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
  6905. ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
  6906. ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
  6907. ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
  6908. ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
  6909. ParseInt32Flag(arg, kStackTraceDepthFlag,
  6910. &GTEST_FLAG(stack_trace_depth)) ||
  6911. ParseStringFlag(arg, kStreamResultToFlag,
  6912. &GTEST_FLAG(stream_result_to)) ||
  6913. ParseBoolFlag(arg, kThrowOnFailureFlag, &GTEST_FLAG(throw_on_failure));
  6914. }
  6915. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  6916. static void LoadFlagsFromFile(const std::string& path) {
  6917. FILE* flagfile = posix::FOpen(path.c_str(), "r");
  6918. if (!flagfile) {
  6919. GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
  6920. << "\"";
  6921. }
  6922. std::string contents(ReadEntireFile(flagfile));
  6923. posix::FClose(flagfile);
  6924. std::vector<std::string> lines;
  6925. SplitString(contents, '\n', &lines);
  6926. for (size_t i = 0; i < lines.size(); ++i) {
  6927. if (lines[i].empty())
  6928. continue;
  6929. if (!ParseGoogleTestFlag(lines[i].c_str()))
  6930. g_help_flag = true;
  6931. }
  6932. }
  6933. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  6934. // Parses the command line for Google Test flags, without initializing
  6935. // other parts of Google Test. The type parameter CharType can be
  6936. // instantiated to either char or wchar_t.
  6937. template <typename CharType>
  6938. void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
  6939. for (int i = 1; i < *argc; i++) {
  6940. const std::string arg_string = StreamableToString(argv[i]);
  6941. const char* const arg = arg_string.c_str();
  6942. using internal::ParseBoolFlag;
  6943. using internal::ParseInt32Flag;
  6944. using internal::ParseStringFlag;
  6945. bool remove_flag = false;
  6946. if (ParseGoogleTestFlag(arg)) {
  6947. remove_flag = true;
  6948. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  6949. } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
  6950. LoadFlagsFromFile(GTEST_FLAG(flagfile));
  6951. remove_flag = true;
  6952. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  6953. } else if (arg_string == "--help" || arg_string == "-h" ||
  6954. arg_string == "-?" || arg_string == "/?" ||
  6955. HasGoogleTestFlagPrefix(arg)) {
  6956. // Both help flag and unrecognized Google Test flags (excluding
  6957. // internal ones) trigger help display.
  6958. g_help_flag = true;
  6959. }
  6960. if (remove_flag) {
  6961. // Shift the remainder of the argv list left by one. Note
  6962. // that argv has (*argc + 1) elements, the last one always being
  6963. // NULL. The following loop moves the trailing NULL element as
  6964. // well.
  6965. for (int j = i; j != *argc; j++) {
  6966. argv[j] = argv[j + 1];
  6967. }
  6968. // Decrements the argument count.
  6969. (*argc)--;
  6970. // We also need to decrement the iterator as we just removed
  6971. // an element.
  6972. i--;
  6973. }
  6974. }
  6975. if (g_help_flag) {
  6976. // We print the help here instead of in RUN_ALL_TESTS(), as the
  6977. // latter may not be called at all if the user is using Google
  6978. // Test with another testing framework.
  6979. PrintColorEncoded(kColorEncodedHelpMessage);
  6980. }
  6981. }
  6982. // Parses the command line for Google Test flags, without initializing
  6983. // other parts of Google Test.
  6984. void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
  6985. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  6986. // Fix the value of *_NSGetArgc() on macOS, but if and only if
  6987. // *_NSGetArgv() == argv
  6988. // Only applicable to char** version of argv
  6989. #if GTEST_OS_MAC
  6990. #ifndef GTEST_OS_IOS
  6991. if (*_NSGetArgv() == argv) {
  6992. *_NSGetArgc() = *argc;
  6993. }
  6994. #endif
  6995. #endif
  6996. }
  6997. void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
  6998. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  6999. }
  7000. // The internal implementation of InitGoogleTest().
  7001. //
  7002. // The type parameter CharType can be instantiated to either char or
  7003. // wchar_t.
  7004. template <typename CharType>
  7005. void InitGoogleTestImpl(int* argc, CharType** argv) {
  7006. // We don't want to run the initialization code twice.
  7007. if (GTestIsInitialized()) return;
  7008. if (*argc <= 0) return;
  7009. g_argvs.clear();
  7010. for (int i = 0; i != *argc; i++) {
  7011. g_argvs.push_back(StreamableToString(argv[i]));
  7012. }
  7013. #if GTEST_HAS_ABSL
  7014. absl::InitializeSymbolizer(g_argvs[0].c_str());
  7015. #endif // GTEST_HAS_ABSL
  7016. ParseGoogleTestFlagsOnly(argc, argv);
  7017. GetUnitTestImpl()->PostFlagParsingInit();
  7018. }
  7019. } // namespace internal
  7020. // Initializes Google Test. This must be called before calling
  7021. // RUN_ALL_TESTS(). In particular, it parses a command line for the
  7022. // flags that Google Test recognizes. Whenever a Google Test flag is
  7023. // seen, it is removed from argv, and *argc is decremented.
  7024. //
  7025. // No value is returned. Instead, the Google Test flag variables are
  7026. // updated.
  7027. //
  7028. // Calling the function for the second time has no user-visible effect.
  7029. void InitGoogleTest(int* argc, char** argv) {
  7030. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7031. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  7032. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7033. internal::InitGoogleTestImpl(argc, argv);
  7034. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7035. }
  7036. // This overloaded version can be used in Windows programs compiled in
  7037. // UNICODE mode.
  7038. void InitGoogleTest(int* argc, wchar_t** argv) {
  7039. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7040. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  7041. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7042. internal::InitGoogleTestImpl(argc, argv);
  7043. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7044. }
  7045. // This overloaded version can be used on Arduino/embedded platforms where
  7046. // there is no argc/argv.
  7047. void InitGoogleTest() {
  7048. // Since Arduino doesn't have a command line, fake out the argc/argv arguments
  7049. int argc = 1;
  7050. const auto arg0 = "dummy";
  7051. char* argv0 = const_cast<char*>(arg0);
  7052. char** argv = &argv0;
  7053. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7054. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
  7055. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7056. internal::InitGoogleTestImpl(&argc, argv);
  7057. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  7058. }
  7059. std::string TempDir() {
  7060. #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
  7061. return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
  7062. #elif GTEST_OS_WINDOWS_MOBILE
  7063. return "\\temp\\";
  7064. #elif GTEST_OS_WINDOWS
  7065. const char* temp_dir = internal::posix::GetEnv("TEMP");
  7066. if (temp_dir == nullptr || temp_dir[0] == '\0') {
  7067. return "\\temp\\";
  7068. } else if (temp_dir[strlen(temp_dir) - 1] == '\\') {
  7069. return temp_dir;
  7070. } else {
  7071. return std::string(temp_dir) + "\\";
  7072. }
  7073. #elif GTEST_OS_LINUX_ANDROID
  7074. const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR");
  7075. if (temp_dir == nullptr || temp_dir[0] == '\0') {
  7076. return "/data/local/tmp/";
  7077. } else {
  7078. return temp_dir;
  7079. }
  7080. #elif GTEST_OS_LINUX
  7081. const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR");
  7082. if (temp_dir == nullptr || temp_dir[0] == '\0') {
  7083. return "/tmp/";
  7084. } else {
  7085. return temp_dir;
  7086. }
  7087. #else
  7088. return "/tmp/";
  7089. #endif // GTEST_OS_WINDOWS_MOBILE
  7090. }
  7091. // Class ScopedTrace
  7092. // Pushes the given source file location and message onto a per-thread
  7093. // trace stack maintained by Google Test.
  7094. void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
  7095. internal::TraceInfo trace;
  7096. trace.file = file;
  7097. trace.line = line;
  7098. trace.message.swap(message);
  7099. UnitTest::GetInstance()->PushGTestTrace(trace);
  7100. }
  7101. // Pops the info pushed by the c'tor.
  7102. ScopedTrace::~ScopedTrace()
  7103. GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
  7104. UnitTest::GetInstance()->PopGTestTrace();
  7105. }
  7106. } // namespace testing
  7107. // Copyright 2005, Google Inc.
  7108. // All rights reserved.
  7109. //
  7110. // Redistribution and use in source and binary forms, with or without
  7111. // modification, are permitted provided that the following conditions are
  7112. // met:
  7113. //
  7114. // * Redistributions of source code must retain the above copyright
  7115. // notice, this list of conditions and the following disclaimer.
  7116. // * Redistributions in binary form must reproduce the above
  7117. // copyright notice, this list of conditions and the following disclaimer
  7118. // in the documentation and/or other materials provided with the
  7119. // distribution.
  7120. // * Neither the name of Google Inc. nor the names of its
  7121. // contributors may be used to endorse or promote products derived from
  7122. // this software without specific prior written permission.
  7123. //
  7124. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7125. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7126. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7127. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7128. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7129. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7130. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7131. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7132. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7133. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7134. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7135. //
  7136. // This file implements death tests.
  7137. #include <functional>
  7138. #include <utility>
  7139. #if GTEST_HAS_DEATH_TEST
  7140. # if GTEST_OS_MAC
  7141. # include <crt_externs.h>
  7142. # endif // GTEST_OS_MAC
  7143. # include <errno.h>
  7144. # include <fcntl.h>
  7145. # include <limits.h>
  7146. # if GTEST_OS_LINUX
  7147. # include <signal.h>
  7148. # endif // GTEST_OS_LINUX
  7149. # include <stdarg.h>
  7150. # if GTEST_OS_WINDOWS
  7151. # include <windows.h>
  7152. # else
  7153. # include <sys/mman.h>
  7154. # include <sys/wait.h>
  7155. # endif // GTEST_OS_WINDOWS
  7156. # if GTEST_OS_QNX
  7157. # include <spawn.h>
  7158. # endif // GTEST_OS_QNX
  7159. # if GTEST_OS_FUCHSIA
  7160. # include <lib/fdio/fd.h>
  7161. # include <lib/fdio/io.h>
  7162. # include <lib/fdio/spawn.h>
  7163. # include <lib/zx/channel.h>
  7164. # include <lib/zx/port.h>
  7165. # include <lib/zx/process.h>
  7166. # include <lib/zx/socket.h>
  7167. # include <zircon/processargs.h>
  7168. # include <zircon/syscalls.h>
  7169. # include <zircon/syscalls/policy.h>
  7170. # include <zircon/syscalls/port.h>
  7171. # endif // GTEST_OS_FUCHSIA
  7172. #endif // GTEST_HAS_DEATH_TEST
  7173. namespace testing {
  7174. // Constants.
  7175. // The default death test style.
  7176. //
  7177. // This is defined in internal/gtest-port.h as "fast", but can be overridden by
  7178. // a definition in internal/custom/gtest-port.h. The recommended value, which is
  7179. // used internally at Google, is "threadsafe".
  7180. static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
  7181. GTEST_DEFINE_string_(
  7182. death_test_style,
  7183. internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
  7184. "Indicates how to run a death test in a forked child process: "
  7185. "\"threadsafe\" (child process re-executes the test binary "
  7186. "from the beginning, running only the specific death test) or "
  7187. "\"fast\" (child process runs the death test immediately "
  7188. "after forking).");
  7189. GTEST_DEFINE_bool_(
  7190. death_test_use_fork,
  7191. internal::BoolFromGTestEnv("death_test_use_fork", false),
  7192. "Instructs to use fork()/_exit() instead of clone() in death tests. "
  7193. "Ignored and always uses fork() on POSIX systems where clone() is not "
  7194. "implemented. Useful when running under valgrind or similar tools if "
  7195. "those do not support clone(). Valgrind 3.3.1 will just fail if "
  7196. "it sees an unsupported combination of clone() flags. "
  7197. "It is not recommended to use this flag w/o valgrind though it will "
  7198. "work in 99% of the cases. Once valgrind is fixed, this flag will "
  7199. "most likely be removed.");
  7200. namespace internal {
  7201. GTEST_DEFINE_string_(
  7202. internal_run_death_test, "",
  7203. "Indicates the file, line number, temporal index of "
  7204. "the single death test to run, and a file descriptor to "
  7205. "which a success code may be sent, all separated by "
  7206. "the '|' characters. This flag is specified if and only if the "
  7207. "current process is a sub-process launched for running a thread-safe "
  7208. "death test. FOR INTERNAL USE ONLY.");
  7209. } // namespace internal
  7210. #if GTEST_HAS_DEATH_TEST
  7211. namespace internal {
  7212. // Valid only for fast death tests. Indicates the code is running in the
  7213. // child process of a fast style death test.
  7214. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  7215. static bool g_in_fast_death_test_child = false;
  7216. # endif
  7217. // Returns a Boolean value indicating whether the caller is currently
  7218. // executing in the context of the death test child process. Tools such as
  7219. // Valgrind heap checkers may need this to modify their behavior in death
  7220. // tests. IMPORTANT: This is an internal utility. Using it may break the
  7221. // implementation of death tests. User code MUST NOT use it.
  7222. bool InDeathTestChild() {
  7223. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  7224. // On Windows and Fuchsia, death tests are thread-safe regardless of the value
  7225. // of the death_test_style flag.
  7226. return !GTEST_FLAG(internal_run_death_test).empty();
  7227. # else
  7228. if (GTEST_FLAG(death_test_style) == "threadsafe")
  7229. return !GTEST_FLAG(internal_run_death_test).empty();
  7230. else
  7231. return g_in_fast_death_test_child;
  7232. #endif
  7233. }
  7234. } // namespace internal
  7235. // ExitedWithCode constructor.
  7236. ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
  7237. }
  7238. // ExitedWithCode function-call operator.
  7239. bool ExitedWithCode::operator()(int exit_status) const {
  7240. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  7241. return exit_status == exit_code_;
  7242. # else
  7243. return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
  7244. # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  7245. }
  7246. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  7247. // KilledBySignal constructor.
  7248. KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
  7249. }
  7250. // KilledBySignal function-call operator.
  7251. bool KilledBySignal::operator()(int exit_status) const {
  7252. # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
  7253. {
  7254. bool result;
  7255. if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
  7256. return result;
  7257. }
  7258. }
  7259. # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
  7260. return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
  7261. }
  7262. # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  7263. namespace internal {
  7264. // Utilities needed for death tests.
  7265. // Generates a textual description of a given exit code, in the format
  7266. // specified by wait(2).
  7267. static std::string ExitSummary(int exit_code) {
  7268. Message m;
  7269. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  7270. m << "Exited with exit status " << exit_code;
  7271. # else
  7272. if (WIFEXITED(exit_code)) {
  7273. m << "Exited with exit status " << WEXITSTATUS(exit_code);
  7274. } else if (WIFSIGNALED(exit_code)) {
  7275. m << "Terminated by signal " << WTERMSIG(exit_code);
  7276. }
  7277. # ifdef WCOREDUMP
  7278. if (WCOREDUMP(exit_code)) {
  7279. m << " (core dumped)";
  7280. }
  7281. # endif
  7282. # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  7283. return m.GetString();
  7284. }
  7285. // Returns true if exit_status describes a process that was terminated
  7286. // by a signal, or exited normally with a nonzero exit code.
  7287. bool ExitedUnsuccessfully(int exit_status) {
  7288. return !ExitedWithCode(0)(exit_status);
  7289. }
  7290. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  7291. // Generates a textual failure message when a death test finds more than
  7292. // one thread running, or cannot determine the number of threads, prior
  7293. // to executing the given statement. It is the responsibility of the
  7294. // caller not to pass a thread_count of 1.
  7295. static std::string DeathTestThreadWarning(size_t thread_count) {
  7296. Message msg;
  7297. msg << "Death tests use fork(), which is unsafe particularly"
  7298. << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
  7299. if (thread_count == 0) {
  7300. msg << "couldn't detect the number of threads.";
  7301. } else {
  7302. msg << "detected " << thread_count << " threads.";
  7303. }
  7304. msg << " See "
  7305. "https://github.com/google/googletest/blob/master/docs/"
  7306. "advanced.md#death-tests-and-threads"
  7307. << " for more explanation and suggested solutions, especially if"
  7308. << " this is the last message you see before your test times out.";
  7309. return msg.GetString();
  7310. }
  7311. # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  7312. // Flag characters for reporting a death test that did not die.
  7313. static const char kDeathTestLived = 'L';
  7314. static const char kDeathTestReturned = 'R';
  7315. static const char kDeathTestThrew = 'T';
  7316. static const char kDeathTestInternalError = 'I';
  7317. #if GTEST_OS_FUCHSIA
  7318. // File descriptor used for the pipe in the child process.
  7319. static const int kFuchsiaReadPipeFd = 3;
  7320. #endif
  7321. // An enumeration describing all of the possible ways that a death test can
  7322. // conclude. DIED means that the process died while executing the test
  7323. // code; LIVED means that process lived beyond the end of the test code;
  7324. // RETURNED means that the test statement attempted to execute a return
  7325. // statement, which is not allowed; THREW means that the test statement
  7326. // returned control by throwing an exception. IN_PROGRESS means the test
  7327. // has not yet concluded.
  7328. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
  7329. // Routine for aborting the program which is safe to call from an
  7330. // exec-style death test child process, in which case the error
  7331. // message is propagated back to the parent process. Otherwise, the
  7332. // message is simply printed to stderr. In either case, the program
  7333. // then exits with status 1.
  7334. static void DeathTestAbort(const std::string& message) {
  7335. // On a POSIX system, this function may be called from a threadsafe-style
  7336. // death test child process, which operates on a very small stack. Use
  7337. // the heap for any additional non-minuscule memory requirements.
  7338. const InternalRunDeathTestFlag* const flag =
  7339. GetUnitTestImpl()->internal_run_death_test_flag();
  7340. if (flag != nullptr) {
  7341. FILE* parent = posix::FDOpen(flag->write_fd(), "w");
  7342. fputc(kDeathTestInternalError, parent);
  7343. fprintf(parent, "%s", message.c_str());
  7344. fflush(parent);
  7345. _exit(1);
  7346. } else {
  7347. fprintf(stderr, "%s", message.c_str());
  7348. fflush(stderr);
  7349. posix::Abort();
  7350. }
  7351. }
  7352. // A replacement for CHECK that calls DeathTestAbort if the assertion
  7353. // fails.
  7354. # define GTEST_DEATH_TEST_CHECK_(expression) \
  7355. do { \
  7356. if (!::testing::internal::IsTrue(expression)) { \
  7357. DeathTestAbort( \
  7358. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  7359. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  7360. + #expression); \
  7361. } \
  7362. } while (::testing::internal::AlwaysFalse())
  7363. // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
  7364. // evaluating any system call that fulfills two conditions: it must return
  7365. // -1 on failure, and set errno to EINTR when it is interrupted and
  7366. // should be tried again. The macro expands to a loop that repeatedly
  7367. // evaluates the expression as long as it evaluates to -1 and sets
  7368. // errno to EINTR. If the expression evaluates to -1 but errno is
  7369. // something other than EINTR, DeathTestAbort is called.
  7370. # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
  7371. do { \
  7372. int gtest_retval; \
  7373. do { \
  7374. gtest_retval = (expression); \
  7375. } while (gtest_retval == -1 && errno == EINTR); \
  7376. if (gtest_retval == -1) { \
  7377. DeathTestAbort( \
  7378. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  7379. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  7380. + #expression + " != -1"); \
  7381. } \
  7382. } while (::testing::internal::AlwaysFalse())
  7383. // Returns the message describing the last system error in errno.
  7384. std::string GetLastErrnoDescription() {
  7385. return errno == 0 ? "" : posix::StrError(errno);
  7386. }
  7387. // This is called from a death test parent process to read a failure
  7388. // message from the death test child process and log it with the FATAL
  7389. // severity. On Windows, the message is read from a pipe handle. On other
  7390. // platforms, it is read from a file descriptor.
  7391. static void FailFromInternalError(int fd) {
  7392. Message error;
  7393. char buffer[256];
  7394. int num_read;
  7395. do {
  7396. while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
  7397. buffer[num_read] = '\0';
  7398. error << buffer;
  7399. }
  7400. } while (num_read == -1 && errno == EINTR);
  7401. if (num_read == 0) {
  7402. GTEST_LOG_(FATAL) << error.GetString();
  7403. } else {
  7404. const int last_error = errno;
  7405. GTEST_LOG_(FATAL) << "Error while reading death test internal: "
  7406. << GetLastErrnoDescription() << " [" << last_error << "]";
  7407. }
  7408. }
  7409. // Death test constructor. Increments the running death test count
  7410. // for the current test.
  7411. DeathTest::DeathTest() {
  7412. TestInfo* const info = GetUnitTestImpl()->current_test_info();
  7413. if (info == nullptr) {
  7414. DeathTestAbort("Cannot run a death test outside of a TEST or "
  7415. "TEST_F construct");
  7416. }
  7417. }
  7418. // Creates and returns a death test by dispatching to the current
  7419. // death test factory.
  7420. bool DeathTest::Create(const char* statement,
  7421. Matcher<const std::string&> matcher, const char* file,
  7422. int line, DeathTest** test) {
  7423. return GetUnitTestImpl()->death_test_factory()->Create(
  7424. statement, std::move(matcher), file, line, test);
  7425. }
  7426. const char* DeathTest::LastMessage() {
  7427. return last_death_test_message_.c_str();
  7428. }
  7429. void DeathTest::set_last_death_test_message(const std::string& message) {
  7430. last_death_test_message_ = message;
  7431. }
  7432. std::string DeathTest::last_death_test_message_;
  7433. // Provides cross platform implementation for some death functionality.
  7434. class DeathTestImpl : public DeathTest {
  7435. protected:
  7436. DeathTestImpl(const char* a_statement, Matcher<const std::string&> matcher)
  7437. : statement_(a_statement),
  7438. matcher_(std::move(matcher)),
  7439. spawned_(false),
  7440. status_(-1),
  7441. outcome_(IN_PROGRESS),
  7442. read_fd_(-1),
  7443. write_fd_(-1) {}
  7444. // read_fd_ is expected to be closed and cleared by a derived class.
  7445. ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
  7446. void Abort(AbortReason reason) override;
  7447. bool Passed(bool status_ok) override;
  7448. const char* statement() const { return statement_; }
  7449. bool spawned() const { return spawned_; }
  7450. void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
  7451. int status() const { return status_; }
  7452. void set_status(int a_status) { status_ = a_status; }
  7453. DeathTestOutcome outcome() const { return outcome_; }
  7454. void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
  7455. int read_fd() const { return read_fd_; }
  7456. void set_read_fd(int fd) { read_fd_ = fd; }
  7457. int write_fd() const { return write_fd_; }
  7458. void set_write_fd(int fd) { write_fd_ = fd; }
  7459. // Called in the parent process only. Reads the result code of the death
  7460. // test child process via a pipe, interprets it to set the outcome_
  7461. // member, and closes read_fd_. Outputs diagnostics and terminates in
  7462. // case of unexpected codes.
  7463. void ReadAndInterpretStatusByte();
  7464. // Returns stderr output from the child process.
  7465. virtual std::string GetErrorLogs();
  7466. private:
  7467. // The textual content of the code this object is testing. This class
  7468. // doesn't own this string and should not attempt to delete it.
  7469. const char* const statement_;
  7470. // A matcher that's expected to match the stderr output by the child process.
  7471. Matcher<const std::string&> matcher_;
  7472. // True if the death test child process has been successfully spawned.
  7473. bool spawned_;
  7474. // The exit status of the child process.
  7475. int status_;
  7476. // How the death test concluded.
  7477. DeathTestOutcome outcome_;
  7478. // Descriptor to the read end of the pipe to the child process. It is
  7479. // always -1 in the child process. The child keeps its write end of the
  7480. // pipe in write_fd_.
  7481. int read_fd_;
  7482. // Descriptor to the child's write end of the pipe to the parent process.
  7483. // It is always -1 in the parent process. The parent keeps its end of the
  7484. // pipe in read_fd_.
  7485. int write_fd_;
  7486. };
  7487. // Called in the parent process only. Reads the result code of the death
  7488. // test child process via a pipe, interprets it to set the outcome_
  7489. // member, and closes read_fd_. Outputs diagnostics and terminates in
  7490. // case of unexpected codes.
  7491. void DeathTestImpl::ReadAndInterpretStatusByte() {
  7492. char flag;
  7493. int bytes_read;
  7494. // The read() here blocks until data is available (signifying the
  7495. // failure of the death test) or until the pipe is closed (signifying
  7496. // its success), so it's okay to call this in the parent before
  7497. // the child process has exited.
  7498. do {
  7499. bytes_read = posix::Read(read_fd(), &flag, 1);
  7500. } while (bytes_read == -1 && errno == EINTR);
  7501. if (bytes_read == 0) {
  7502. set_outcome(DIED);
  7503. } else if (bytes_read == 1) {
  7504. switch (flag) {
  7505. case kDeathTestReturned:
  7506. set_outcome(RETURNED);
  7507. break;
  7508. case kDeathTestThrew:
  7509. set_outcome(THREW);
  7510. break;
  7511. case kDeathTestLived:
  7512. set_outcome(LIVED);
  7513. break;
  7514. case kDeathTestInternalError:
  7515. FailFromInternalError(read_fd()); // Does not return.
  7516. break;
  7517. default:
  7518. GTEST_LOG_(FATAL) << "Death test child process reported "
  7519. << "unexpected status byte ("
  7520. << static_cast<unsigned int>(flag) << ")";
  7521. }
  7522. } else {
  7523. GTEST_LOG_(FATAL) << "Read from death test child process failed: "
  7524. << GetLastErrnoDescription();
  7525. }
  7526. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
  7527. set_read_fd(-1);
  7528. }
  7529. std::string DeathTestImpl::GetErrorLogs() {
  7530. return GetCapturedStderr();
  7531. }
  7532. // Signals that the death test code which should have exited, didn't.
  7533. // Should be called only in a death test child process.
  7534. // Writes a status byte to the child's status file descriptor, then
  7535. // calls _exit(1).
  7536. void DeathTestImpl::Abort(AbortReason reason) {
  7537. // The parent process considers the death test to be a failure if
  7538. // it finds any data in our pipe. So, here we write a single flag byte
  7539. // to the pipe, then exit.
  7540. const char status_ch =
  7541. reason == TEST_DID_NOT_DIE ? kDeathTestLived :
  7542. reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
  7543. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
  7544. // We are leaking the descriptor here because on some platforms (i.e.,
  7545. // when built as Windows DLL), destructors of global objects will still
  7546. // run after calling _exit(). On such systems, write_fd_ will be
  7547. // indirectly closed from the destructor of UnitTestImpl, causing double
  7548. // close if it is also closed here. On debug configurations, double close
  7549. // may assert. As there are no in-process buffers to flush here, we are
  7550. // relying on the OS to close the descriptor after the process terminates
  7551. // when the destructors are not run.
  7552. _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
  7553. }
  7554. // Returns an indented copy of stderr output for a death test.
  7555. // This makes distinguishing death test output lines from regular log lines
  7556. // much easier.
  7557. static ::std::string FormatDeathTestOutput(const ::std::string& output) {
  7558. ::std::string ret;
  7559. for (size_t at = 0; ; ) {
  7560. const size_t line_end = output.find('\n', at);
  7561. ret += "[ DEATH ] ";
  7562. if (line_end == ::std::string::npos) {
  7563. ret += output.substr(at);
  7564. break;
  7565. }
  7566. ret += output.substr(at, line_end + 1 - at);
  7567. at = line_end + 1;
  7568. }
  7569. return ret;
  7570. }
  7571. // Assesses the success or failure of a death test, using both private
  7572. // members which have previously been set, and one argument:
  7573. //
  7574. // Private data members:
  7575. // outcome: An enumeration describing how the death test
  7576. // concluded: DIED, LIVED, THREW, or RETURNED. The death test
  7577. // fails in the latter three cases.
  7578. // status: The exit status of the child process. On *nix, it is in the
  7579. // in the format specified by wait(2). On Windows, this is the
  7580. // value supplied to the ExitProcess() API or a numeric code
  7581. // of the exception that terminated the program.
  7582. // matcher_: A matcher that's expected to match the stderr output by the child
  7583. // process.
  7584. //
  7585. // Argument:
  7586. // status_ok: true if exit_status is acceptable in the context of
  7587. // this particular death test, which fails if it is false
  7588. //
  7589. // Returns true if and only if all of the above conditions are met. Otherwise,
  7590. // the first failing condition, in the order given above, is the one that is
  7591. // reported. Also sets the last death test message string.
  7592. bool DeathTestImpl::Passed(bool status_ok) {
  7593. if (!spawned())
  7594. return false;
  7595. const std::string error_message = GetErrorLogs();
  7596. bool success = false;
  7597. Message buffer;
  7598. buffer << "Death test: " << statement() << "\n";
  7599. switch (outcome()) {
  7600. case LIVED:
  7601. buffer << " Result: failed to die.\n"
  7602. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  7603. break;
  7604. case THREW:
  7605. buffer << " Result: threw an exception.\n"
  7606. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  7607. break;
  7608. case RETURNED:
  7609. buffer << " Result: illegal return in test statement.\n"
  7610. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  7611. break;
  7612. case DIED:
  7613. if (status_ok) {
  7614. if (matcher_.Matches(error_message)) {
  7615. success = true;
  7616. } else {
  7617. std::ostringstream stream;
  7618. matcher_.DescribeTo(&stream);
  7619. buffer << " Result: died but not with expected error.\n"
  7620. << " Expected: " << stream.str() << "\n"
  7621. << "Actual msg:\n"
  7622. << FormatDeathTestOutput(error_message);
  7623. }
  7624. } else {
  7625. buffer << " Result: died but not with expected exit code:\n"
  7626. << " " << ExitSummary(status()) << "\n"
  7627. << "Actual msg:\n" << FormatDeathTestOutput(error_message);
  7628. }
  7629. break;
  7630. case IN_PROGRESS:
  7631. default:
  7632. GTEST_LOG_(FATAL)
  7633. << "DeathTest::Passed somehow called before conclusion of test";
  7634. }
  7635. DeathTest::set_last_death_test_message(buffer.GetString());
  7636. return success;
  7637. }
  7638. # if GTEST_OS_WINDOWS
  7639. // WindowsDeathTest implements death tests on Windows. Due to the
  7640. // specifics of starting new processes on Windows, death tests there are
  7641. // always threadsafe, and Google Test considers the
  7642. // --gtest_death_test_style=fast setting to be equivalent to
  7643. // --gtest_death_test_style=threadsafe there.
  7644. //
  7645. // A few implementation notes: Like the Linux version, the Windows
  7646. // implementation uses pipes for child-to-parent communication. But due to
  7647. // the specifics of pipes on Windows, some extra steps are required:
  7648. //
  7649. // 1. The parent creates a communication pipe and stores handles to both
  7650. // ends of it.
  7651. // 2. The parent starts the child and provides it with the information
  7652. // necessary to acquire the handle to the write end of the pipe.
  7653. // 3. The child acquires the write end of the pipe and signals the parent
  7654. // using a Windows event.
  7655. // 4. Now the parent can release the write end of the pipe on its side. If
  7656. // this is done before step 3, the object's reference count goes down to
  7657. // 0 and it is destroyed, preventing the child from acquiring it. The
  7658. // parent now has to release it, or read operations on the read end of
  7659. // the pipe will not return when the child terminates.
  7660. // 5. The parent reads child's output through the pipe (outcome code and
  7661. // any possible error messages) from the pipe, and its stderr and then
  7662. // determines whether to fail the test.
  7663. //
  7664. // Note: to distinguish Win32 API calls from the local method and function
  7665. // calls, the former are explicitly resolved in the global namespace.
  7666. //
  7667. class WindowsDeathTest : public DeathTestImpl {
  7668. public:
  7669. WindowsDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
  7670. const char* file, int line)
  7671. : DeathTestImpl(a_statement, std::move(matcher)),
  7672. file_(file),
  7673. line_(line) {}
  7674. // All of these virtual functions are inherited from DeathTest.
  7675. virtual int Wait();
  7676. virtual TestRole AssumeRole();
  7677. private:
  7678. // The name of the file in which the death test is located.
  7679. const char* const file_;
  7680. // The line number on which the death test is located.
  7681. const int line_;
  7682. // Handle to the write end of the pipe to the child process.
  7683. AutoHandle write_handle_;
  7684. // Child process handle.
  7685. AutoHandle child_handle_;
  7686. // Event the child process uses to signal the parent that it has
  7687. // acquired the handle to the write end of the pipe. After seeing this
  7688. // event the parent can release its own handles to make sure its
  7689. // ReadFile() calls return when the child terminates.
  7690. AutoHandle event_handle_;
  7691. };
  7692. // Waits for the child in a death test to exit, returning its exit
  7693. // status, or 0 if no child process exists. As a side effect, sets the
  7694. // outcome data member.
  7695. int WindowsDeathTest::Wait() {
  7696. if (!spawned())
  7697. return 0;
  7698. // Wait until the child either signals that it has acquired the write end
  7699. // of the pipe or it dies.
  7700. const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
  7701. switch (::WaitForMultipleObjects(2,
  7702. wait_handles,
  7703. FALSE, // Waits for any of the handles.
  7704. INFINITE)) {
  7705. case WAIT_OBJECT_0:
  7706. case WAIT_OBJECT_0 + 1:
  7707. break;
  7708. default:
  7709. GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
  7710. }
  7711. // The child has acquired the write end of the pipe or exited.
  7712. // We release the handle on our side and continue.
  7713. write_handle_.Reset();
  7714. event_handle_.Reset();
  7715. ReadAndInterpretStatusByte();
  7716. // Waits for the child process to exit if it haven't already. This
  7717. // returns immediately if the child has already exited, regardless of
  7718. // whether previous calls to WaitForMultipleObjects synchronized on this
  7719. // handle or not.
  7720. GTEST_DEATH_TEST_CHECK_(
  7721. WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
  7722. INFINITE));
  7723. DWORD status_code;
  7724. GTEST_DEATH_TEST_CHECK_(
  7725. ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
  7726. child_handle_.Reset();
  7727. set_status(static_cast<int>(status_code));
  7728. return status();
  7729. }
  7730. // The AssumeRole process for a Windows death test. It creates a child
  7731. // process with the same executable as the current process to run the
  7732. // death test. The child process is given the --gtest_filter and
  7733. // --gtest_internal_run_death_test flags such that it knows to run the
  7734. // current death test only.
  7735. DeathTest::TestRole WindowsDeathTest::AssumeRole() {
  7736. const UnitTestImpl* const impl = GetUnitTestImpl();
  7737. const InternalRunDeathTestFlag* const flag =
  7738. impl->internal_run_death_test_flag();
  7739. const TestInfo* const info = impl->current_test_info();
  7740. const int death_test_index = info->result()->death_test_count();
  7741. if (flag != nullptr) {
  7742. // ParseInternalRunDeathTestFlag() has performed all the necessary
  7743. // processing.
  7744. set_write_fd(flag->write_fd());
  7745. return EXECUTE_TEST;
  7746. }
  7747. // WindowsDeathTest uses an anonymous pipe to communicate results of
  7748. // a death test.
  7749. SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
  7750. nullptr, TRUE};
  7751. HANDLE read_handle, write_handle;
  7752. GTEST_DEATH_TEST_CHECK_(
  7753. ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
  7754. 0) // Default buffer size.
  7755. != FALSE);
  7756. set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
  7757. O_RDONLY));
  7758. write_handle_.Reset(write_handle);
  7759. event_handle_.Reset(::CreateEvent(
  7760. &handles_are_inheritable,
  7761. TRUE, // The event will automatically reset to non-signaled state.
  7762. FALSE, // The initial state is non-signalled.
  7763. nullptr)); // The even is unnamed.
  7764. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr);
  7765. const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
  7766. kFilterFlag + "=" + info->test_suite_name() +
  7767. "." + info->name();
  7768. const std::string internal_flag =
  7769. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
  7770. "=" + file_ + "|" + StreamableToString(line_) + "|" +
  7771. StreamableToString(death_test_index) + "|" +
  7772. StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
  7773. // size_t has the same width as pointers on both 32-bit and 64-bit
  7774. // Windows platforms.
  7775. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
  7776. "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
  7777. "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
  7778. char executable_path[_MAX_PATH + 1]; // NOLINT
  7779. GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr,
  7780. executable_path,
  7781. _MAX_PATH));
  7782. std::string command_line =
  7783. std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
  7784. internal_flag + "\"";
  7785. DeathTest::set_last_death_test_message("");
  7786. CaptureStderr();
  7787. // Flush the log buffers since the log streams are shared with the child.
  7788. FlushInfoLog();
  7789. // The child process will share the standard handles with the parent.
  7790. STARTUPINFOA startup_info;
  7791. memset(&startup_info, 0, sizeof(STARTUPINFO));
  7792. startup_info.dwFlags = STARTF_USESTDHANDLES;
  7793. startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
  7794. startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
  7795. startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
  7796. PROCESS_INFORMATION process_info;
  7797. GTEST_DEATH_TEST_CHECK_(
  7798. ::CreateProcessA(
  7799. executable_path, const_cast<char*>(command_line.c_str()),
  7800. nullptr, // Retuned process handle is not inheritable.
  7801. nullptr, // Retuned thread handle is not inheritable.
  7802. TRUE, // Child inherits all inheritable handles (for write_handle_).
  7803. 0x0, // Default creation flags.
  7804. nullptr, // Inherit the parent's environment.
  7805. UnitTest::GetInstance()->original_working_dir(), &startup_info,
  7806. &process_info) != FALSE);
  7807. child_handle_.Reset(process_info.hProcess);
  7808. ::CloseHandle(process_info.hThread);
  7809. set_spawned(true);
  7810. return OVERSEE_TEST;
  7811. }
  7812. # elif GTEST_OS_FUCHSIA
  7813. class FuchsiaDeathTest : public DeathTestImpl {
  7814. public:
  7815. FuchsiaDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
  7816. const char* file, int line)
  7817. : DeathTestImpl(a_statement, std::move(matcher)),
  7818. file_(file),
  7819. line_(line) {}
  7820. // All of these virtual functions are inherited from DeathTest.
  7821. int Wait() override;
  7822. TestRole AssumeRole() override;
  7823. std::string GetErrorLogs() override;
  7824. private:
  7825. // The name of the file in which the death test is located.
  7826. const char* const file_;
  7827. // The line number on which the death test is located.
  7828. const int line_;
  7829. // The stderr data captured by the child process.
  7830. std::string captured_stderr_;
  7831. zx::process child_process_;
  7832. zx::channel exception_channel_;
  7833. zx::socket stderr_socket_;
  7834. };
  7835. // Utility class for accumulating command-line arguments.
  7836. class Arguments {
  7837. public:
  7838. Arguments() { args_.push_back(nullptr); }
  7839. ~Arguments() {
  7840. for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
  7841. ++i) {
  7842. free(*i);
  7843. }
  7844. }
  7845. void AddArgument(const char* argument) {
  7846. args_.insert(args_.end() - 1, posix::StrDup(argument));
  7847. }
  7848. template <typename Str>
  7849. void AddArguments(const ::std::vector<Str>& arguments) {
  7850. for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
  7851. i != arguments.end();
  7852. ++i) {
  7853. args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
  7854. }
  7855. }
  7856. char* const* Argv() {
  7857. return &args_[0];
  7858. }
  7859. int size() {
  7860. return static_cast<int>(args_.size()) - 1;
  7861. }
  7862. private:
  7863. std::vector<char*> args_;
  7864. };
  7865. // Waits for the child in a death test to exit, returning its exit
  7866. // status, or 0 if no child process exists. As a side effect, sets the
  7867. // outcome data member.
  7868. int FuchsiaDeathTest::Wait() {
  7869. const int kProcessKey = 0;
  7870. const int kSocketKey = 1;
  7871. const int kExceptionKey = 2;
  7872. if (!spawned())
  7873. return 0;
  7874. // Create a port to wait for socket/task/exception events.
  7875. zx_status_t status_zx;
  7876. zx::port port;
  7877. status_zx = zx::port::create(0, &port);
  7878. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7879. // Register to wait for the child process to terminate.
  7880. status_zx = child_process_.wait_async(
  7881. port, kProcessKey, ZX_PROCESS_TERMINATED, 0);
  7882. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7883. // Register to wait for the socket to be readable or closed.
  7884. status_zx = stderr_socket_.wait_async(
  7885. port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
  7886. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7887. // Register to wait for an exception.
  7888. status_zx = exception_channel_.wait_async(
  7889. port, kExceptionKey, ZX_CHANNEL_READABLE, 0);
  7890. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7891. bool process_terminated = false;
  7892. bool socket_closed = false;
  7893. do {
  7894. zx_port_packet_t packet = {};
  7895. status_zx = port.wait(zx::time::infinite(), &packet);
  7896. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7897. if (packet.key == kExceptionKey) {
  7898. // Process encountered an exception. Kill it directly rather than
  7899. // letting other handlers process the event. We will get a kProcessKey
  7900. // event when the process actually terminates.
  7901. status_zx = child_process_.kill();
  7902. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7903. } else if (packet.key == kProcessKey) {
  7904. // Process terminated.
  7905. GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
  7906. GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
  7907. process_terminated = true;
  7908. } else if (packet.key == kSocketKey) {
  7909. GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
  7910. if (packet.signal.observed & ZX_SOCKET_READABLE) {
  7911. // Read data from the socket.
  7912. constexpr size_t kBufferSize = 1024;
  7913. do {
  7914. size_t old_length = captured_stderr_.length();
  7915. size_t bytes_read = 0;
  7916. captured_stderr_.resize(old_length + kBufferSize);
  7917. status_zx = stderr_socket_.read(
  7918. 0, &captured_stderr_.front() + old_length, kBufferSize,
  7919. &bytes_read);
  7920. captured_stderr_.resize(old_length + bytes_read);
  7921. } while (status_zx == ZX_OK);
  7922. if (status_zx == ZX_ERR_PEER_CLOSED) {
  7923. socket_closed = true;
  7924. } else {
  7925. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);
  7926. status_zx = stderr_socket_.wait_async(
  7927. port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
  7928. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7929. }
  7930. } else {
  7931. GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);
  7932. socket_closed = true;
  7933. }
  7934. }
  7935. } while (!process_terminated && !socket_closed);
  7936. ReadAndInterpretStatusByte();
  7937. zx_info_process_v2_t buffer;
  7938. status_zx = child_process_.get_info(
  7939. ZX_INFO_PROCESS_V2, &buffer, sizeof(buffer), nullptr, nullptr);
  7940. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7941. GTEST_DEATH_TEST_CHECK_(buffer.flags & ZX_INFO_PROCESS_FLAG_EXITED);
  7942. set_status(static_cast<int>(buffer.return_code));
  7943. return status();
  7944. }
  7945. // The AssumeRole process for a Fuchsia death test. It creates a child
  7946. // process with the same executable as the current process to run the
  7947. // death test. The child process is given the --gtest_filter and
  7948. // --gtest_internal_run_death_test flags such that it knows to run the
  7949. // current death test only.
  7950. DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
  7951. const UnitTestImpl* const impl = GetUnitTestImpl();
  7952. const InternalRunDeathTestFlag* const flag =
  7953. impl->internal_run_death_test_flag();
  7954. const TestInfo* const info = impl->current_test_info();
  7955. const int death_test_index = info->result()->death_test_count();
  7956. if (flag != nullptr) {
  7957. // ParseInternalRunDeathTestFlag() has performed all the necessary
  7958. // processing.
  7959. set_write_fd(kFuchsiaReadPipeFd);
  7960. return EXECUTE_TEST;
  7961. }
  7962. // Flush the log buffers since the log streams are shared with the child.
  7963. FlushInfoLog();
  7964. // Build the child process command line.
  7965. const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
  7966. kFilterFlag + "=" + info->test_suite_name() +
  7967. "." + info->name();
  7968. const std::string internal_flag =
  7969. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
  7970. + file_ + "|"
  7971. + StreamableToString(line_) + "|"
  7972. + StreamableToString(death_test_index);
  7973. Arguments args;
  7974. args.AddArguments(GetInjectableArgvs());
  7975. args.AddArgument(filter_flag.c_str());
  7976. args.AddArgument(internal_flag.c_str());
  7977. // Build the pipe for communication with the child.
  7978. zx_status_t status;
  7979. zx_handle_t child_pipe_handle;
  7980. int child_pipe_fd;
  7981. status = fdio_pipe_half(&child_pipe_fd, &child_pipe_handle);
  7982. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7983. set_read_fd(child_pipe_fd);
  7984. // Set the pipe handle for the child.
  7985. fdio_spawn_action_t spawn_actions[2] = {};
  7986. fdio_spawn_action_t* add_handle_action = &spawn_actions[0];
  7987. add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;
  7988. add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd);
  7989. add_handle_action->h.handle = child_pipe_handle;
  7990. // Create a socket pair will be used to receive the child process' stderr.
  7991. zx::socket stderr_producer_socket;
  7992. status =
  7993. zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
  7994. GTEST_DEATH_TEST_CHECK_(status >= 0);
  7995. int stderr_producer_fd = -1;
  7996. status =
  7997. fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd);
  7998. GTEST_DEATH_TEST_CHECK_(status >= 0);
  7999. // Make the stderr socket nonblocking.
  8000. GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);
  8001. fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];
  8002. add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;
  8003. add_stderr_action->fd.local_fd = stderr_producer_fd;
  8004. add_stderr_action->fd.target_fd = STDERR_FILENO;
  8005. // Create a child job.
  8006. zx_handle_t child_job = ZX_HANDLE_INVALID;
  8007. status = zx_job_create(zx_job_default(), 0, & child_job);
  8008. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  8009. zx_policy_basic_t policy;
  8010. policy.condition = ZX_POL_NEW_ANY;
  8011. policy.policy = ZX_POL_ACTION_ALLOW;
  8012. status = zx_job_set_policy(
  8013. child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);
  8014. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  8015. // Create an exception channel attached to the |child_job|, to allow
  8016. // us to suppress the system default exception handler from firing.
  8017. status =
  8018. zx_task_create_exception_channel(
  8019. child_job, 0, exception_channel_.reset_and_get_address());
  8020. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  8021. // Spawn the child process.
  8022. status = fdio_spawn_etc(
  8023. child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr,
  8024. 2, spawn_actions, child_process_.reset_and_get_address(), nullptr);
  8025. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  8026. set_spawned(true);
  8027. return OVERSEE_TEST;
  8028. }
  8029. std::string FuchsiaDeathTest::GetErrorLogs() {
  8030. return captured_stderr_;
  8031. }
  8032. #else // We are neither on Windows, nor on Fuchsia.
  8033. // ForkingDeathTest provides implementations for most of the abstract
  8034. // methods of the DeathTest interface. Only the AssumeRole method is
  8035. // left undefined.
  8036. class ForkingDeathTest : public DeathTestImpl {
  8037. public:
  8038. ForkingDeathTest(const char* statement, Matcher<const std::string&> matcher);
  8039. // All of these virtual functions are inherited from DeathTest.
  8040. int Wait() override;
  8041. protected:
  8042. void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
  8043. private:
  8044. // PID of child process during death test; 0 in the child process itself.
  8045. pid_t child_pid_;
  8046. };
  8047. // Constructs a ForkingDeathTest.
  8048. ForkingDeathTest::ForkingDeathTest(const char* a_statement,
  8049. Matcher<const std::string&> matcher)
  8050. : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}
  8051. // Waits for the child in a death test to exit, returning its exit
  8052. // status, or 0 if no child process exists. As a side effect, sets the
  8053. // outcome data member.
  8054. int ForkingDeathTest::Wait() {
  8055. if (!spawned())
  8056. return 0;
  8057. ReadAndInterpretStatusByte();
  8058. int status_value;
  8059. GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
  8060. set_status(status_value);
  8061. return status_value;
  8062. }
  8063. // A concrete death test class that forks, then immediately runs the test
  8064. // in the child process.
  8065. class NoExecDeathTest : public ForkingDeathTest {
  8066. public:
  8067. NoExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher)
  8068. : ForkingDeathTest(a_statement, std::move(matcher)) {}
  8069. TestRole AssumeRole() override;
  8070. };
  8071. // The AssumeRole process for a fork-and-run death test. It implements a
  8072. // straightforward fork, with a simple pipe to transmit the status byte.
  8073. DeathTest::TestRole NoExecDeathTest::AssumeRole() {
  8074. const size_t thread_count = GetThreadCount();
  8075. if (thread_count != 1) {
  8076. GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
  8077. }
  8078. int pipe_fd[2];
  8079. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  8080. DeathTest::set_last_death_test_message("");
  8081. CaptureStderr();
  8082. // When we fork the process below, the log file buffers are copied, but the
  8083. // file descriptors are shared. We flush all log files here so that closing
  8084. // the file descriptors in the child process doesn't throw off the
  8085. // synchronization between descriptors and buffers in the parent process.
  8086. // This is as close to the fork as possible to avoid a race condition in case
  8087. // there are multiple threads running before the death test, and another
  8088. // thread writes to the log file.
  8089. FlushInfoLog();
  8090. const pid_t child_pid = fork();
  8091. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  8092. set_child_pid(child_pid);
  8093. if (child_pid == 0) {
  8094. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
  8095. set_write_fd(pipe_fd[1]);
  8096. // Redirects all logging to stderr in the child process to prevent
  8097. // concurrent writes to the log files. We capture stderr in the parent
  8098. // process and append the child process' output to a log.
  8099. LogToStderr();
  8100. // Event forwarding to the listeners of event listener API mush be shut
  8101. // down in death test subprocesses.
  8102. GetUnitTestImpl()->listeners()->SuppressEventForwarding();
  8103. g_in_fast_death_test_child = true;
  8104. return EXECUTE_TEST;
  8105. } else {
  8106. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  8107. set_read_fd(pipe_fd[0]);
  8108. set_spawned(true);
  8109. return OVERSEE_TEST;
  8110. }
  8111. }
  8112. // A concrete death test class that forks and re-executes the main
  8113. // program from the beginning, with command-line flags set that cause
  8114. // only this specific death test to be run.
  8115. class ExecDeathTest : public ForkingDeathTest {
  8116. public:
  8117. ExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
  8118. const char* file, int line)
  8119. : ForkingDeathTest(a_statement, std::move(matcher)),
  8120. file_(file),
  8121. line_(line) {}
  8122. TestRole AssumeRole() override;
  8123. private:
  8124. static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
  8125. ::std::vector<std::string> args = GetInjectableArgvs();
  8126. # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
  8127. ::std::vector<std::string> extra_args =
  8128. GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
  8129. args.insert(args.end(), extra_args.begin(), extra_args.end());
  8130. # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
  8131. return args;
  8132. }
  8133. // The name of the file in which the death test is located.
  8134. const char* const file_;
  8135. // The line number on which the death test is located.
  8136. const int line_;
  8137. };
  8138. // Utility class for accumulating command-line arguments.
  8139. class Arguments {
  8140. public:
  8141. Arguments() { args_.push_back(nullptr); }
  8142. ~Arguments() {
  8143. for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
  8144. ++i) {
  8145. free(*i);
  8146. }
  8147. }
  8148. void AddArgument(const char* argument) {
  8149. args_.insert(args_.end() - 1, posix::StrDup(argument));
  8150. }
  8151. template <typename Str>
  8152. void AddArguments(const ::std::vector<Str>& arguments) {
  8153. for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
  8154. i != arguments.end();
  8155. ++i) {
  8156. args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
  8157. }
  8158. }
  8159. char* const* Argv() {
  8160. return &args_[0];
  8161. }
  8162. private:
  8163. std::vector<char*> args_;
  8164. };
  8165. // A struct that encompasses the arguments to the child process of a
  8166. // threadsafe-style death test process.
  8167. struct ExecDeathTestArgs {
  8168. char* const* argv; // Command-line arguments for the child's call to exec
  8169. int close_fd; // File descriptor to close; the read end of a pipe
  8170. };
  8171. # if GTEST_OS_QNX
  8172. extern "C" char** environ;
  8173. # else // GTEST_OS_QNX
  8174. // The main function for a threadsafe-style death test child process.
  8175. // This function is called in a clone()-ed process and thus must avoid
  8176. // any potentially unsafe operations like malloc or libc functions.
  8177. static int ExecDeathTestChildMain(void* child_arg) {
  8178. ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
  8179. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
  8180. // We need to execute the test program in the same environment where
  8181. // it was originally invoked. Therefore we change to the original
  8182. // working directory first.
  8183. const char* const original_dir =
  8184. UnitTest::GetInstance()->original_working_dir();
  8185. // We can safely call chdir() as it's a direct system call.
  8186. if (chdir(original_dir) != 0) {
  8187. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  8188. GetLastErrnoDescription());
  8189. return EXIT_FAILURE;
  8190. }
  8191. // We can safely call execv() as it's almost a direct system call. We
  8192. // cannot use execvp() as it's a libc function and thus potentially
  8193. // unsafe. Since execv() doesn't search the PATH, the user must
  8194. // invoke the test program via a valid path that contains at least
  8195. // one path separator.
  8196. execv(args->argv[0], args->argv);
  8197. DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " +
  8198. original_dir + " failed: " +
  8199. GetLastErrnoDescription());
  8200. return EXIT_FAILURE;
  8201. }
  8202. # endif // GTEST_OS_QNX
  8203. # if GTEST_HAS_CLONE
  8204. // Two utility routines that together determine the direction the stack
  8205. // grows.
  8206. // This could be accomplished more elegantly by a single recursive
  8207. // function, but we want to guard against the unlikely possibility of
  8208. // a smart compiler optimizing the recursion away.
  8209. //
  8210. // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
  8211. // StackLowerThanAddress into StackGrowsDown, which then doesn't give
  8212. // correct answer.
  8213. static void StackLowerThanAddress(const void* ptr,
  8214. bool* result) GTEST_NO_INLINE_;
  8215. // Make sure sanitizers do not tamper with the stack here.
  8216. // Ideally, we want to use `__builtin_frame_address` instead of a local variable
  8217. // address with sanitizer disabled, but it does not work when the
  8218. // compiler optimizes the stack frame out, which happens on PowerPC targets.
  8219. // HWAddressSanitizer add a random tag to the MSB of the local variable address,
  8220. // making comparison result unpredictable.
  8221. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  8222. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  8223. static void StackLowerThanAddress(const void* ptr, bool* result) {
  8224. int dummy = 0;
  8225. *result = std::less<const void*>()(&dummy, ptr);
  8226. }
  8227. // Make sure AddressSanitizer does not tamper with the stack here.
  8228. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  8229. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  8230. static bool StackGrowsDown() {
  8231. int dummy = 0;
  8232. bool result;
  8233. StackLowerThanAddress(&dummy, &result);
  8234. return result;
  8235. }
  8236. # endif // GTEST_HAS_CLONE
  8237. // Spawns a child process with the same executable as the current process in
  8238. // a thread-safe manner and instructs it to run the death test. The
  8239. // implementation uses fork(2) + exec. On systems where clone(2) is
  8240. // available, it is used instead, being slightly more thread-safe. On QNX,
  8241. // fork supports only single-threaded environments, so this function uses
  8242. // spawn(2) there instead. The function dies with an error message if
  8243. // anything goes wrong.
  8244. static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
  8245. ExecDeathTestArgs args = { argv, close_fd };
  8246. pid_t child_pid = -1;
  8247. # if GTEST_OS_QNX
  8248. // Obtains the current directory and sets it to be closed in the child
  8249. // process.
  8250. const int cwd_fd = open(".", O_RDONLY);
  8251. GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
  8252. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
  8253. // We need to execute the test program in the same environment where
  8254. // it was originally invoked. Therefore we change to the original
  8255. // working directory first.
  8256. const char* const original_dir =
  8257. UnitTest::GetInstance()->original_working_dir();
  8258. // We can safely call chdir() as it's a direct system call.
  8259. if (chdir(original_dir) != 0) {
  8260. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  8261. GetLastErrnoDescription());
  8262. return EXIT_FAILURE;
  8263. }
  8264. int fd_flags;
  8265. // Set close_fd to be closed after spawn.
  8266. GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
  8267. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
  8268. fd_flags | FD_CLOEXEC));
  8269. struct inheritance inherit = {0};
  8270. // spawn is a system call.
  8271. child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ);
  8272. // Restores the current working directory.
  8273. GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
  8274. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
  8275. # else // GTEST_OS_QNX
  8276. # if GTEST_OS_LINUX
  8277. // When a SIGPROF signal is received while fork() or clone() are executing,
  8278. // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
  8279. // it after the call to fork()/clone() is complete.
  8280. struct sigaction saved_sigprof_action;
  8281. struct sigaction ignore_sigprof_action;
  8282. memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
  8283. sigemptyset(&ignore_sigprof_action.sa_mask);
  8284. ignore_sigprof_action.sa_handler = SIG_IGN;
  8285. GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
  8286. SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
  8287. # endif // GTEST_OS_LINUX
  8288. # if GTEST_HAS_CLONE
  8289. const bool use_fork = GTEST_FLAG(death_test_use_fork);
  8290. if (!use_fork) {
  8291. static const bool stack_grows_down = StackGrowsDown();
  8292. const auto stack_size = static_cast<size_t>(getpagesize() * 2);
  8293. // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
  8294. void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE,
  8295. MAP_ANON | MAP_PRIVATE, -1, 0);
  8296. GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
  8297. // Maximum stack alignment in bytes: For a downward-growing stack, this
  8298. // amount is subtracted from size of the stack space to get an address
  8299. // that is within the stack space and is aligned on all systems we care
  8300. // about. As far as I know there is no ABI with stack alignment greater
  8301. // than 64. We assume stack and stack_size already have alignment of
  8302. // kMaxStackAlignment.
  8303. const size_t kMaxStackAlignment = 64;
  8304. void* const stack_top =
  8305. static_cast<char*>(stack) +
  8306. (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
  8307. GTEST_DEATH_TEST_CHECK_(
  8308. static_cast<size_t>(stack_size) > kMaxStackAlignment &&
  8309. reinterpret_cast<uintptr_t>(stack_top) % kMaxStackAlignment == 0);
  8310. child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
  8311. GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
  8312. }
  8313. # else
  8314. const bool use_fork = true;
  8315. # endif // GTEST_HAS_CLONE
  8316. if (use_fork && (child_pid = fork()) == 0) {
  8317. ExecDeathTestChildMain(&args);
  8318. _exit(0);
  8319. }
  8320. # endif // GTEST_OS_QNX
  8321. # if GTEST_OS_LINUX
  8322. GTEST_DEATH_TEST_CHECK_SYSCALL_(
  8323. sigaction(SIGPROF, &saved_sigprof_action, nullptr));
  8324. # endif // GTEST_OS_LINUX
  8325. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  8326. return child_pid;
  8327. }
  8328. // The AssumeRole process for a fork-and-exec death test. It re-executes the
  8329. // main program from the beginning, setting the --gtest_filter
  8330. // and --gtest_internal_run_death_test flags to cause only the current
  8331. // death test to be re-run.
  8332. DeathTest::TestRole ExecDeathTest::AssumeRole() {
  8333. const UnitTestImpl* const impl = GetUnitTestImpl();
  8334. const InternalRunDeathTestFlag* const flag =
  8335. impl->internal_run_death_test_flag();
  8336. const TestInfo* const info = impl->current_test_info();
  8337. const int death_test_index = info->result()->death_test_count();
  8338. if (flag != nullptr) {
  8339. set_write_fd(flag->write_fd());
  8340. return EXECUTE_TEST;
  8341. }
  8342. int pipe_fd[2];
  8343. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  8344. // Clear the close-on-exec flag on the write end of the pipe, lest
  8345. // it be closed when the child process does an exec:
  8346. GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
  8347. const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
  8348. kFilterFlag + "=" + info->test_suite_name() +
  8349. "." + info->name();
  8350. const std::string internal_flag =
  8351. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
  8352. + file_ + "|" + StreamableToString(line_) + "|"
  8353. + StreamableToString(death_test_index) + "|"
  8354. + StreamableToString(pipe_fd[1]);
  8355. Arguments args;
  8356. args.AddArguments(GetArgvsForDeathTestChildProcess());
  8357. args.AddArgument(filter_flag.c_str());
  8358. args.AddArgument(internal_flag.c_str());
  8359. DeathTest::set_last_death_test_message("");
  8360. CaptureStderr();
  8361. // See the comment in NoExecDeathTest::AssumeRole for why the next line
  8362. // is necessary.
  8363. FlushInfoLog();
  8364. const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
  8365. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  8366. set_child_pid(child_pid);
  8367. set_read_fd(pipe_fd[0]);
  8368. set_spawned(true);
  8369. return OVERSEE_TEST;
  8370. }
  8371. # endif // !GTEST_OS_WINDOWS
  8372. // Creates a concrete DeathTest-derived class that depends on the
  8373. // --gtest_death_test_style flag, and sets the pointer pointed to
  8374. // by the "test" argument to its address. If the test should be
  8375. // skipped, sets that pointer to NULL. Returns true, unless the
  8376. // flag is set to an invalid value.
  8377. bool DefaultDeathTestFactory::Create(const char* statement,
  8378. Matcher<const std::string&> matcher,
  8379. const char* file, int line,
  8380. DeathTest** test) {
  8381. UnitTestImpl* const impl = GetUnitTestImpl();
  8382. const InternalRunDeathTestFlag* const flag =
  8383. impl->internal_run_death_test_flag();
  8384. const int death_test_index = impl->current_test_info()
  8385. ->increment_death_test_count();
  8386. if (flag != nullptr) {
  8387. if (death_test_index > flag->index()) {
  8388. DeathTest::set_last_death_test_message(
  8389. "Death test count (" + StreamableToString(death_test_index)
  8390. + ") somehow exceeded expected maximum ("
  8391. + StreamableToString(flag->index()) + ")");
  8392. return false;
  8393. }
  8394. if (!(flag->file() == file && flag->line() == line &&
  8395. flag->index() == death_test_index)) {
  8396. *test = nullptr;
  8397. return true;
  8398. }
  8399. }
  8400. # if GTEST_OS_WINDOWS
  8401. if (GTEST_FLAG(death_test_style) == "threadsafe" ||
  8402. GTEST_FLAG(death_test_style) == "fast") {
  8403. *test = new WindowsDeathTest(statement, std::move(matcher), file, line);
  8404. }
  8405. # elif GTEST_OS_FUCHSIA
  8406. if (GTEST_FLAG(death_test_style) == "threadsafe" ||
  8407. GTEST_FLAG(death_test_style) == "fast") {
  8408. *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);
  8409. }
  8410. # else
  8411. if (GTEST_FLAG(death_test_style) == "threadsafe") {
  8412. *test = new ExecDeathTest(statement, std::move(matcher), file, line);
  8413. } else if (GTEST_FLAG(death_test_style) == "fast") {
  8414. *test = new NoExecDeathTest(statement, std::move(matcher));
  8415. }
  8416. # endif // GTEST_OS_WINDOWS
  8417. else { // NOLINT - this is more readable than unbalanced brackets inside #if.
  8418. DeathTest::set_last_death_test_message(
  8419. "Unknown death test style \"" + GTEST_FLAG(death_test_style)
  8420. + "\" encountered");
  8421. return false;
  8422. }
  8423. return true;
  8424. }
  8425. # if GTEST_OS_WINDOWS
  8426. // Recreates the pipe and event handles from the provided parameters,
  8427. // signals the event, and returns a file descriptor wrapped around the pipe
  8428. // handle. This function is called in the child process only.
  8429. static int GetStatusFileDescriptor(unsigned int parent_process_id,
  8430. size_t write_handle_as_size_t,
  8431. size_t event_handle_as_size_t) {
  8432. AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
  8433. FALSE, // Non-inheritable.
  8434. parent_process_id));
  8435. if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
  8436. DeathTestAbort("Unable to open parent process " +
  8437. StreamableToString(parent_process_id));
  8438. }
  8439. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
  8440. const HANDLE write_handle =
  8441. reinterpret_cast<HANDLE>(write_handle_as_size_t);
  8442. HANDLE dup_write_handle;
  8443. // The newly initialized handle is accessible only in the parent
  8444. // process. To obtain one accessible within the child, we need to use
  8445. // DuplicateHandle.
  8446. if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
  8447. ::GetCurrentProcess(), &dup_write_handle,
  8448. 0x0, // Requested privileges ignored since
  8449. // DUPLICATE_SAME_ACCESS is used.
  8450. FALSE, // Request non-inheritable handler.
  8451. DUPLICATE_SAME_ACCESS)) {
  8452. DeathTestAbort("Unable to duplicate the pipe handle " +
  8453. StreamableToString(write_handle_as_size_t) +
  8454. " from the parent process " +
  8455. StreamableToString(parent_process_id));
  8456. }
  8457. const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
  8458. HANDLE dup_event_handle;
  8459. if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
  8460. ::GetCurrentProcess(), &dup_event_handle,
  8461. 0x0,
  8462. FALSE,
  8463. DUPLICATE_SAME_ACCESS)) {
  8464. DeathTestAbort("Unable to duplicate the event handle " +
  8465. StreamableToString(event_handle_as_size_t) +
  8466. " from the parent process " +
  8467. StreamableToString(parent_process_id));
  8468. }
  8469. const int write_fd =
  8470. ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
  8471. if (write_fd == -1) {
  8472. DeathTestAbort("Unable to convert pipe handle " +
  8473. StreamableToString(write_handle_as_size_t) +
  8474. " to a file descriptor");
  8475. }
  8476. // Signals the parent that the write end of the pipe has been acquired
  8477. // so the parent can release its own write end.
  8478. ::SetEvent(dup_event_handle);
  8479. return write_fd;
  8480. }
  8481. # endif // GTEST_OS_WINDOWS
  8482. // Returns a newly created InternalRunDeathTestFlag object with fields
  8483. // initialized from the GTEST_FLAG(internal_run_death_test) flag if
  8484. // the flag is specified; otherwise returns NULL.
  8485. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
  8486. if (GTEST_FLAG(internal_run_death_test) == "") return nullptr;
  8487. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
  8488. // can use it here.
  8489. int line = -1;
  8490. int index = -1;
  8491. ::std::vector< ::std::string> fields;
  8492. SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
  8493. int write_fd = -1;
  8494. # if GTEST_OS_WINDOWS
  8495. unsigned int parent_process_id = 0;
  8496. size_t write_handle_as_size_t = 0;
  8497. size_t event_handle_as_size_t = 0;
  8498. if (fields.size() != 6
  8499. || !ParseNaturalNumber(fields[1], &line)
  8500. || !ParseNaturalNumber(fields[2], &index)
  8501. || !ParseNaturalNumber(fields[3], &parent_process_id)
  8502. || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
  8503. || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
  8504. DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
  8505. GTEST_FLAG(internal_run_death_test));
  8506. }
  8507. write_fd = GetStatusFileDescriptor(parent_process_id,
  8508. write_handle_as_size_t,
  8509. event_handle_as_size_t);
  8510. # elif GTEST_OS_FUCHSIA
  8511. if (fields.size() != 3
  8512. || !ParseNaturalNumber(fields[1], &line)
  8513. || !ParseNaturalNumber(fields[2], &index)) {
  8514. DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
  8515. + GTEST_FLAG(internal_run_death_test));
  8516. }
  8517. # else
  8518. if (fields.size() != 4
  8519. || !ParseNaturalNumber(fields[1], &line)
  8520. || !ParseNaturalNumber(fields[2], &index)
  8521. || !ParseNaturalNumber(fields[3], &write_fd)) {
  8522. DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
  8523. + GTEST_FLAG(internal_run_death_test));
  8524. }
  8525. # endif // GTEST_OS_WINDOWS
  8526. return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
  8527. }
  8528. } // namespace internal
  8529. #endif // GTEST_HAS_DEATH_TEST
  8530. } // namespace testing
  8531. // Copyright 2008, Google Inc.
  8532. // All rights reserved.
  8533. //
  8534. // Redistribution and use in source and binary forms, with or without
  8535. // modification, are permitted provided that the following conditions are
  8536. // met:
  8537. //
  8538. // * Redistributions of source code must retain the above copyright
  8539. // notice, this list of conditions and the following disclaimer.
  8540. // * Redistributions in binary form must reproduce the above
  8541. // copyright notice, this list of conditions and the following disclaimer
  8542. // in the documentation and/or other materials provided with the
  8543. // distribution.
  8544. // * Neither the name of Google Inc. nor the names of its
  8545. // contributors may be used to endorse or promote products derived from
  8546. // this software without specific prior written permission.
  8547. //
  8548. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8549. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8550. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8551. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8552. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8553. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8554. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8555. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8556. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8557. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8558. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8559. #include <stdlib.h>
  8560. #if GTEST_OS_WINDOWS_MOBILE
  8561. # include <windows.h>
  8562. #elif GTEST_OS_WINDOWS
  8563. # include <direct.h>
  8564. # include <io.h>
  8565. #else
  8566. # include <limits.h>
  8567. # include <climits> // Some Linux distributions define PATH_MAX here.
  8568. #endif // GTEST_OS_WINDOWS_MOBILE
  8569. #if GTEST_OS_WINDOWS
  8570. # define GTEST_PATH_MAX_ _MAX_PATH
  8571. #elif defined(PATH_MAX)
  8572. # define GTEST_PATH_MAX_ PATH_MAX
  8573. #elif defined(_XOPEN_PATH_MAX)
  8574. # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
  8575. #else
  8576. # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
  8577. #endif // GTEST_OS_WINDOWS
  8578. namespace testing {
  8579. namespace internal {
  8580. #if GTEST_OS_WINDOWS
  8581. // On Windows, '\\' is the standard path separator, but many tools and the
  8582. // Windows API also accept '/' as an alternate path separator. Unless otherwise
  8583. // noted, a file path can contain either kind of path separators, or a mixture
  8584. // of them.
  8585. const char kPathSeparator = '\\';
  8586. const char kAlternatePathSeparator = '/';
  8587. const char kAlternatePathSeparatorString[] = "/";
  8588. # if GTEST_OS_WINDOWS_MOBILE
  8589. // Windows CE doesn't have a current directory. You should not use
  8590. // the current directory in tests on Windows CE, but this at least
  8591. // provides a reasonable fallback.
  8592. const char kCurrentDirectoryString[] = "\\";
  8593. // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
  8594. const DWORD kInvalidFileAttributes = 0xffffffff;
  8595. # else
  8596. const char kCurrentDirectoryString[] = ".\\";
  8597. # endif // GTEST_OS_WINDOWS_MOBILE
  8598. #else
  8599. const char kPathSeparator = '/';
  8600. const char kCurrentDirectoryString[] = "./";
  8601. #endif // GTEST_OS_WINDOWS
  8602. // Returns whether the given character is a valid path separator.
  8603. static bool IsPathSeparator(char c) {
  8604. #if GTEST_HAS_ALT_PATH_SEP_
  8605. return (c == kPathSeparator) || (c == kAlternatePathSeparator);
  8606. #else
  8607. return c == kPathSeparator;
  8608. #endif
  8609. }
  8610. // Returns the current working directory, or "" if unsuccessful.
  8611. FilePath FilePath::GetCurrentDir() {
  8612. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
  8613. GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \
  8614. GTEST_OS_XTENSA
  8615. // These platforms do not have a current directory, so we just return
  8616. // something reasonable.
  8617. return FilePath(kCurrentDirectoryString);
  8618. #elif GTEST_OS_WINDOWS
  8619. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  8620. return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
  8621. #else
  8622. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  8623. char* result = getcwd(cwd, sizeof(cwd));
  8624. # if GTEST_OS_NACL
  8625. // getcwd will likely fail in NaCl due to the sandbox, so return something
  8626. // reasonable. The user may have provided a shim implementation for getcwd,
  8627. // however, so fallback only when failure is detected.
  8628. return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
  8629. # endif // GTEST_OS_NACL
  8630. return FilePath(result == nullptr ? "" : cwd);
  8631. #endif // GTEST_OS_WINDOWS_MOBILE
  8632. }
  8633. // Returns a copy of the FilePath with the case-insensitive extension removed.
  8634. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
  8635. // FilePath("dir/file"). If a case-insensitive extension is not
  8636. // found, returns a copy of the original FilePath.
  8637. FilePath FilePath::RemoveExtension(const char* extension) const {
  8638. const std::string dot_extension = std::string(".") + extension;
  8639. if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
  8640. return FilePath(pathname_.substr(
  8641. 0, pathname_.length() - dot_extension.length()));
  8642. }
  8643. return *this;
  8644. }
  8645. // Returns a pointer to the last occurrence of a valid path separator in
  8646. // the FilePath. On Windows, for example, both '/' and '\' are valid path
  8647. // separators. Returns NULL if no path separator was found.
  8648. const char* FilePath::FindLastPathSeparator() const {
  8649. const char* const last_sep = strrchr(c_str(), kPathSeparator);
  8650. #if GTEST_HAS_ALT_PATH_SEP_
  8651. const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
  8652. // Comparing two pointers of which only one is NULL is undefined.
  8653. if (last_alt_sep != nullptr &&
  8654. (last_sep == nullptr || last_alt_sep > last_sep)) {
  8655. return last_alt_sep;
  8656. }
  8657. #endif
  8658. return last_sep;
  8659. }
  8660. // Returns a copy of the FilePath with the directory part removed.
  8661. // Example: FilePath("path/to/file").RemoveDirectoryName() returns
  8662. // FilePath("file"). If there is no directory part ("just_a_file"), it returns
  8663. // the FilePath unmodified. If there is no file part ("just_a_dir/") it
  8664. // returns an empty FilePath ("").
  8665. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  8666. FilePath FilePath::RemoveDirectoryName() const {
  8667. const char* const last_sep = FindLastPathSeparator();
  8668. return last_sep ? FilePath(last_sep + 1) : *this;
  8669. }
  8670. // RemoveFileName returns the directory path with the filename removed.
  8671. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
  8672. // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
  8673. // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
  8674. // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
  8675. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  8676. FilePath FilePath::RemoveFileName() const {
  8677. const char* const last_sep = FindLastPathSeparator();
  8678. std::string dir;
  8679. if (last_sep) {
  8680. dir = std::string(c_str(), static_cast<size_t>(last_sep + 1 - c_str()));
  8681. } else {
  8682. dir = kCurrentDirectoryString;
  8683. }
  8684. return FilePath(dir);
  8685. }
  8686. // Helper functions for naming files in a directory for xml output.
  8687. // Given directory = "dir", base_name = "test", number = 0,
  8688. // extension = "xml", returns "dir/test.xml". If number is greater
  8689. // than zero (e.g., 12), returns "dir/test_12.xml".
  8690. // On Windows platform, uses \ as the separator rather than /.
  8691. FilePath FilePath::MakeFileName(const FilePath& directory,
  8692. const FilePath& base_name,
  8693. int number,
  8694. const char* extension) {
  8695. std::string file;
  8696. if (number == 0) {
  8697. file = base_name.string() + "." + extension;
  8698. } else {
  8699. file = base_name.string() + "_" + StreamableToString(number)
  8700. + "." + extension;
  8701. }
  8702. return ConcatPaths(directory, FilePath(file));
  8703. }
  8704. // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
  8705. // On Windows, uses \ as the separator rather than /.
  8706. FilePath FilePath::ConcatPaths(const FilePath& directory,
  8707. const FilePath& relative_path) {
  8708. if (directory.IsEmpty())
  8709. return relative_path;
  8710. const FilePath dir(directory.RemoveTrailingPathSeparator());
  8711. return FilePath(dir.string() + kPathSeparator + relative_path.string());
  8712. }
  8713. // Returns true if pathname describes something findable in the file-system,
  8714. // either a file, directory, or whatever.
  8715. bool FilePath::FileOrDirectoryExists() const {
  8716. #if GTEST_OS_WINDOWS_MOBILE
  8717. LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
  8718. const DWORD attributes = GetFileAttributes(unicode);
  8719. delete [] unicode;
  8720. return attributes != kInvalidFileAttributes;
  8721. #else
  8722. posix::StatStruct file_stat;
  8723. return posix::Stat(pathname_.c_str(), &file_stat) == 0;
  8724. #endif // GTEST_OS_WINDOWS_MOBILE
  8725. }
  8726. // Returns true if pathname describes a directory in the file-system
  8727. // that exists.
  8728. bool FilePath::DirectoryExists() const {
  8729. bool result = false;
  8730. #if GTEST_OS_WINDOWS
  8731. // Don't strip off trailing separator if path is a root directory on
  8732. // Windows (like "C:\\").
  8733. const FilePath& path(IsRootDirectory() ? *this :
  8734. RemoveTrailingPathSeparator());
  8735. #else
  8736. const FilePath& path(*this);
  8737. #endif
  8738. #if GTEST_OS_WINDOWS_MOBILE
  8739. LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
  8740. const DWORD attributes = GetFileAttributes(unicode);
  8741. delete [] unicode;
  8742. if ((attributes != kInvalidFileAttributes) &&
  8743. (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  8744. result = true;
  8745. }
  8746. #else
  8747. posix::StatStruct file_stat;
  8748. result = posix::Stat(path.c_str(), &file_stat) == 0 &&
  8749. posix::IsDir(file_stat);
  8750. #endif // GTEST_OS_WINDOWS_MOBILE
  8751. return result;
  8752. }
  8753. // Returns true if pathname describes a root directory. (Windows has one
  8754. // root directory per disk drive.)
  8755. bool FilePath::IsRootDirectory() const {
  8756. #if GTEST_OS_WINDOWS
  8757. return pathname_.length() == 3 && IsAbsolutePath();
  8758. #else
  8759. return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
  8760. #endif
  8761. }
  8762. // Returns true if pathname describes an absolute path.
  8763. bool FilePath::IsAbsolutePath() const {
  8764. const char* const name = pathname_.c_str();
  8765. #if GTEST_OS_WINDOWS
  8766. return pathname_.length() >= 3 &&
  8767. ((name[0] >= 'a' && name[0] <= 'z') ||
  8768. (name[0] >= 'A' && name[0] <= 'Z')) &&
  8769. name[1] == ':' &&
  8770. IsPathSeparator(name[2]);
  8771. #else
  8772. return IsPathSeparator(name[0]);
  8773. #endif
  8774. }
  8775. // Returns a pathname for a file that does not currently exist. The pathname
  8776. // will be directory/base_name.extension or
  8777. // directory/base_name_<number>.extension if directory/base_name.extension
  8778. // already exists. The number will be incremented until a pathname is found
  8779. // that does not already exist.
  8780. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
  8781. // There could be a race condition if two or more processes are calling this
  8782. // function at the same time -- they could both pick the same filename.
  8783. FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
  8784. const FilePath& base_name,
  8785. const char* extension) {
  8786. FilePath full_pathname;
  8787. int number = 0;
  8788. do {
  8789. full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
  8790. } while (full_pathname.FileOrDirectoryExists());
  8791. return full_pathname;
  8792. }
  8793. // Returns true if FilePath ends with a path separator, which indicates that
  8794. // it is intended to represent a directory. Returns false otherwise.
  8795. // This does NOT check that a directory (or file) actually exists.
  8796. bool FilePath::IsDirectory() const {
  8797. return !pathname_.empty() &&
  8798. IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
  8799. }
  8800. // Create directories so that path exists. Returns true if successful or if
  8801. // the directories already exist; returns false if unable to create directories
  8802. // for any reason.
  8803. bool FilePath::CreateDirectoriesRecursively() const {
  8804. if (!this->IsDirectory()) {
  8805. return false;
  8806. }
  8807. if (pathname_.length() == 0 || this->DirectoryExists()) {
  8808. return true;
  8809. }
  8810. const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
  8811. return parent.CreateDirectoriesRecursively() && this->CreateFolder();
  8812. }
  8813. // Create the directory so that path exists. Returns true if successful or
  8814. // if the directory already exists; returns false if unable to create the
  8815. // directory for any reason, including if the parent directory does not
  8816. // exist. Not named "CreateDirectory" because that's a macro on Windows.
  8817. bool FilePath::CreateFolder() const {
  8818. #if GTEST_OS_WINDOWS_MOBILE
  8819. FilePath removed_sep(this->RemoveTrailingPathSeparator());
  8820. LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
  8821. int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
  8822. delete [] unicode;
  8823. #elif GTEST_OS_WINDOWS
  8824. int result = _mkdir(pathname_.c_str());
  8825. #elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA
  8826. // do nothing
  8827. int result = 0;
  8828. #else
  8829. int result = mkdir(pathname_.c_str(), 0777);
  8830. #endif // GTEST_OS_WINDOWS_MOBILE
  8831. if (result == -1) {
  8832. return this->DirectoryExists(); // An error is OK if the directory exists.
  8833. }
  8834. return true; // No error.
  8835. }
  8836. // If input name has a trailing separator character, remove it and return the
  8837. // name, otherwise return the name string unmodified.
  8838. // On Windows platform, uses \ as the separator, other platforms use /.
  8839. FilePath FilePath::RemoveTrailingPathSeparator() const {
  8840. return IsDirectory()
  8841. ? FilePath(pathname_.substr(0, pathname_.length() - 1))
  8842. : *this;
  8843. }
  8844. // Removes any redundant separators that might be in the pathname.
  8845. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
  8846. // redundancies that might be in a pathname involving "." or "..".
  8847. void FilePath::Normalize() {
  8848. auto out = pathname_.begin();
  8849. for (const char character : pathname_) {
  8850. if (!IsPathSeparator(character)) {
  8851. *(out++) = character;
  8852. } else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {
  8853. *(out++) = kPathSeparator;
  8854. } else {
  8855. continue;
  8856. }
  8857. }
  8858. pathname_.erase(out, pathname_.end());
  8859. }
  8860. } // namespace internal
  8861. } // namespace testing
  8862. // Copyright 2007, Google Inc.
  8863. // All rights reserved.
  8864. //
  8865. // Redistribution and use in source and binary forms, with or without
  8866. // modification, are permitted provided that the following conditions are
  8867. // met:
  8868. //
  8869. // * Redistributions of source code must retain the above copyright
  8870. // notice, this list of conditions and the following disclaimer.
  8871. // * Redistributions in binary form must reproduce the above
  8872. // copyright notice, this list of conditions and the following disclaimer
  8873. // in the documentation and/or other materials provided with the
  8874. // distribution.
  8875. // * Neither the name of Google Inc. nor the names of its
  8876. // contributors may be used to endorse or promote products derived from
  8877. // this software without specific prior written permission.
  8878. //
  8879. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8880. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8881. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8882. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8883. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8884. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8885. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8886. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8887. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8888. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8889. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8890. // The Google C++ Testing and Mocking Framework (Google Test)
  8891. //
  8892. // This file implements just enough of the matcher interface to allow
  8893. // EXPECT_DEATH and friends to accept a matcher argument.
  8894. #include <string>
  8895. namespace testing {
  8896. // Constructs a matcher that matches a const std::string& whose value is
  8897. // equal to s.
  8898. Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); }
  8899. // Constructs a matcher that matches a const std::string& whose value is
  8900. // equal to s.
  8901. Matcher<const std::string&>::Matcher(const char* s) {
  8902. *this = Eq(std::string(s));
  8903. }
  8904. // Constructs a matcher that matches a std::string whose value is equal to
  8905. // s.
  8906. Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }
  8907. // Constructs a matcher that matches a std::string whose value is equal to
  8908. // s.
  8909. Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }
  8910. #if GTEST_INTERNAL_HAS_STRING_VIEW
  8911. // Constructs a matcher that matches a const StringView& whose value is
  8912. // equal to s.
  8913. Matcher<const internal::StringView&>::Matcher(const std::string& s) {
  8914. *this = Eq(s);
  8915. }
  8916. // Constructs a matcher that matches a const StringView& whose value is
  8917. // equal to s.
  8918. Matcher<const internal::StringView&>::Matcher(const char* s) {
  8919. *this = Eq(std::string(s));
  8920. }
  8921. // Constructs a matcher that matches a const StringView& whose value is
  8922. // equal to s.
  8923. Matcher<const internal::StringView&>::Matcher(internal::StringView s) {
  8924. *this = Eq(std::string(s));
  8925. }
  8926. // Constructs a matcher that matches a StringView whose value is equal to
  8927. // s.
  8928. Matcher<internal::StringView>::Matcher(const std::string& s) { *this = Eq(s); }
  8929. // Constructs a matcher that matches a StringView whose value is equal to
  8930. // s.
  8931. Matcher<internal::StringView>::Matcher(const char* s) {
  8932. *this = Eq(std::string(s));
  8933. }
  8934. // Constructs a matcher that matches a StringView whose value is equal to
  8935. // s.
  8936. Matcher<internal::StringView>::Matcher(internal::StringView s) {
  8937. *this = Eq(std::string(s));
  8938. }
  8939. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  8940. } // namespace testing
  8941. // Copyright 2008, Google Inc.
  8942. // All rights reserved.
  8943. //
  8944. // Redistribution and use in source and binary forms, with or without
  8945. // modification, are permitted provided that the following conditions are
  8946. // met:
  8947. //
  8948. // * Redistributions of source code must retain the above copyright
  8949. // notice, this list of conditions and the following disclaimer.
  8950. // * Redistributions in binary form must reproduce the above
  8951. // copyright notice, this list of conditions and the following disclaimer
  8952. // in the documentation and/or other materials provided with the
  8953. // distribution.
  8954. // * Neither the name of Google Inc. nor the names of its
  8955. // contributors may be used to endorse or promote products derived from
  8956. // this software without specific prior written permission.
  8957. //
  8958. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8959. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8960. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8961. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8962. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8963. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8964. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8965. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8966. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8967. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8968. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8969. #include <limits.h>
  8970. #include <stdio.h>
  8971. #include <stdlib.h>
  8972. #include <string.h>
  8973. #include <cstdint>
  8974. #include <fstream>
  8975. #include <memory>
  8976. #if GTEST_OS_WINDOWS
  8977. # include <windows.h>
  8978. # include <io.h>
  8979. # include <sys/stat.h>
  8980. # include <map> // Used in ThreadLocal.
  8981. # ifdef _MSC_VER
  8982. # include <crtdbg.h>
  8983. # endif // _MSC_VER
  8984. #else
  8985. # include <unistd.h>
  8986. #endif // GTEST_OS_WINDOWS
  8987. #if GTEST_OS_MAC
  8988. # include <mach/mach_init.h>
  8989. # include <mach/task.h>
  8990. # include <mach/vm_map.h>
  8991. #endif // GTEST_OS_MAC
  8992. #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
  8993. GTEST_OS_NETBSD || GTEST_OS_OPENBSD
  8994. # include <sys/sysctl.h>
  8995. # if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
  8996. # include <sys/user.h>
  8997. # endif
  8998. #endif
  8999. #if GTEST_OS_QNX
  9000. # include <devctl.h>
  9001. # include <fcntl.h>
  9002. # include <sys/procfs.h>
  9003. #endif // GTEST_OS_QNX
  9004. #if GTEST_OS_AIX
  9005. # include <procinfo.h>
  9006. # include <sys/types.h>
  9007. #endif // GTEST_OS_AIX
  9008. #if GTEST_OS_FUCHSIA
  9009. # include <zircon/process.h>
  9010. # include <zircon/syscalls.h>
  9011. #endif // GTEST_OS_FUCHSIA
  9012. namespace testing {
  9013. namespace internal {
  9014. #if defined(_MSC_VER) || defined(__BORLANDC__)
  9015. // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
  9016. const int kStdOutFileno = 1;
  9017. const int kStdErrFileno = 2;
  9018. #else
  9019. const int kStdOutFileno = STDOUT_FILENO;
  9020. const int kStdErrFileno = STDERR_FILENO;
  9021. #endif // _MSC_VER
  9022. #if GTEST_OS_LINUX
  9023. namespace {
  9024. template <typename T>
  9025. T ReadProcFileField(const std::string& filename, int field) {
  9026. std::string dummy;
  9027. std::ifstream file(filename.c_str());
  9028. while (field-- > 0) {
  9029. file >> dummy;
  9030. }
  9031. T output = 0;
  9032. file >> output;
  9033. return output;
  9034. }
  9035. } // namespace
  9036. // Returns the number of active threads, or 0 when there is an error.
  9037. size_t GetThreadCount() {
  9038. const std::string filename =
  9039. (Message() << "/proc/" << getpid() << "/stat").GetString();
  9040. return ReadProcFileField<size_t>(filename, 19);
  9041. }
  9042. #elif GTEST_OS_MAC
  9043. size_t GetThreadCount() {
  9044. const task_t task = mach_task_self();
  9045. mach_msg_type_number_t thread_count;
  9046. thread_act_array_t thread_list;
  9047. const kern_return_t status = task_threads(task, &thread_list, &thread_count);
  9048. if (status == KERN_SUCCESS) {
  9049. // task_threads allocates resources in thread_list and we need to free them
  9050. // to avoid leaks.
  9051. vm_deallocate(task,
  9052. reinterpret_cast<vm_address_t>(thread_list),
  9053. sizeof(thread_t) * thread_count);
  9054. return static_cast<size_t>(thread_count);
  9055. } else {
  9056. return 0;
  9057. }
  9058. }
  9059. #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
  9060. GTEST_OS_NETBSD
  9061. #if GTEST_OS_NETBSD
  9062. #undef KERN_PROC
  9063. #define KERN_PROC KERN_PROC2
  9064. #define kinfo_proc kinfo_proc2
  9065. #endif
  9066. #if GTEST_OS_DRAGONFLY
  9067. #define KP_NLWP(kp) (kp.kp_nthreads)
  9068. #elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
  9069. #define KP_NLWP(kp) (kp.ki_numthreads)
  9070. #elif GTEST_OS_NETBSD
  9071. #define KP_NLWP(kp) (kp.p_nlwps)
  9072. #endif
  9073. // Returns the number of threads running in the process, or 0 to indicate that
  9074. // we cannot detect it.
  9075. size_t GetThreadCount() {
  9076. int mib[] = {
  9077. CTL_KERN,
  9078. KERN_PROC,
  9079. KERN_PROC_PID,
  9080. getpid(),
  9081. #if GTEST_OS_NETBSD
  9082. sizeof(struct kinfo_proc),
  9083. 1,
  9084. #endif
  9085. };
  9086. u_int miblen = sizeof(mib) / sizeof(mib[0]);
  9087. struct kinfo_proc info;
  9088. size_t size = sizeof(info);
  9089. if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
  9090. return 0;
  9091. }
  9092. return static_cast<size_t>(KP_NLWP(info));
  9093. }
  9094. #elif GTEST_OS_OPENBSD
  9095. // Returns the number of threads running in the process, or 0 to indicate that
  9096. // we cannot detect it.
  9097. size_t GetThreadCount() {
  9098. int mib[] = {
  9099. CTL_KERN,
  9100. KERN_PROC,
  9101. KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
  9102. getpid(),
  9103. sizeof(struct kinfo_proc),
  9104. 0,
  9105. };
  9106. u_int miblen = sizeof(mib) / sizeof(mib[0]);
  9107. // get number of structs
  9108. size_t size;
  9109. if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
  9110. return 0;
  9111. }
  9112. mib[5] = static_cast<int>(size / static_cast<size_t>(mib[4]));
  9113. // populate array of structs
  9114. struct kinfo_proc info[mib[5]];
  9115. if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
  9116. return 0;
  9117. }
  9118. // exclude empty members
  9119. size_t nthreads = 0;
  9120. for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) {
  9121. if (info[i].p_tid != -1)
  9122. nthreads++;
  9123. }
  9124. return nthreads;
  9125. }
  9126. #elif GTEST_OS_QNX
  9127. // Returns the number of threads running in the process, or 0 to indicate that
  9128. // we cannot detect it.
  9129. size_t GetThreadCount() {
  9130. const int fd = open("/proc/self/as", O_RDONLY);
  9131. if (fd < 0) {
  9132. return 0;
  9133. }
  9134. procfs_info process_info;
  9135. const int status =
  9136. devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);
  9137. close(fd);
  9138. if (status == EOK) {
  9139. return static_cast<size_t>(process_info.num_threads);
  9140. } else {
  9141. return 0;
  9142. }
  9143. }
  9144. #elif GTEST_OS_AIX
  9145. size_t GetThreadCount() {
  9146. struct procentry64 entry;
  9147. pid_t pid = getpid();
  9148. int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);
  9149. if (status == 1) {
  9150. return entry.pi_thcount;
  9151. } else {
  9152. return 0;
  9153. }
  9154. }
  9155. #elif GTEST_OS_FUCHSIA
  9156. size_t GetThreadCount() {
  9157. int dummy_buffer;
  9158. size_t avail;
  9159. zx_status_t status = zx_object_get_info(
  9160. zx_process_self(),
  9161. ZX_INFO_PROCESS_THREADS,
  9162. &dummy_buffer,
  9163. 0,
  9164. nullptr,
  9165. &avail);
  9166. if (status == ZX_OK) {
  9167. return avail;
  9168. } else {
  9169. return 0;
  9170. }
  9171. }
  9172. #else
  9173. size_t GetThreadCount() {
  9174. // There's no portable way to detect the number of threads, so we just
  9175. // return 0 to indicate that we cannot detect it.
  9176. return 0;
  9177. }
  9178. #endif // GTEST_OS_LINUX
  9179. #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
  9180. void SleepMilliseconds(int n) {
  9181. ::Sleep(static_cast<DWORD>(n));
  9182. }
  9183. AutoHandle::AutoHandle()
  9184. : handle_(INVALID_HANDLE_VALUE) {}
  9185. AutoHandle::AutoHandle(Handle handle)
  9186. : handle_(handle) {}
  9187. AutoHandle::~AutoHandle() {
  9188. Reset();
  9189. }
  9190. AutoHandle::Handle AutoHandle::Get() const {
  9191. return handle_;
  9192. }
  9193. void AutoHandle::Reset() {
  9194. Reset(INVALID_HANDLE_VALUE);
  9195. }
  9196. void AutoHandle::Reset(HANDLE handle) {
  9197. // Resetting with the same handle we already own is invalid.
  9198. if (handle_ != handle) {
  9199. if (IsCloseable()) {
  9200. ::CloseHandle(handle_);
  9201. }
  9202. handle_ = handle;
  9203. } else {
  9204. GTEST_CHECK_(!IsCloseable())
  9205. << "Resetting a valid handle to itself is likely a programmer error "
  9206. "and thus not allowed.";
  9207. }
  9208. }
  9209. bool AutoHandle::IsCloseable() const {
  9210. // Different Windows APIs may use either of these values to represent an
  9211. // invalid handle.
  9212. return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
  9213. }
  9214. Notification::Notification()
  9215. : event_(::CreateEvent(nullptr, // Default security attributes.
  9216. TRUE, // Do not reset automatically.
  9217. FALSE, // Initially unset.
  9218. nullptr)) { // Anonymous event.
  9219. GTEST_CHECK_(event_.Get() != nullptr);
  9220. }
  9221. void Notification::Notify() {
  9222. GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
  9223. }
  9224. void Notification::WaitForNotification() {
  9225. GTEST_CHECK_(
  9226. ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
  9227. }
  9228. Mutex::Mutex()
  9229. : owner_thread_id_(0),
  9230. type_(kDynamic),
  9231. critical_section_init_phase_(0),
  9232. critical_section_(new CRITICAL_SECTION) {
  9233. ::InitializeCriticalSection(critical_section_);
  9234. }
  9235. Mutex::~Mutex() {
  9236. // Static mutexes are leaked intentionally. It is not thread-safe to try
  9237. // to clean them up.
  9238. if (type_ == kDynamic) {
  9239. ::DeleteCriticalSection(critical_section_);
  9240. delete critical_section_;
  9241. critical_section_ = nullptr;
  9242. }
  9243. }
  9244. void Mutex::Lock() {
  9245. ThreadSafeLazyInit();
  9246. ::EnterCriticalSection(critical_section_);
  9247. owner_thread_id_ = ::GetCurrentThreadId();
  9248. }
  9249. void Mutex::Unlock() {
  9250. ThreadSafeLazyInit();
  9251. // We don't protect writing to owner_thread_id_ here, as it's the
  9252. // caller's responsibility to ensure that the current thread holds the
  9253. // mutex when this is called.
  9254. owner_thread_id_ = 0;
  9255. ::LeaveCriticalSection(critical_section_);
  9256. }
  9257. // Does nothing if the current thread holds the mutex. Otherwise, crashes
  9258. // with high probability.
  9259. void Mutex::AssertHeld() {
  9260. ThreadSafeLazyInit();
  9261. GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
  9262. << "The current thread is not holding the mutex @" << this;
  9263. }
  9264. namespace {
  9265. #ifdef _MSC_VER
  9266. // Use the RAII idiom to flag mem allocs that are intentionally never
  9267. // deallocated. The motivation is to silence the false positive mem leaks
  9268. // that are reported by the debug version of MS's CRT which can only detect
  9269. // if an alloc is missing a matching deallocation.
  9270. // Example:
  9271. // MemoryIsNotDeallocated memory_is_not_deallocated;
  9272. // critical_section_ = new CRITICAL_SECTION;
  9273. //
  9274. class MemoryIsNotDeallocated
  9275. {
  9276. public:
  9277. MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
  9278. old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  9279. // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
  9280. // doesn't report mem leak if there's no matching deallocation.
  9281. _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
  9282. }
  9283. ~MemoryIsNotDeallocated() {
  9284. // Restore the original _CRTDBG_ALLOC_MEM_DF flag
  9285. _CrtSetDbgFlag(old_crtdbg_flag_);
  9286. }
  9287. private:
  9288. int old_crtdbg_flag_;
  9289. GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
  9290. };
  9291. #endif // _MSC_VER
  9292. } // namespace
  9293. // Initializes owner_thread_id_ and critical_section_ in static mutexes.
  9294. void Mutex::ThreadSafeLazyInit() {
  9295. // Dynamic mutexes are initialized in the constructor.
  9296. if (type_ == kStatic) {
  9297. switch (
  9298. ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
  9299. case 0:
  9300. // If critical_section_init_phase_ was 0 before the exchange, we
  9301. // are the first to test it and need to perform the initialization.
  9302. owner_thread_id_ = 0;
  9303. {
  9304. // Use RAII to flag that following mem alloc is never deallocated.
  9305. #ifdef _MSC_VER
  9306. MemoryIsNotDeallocated memory_is_not_deallocated;
  9307. #endif // _MSC_VER
  9308. critical_section_ = new CRITICAL_SECTION;
  9309. }
  9310. ::InitializeCriticalSection(critical_section_);
  9311. // Updates the critical_section_init_phase_ to 2 to signal
  9312. // initialization complete.
  9313. GTEST_CHECK_(::InterlockedCompareExchange(
  9314. &critical_section_init_phase_, 2L, 1L) ==
  9315. 1L);
  9316. break;
  9317. case 1:
  9318. // Somebody else is already initializing the mutex; spin until they
  9319. // are done.
  9320. while (::InterlockedCompareExchange(&critical_section_init_phase_,
  9321. 2L,
  9322. 2L) != 2L) {
  9323. // Possibly yields the rest of the thread's time slice to other
  9324. // threads.
  9325. ::Sleep(0);
  9326. }
  9327. break;
  9328. case 2:
  9329. break; // The mutex is already initialized and ready for use.
  9330. default:
  9331. GTEST_CHECK_(false)
  9332. << "Unexpected value of critical_section_init_phase_ "
  9333. << "while initializing a static mutex.";
  9334. }
  9335. }
  9336. }
  9337. namespace {
  9338. class ThreadWithParamSupport : public ThreadWithParamBase {
  9339. public:
  9340. static HANDLE CreateThread(Runnable* runnable,
  9341. Notification* thread_can_start) {
  9342. ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
  9343. DWORD thread_id;
  9344. HANDLE thread_handle = ::CreateThread(
  9345. nullptr, // Default security.
  9346. 0, // Default stack size.
  9347. &ThreadWithParamSupport::ThreadMain,
  9348. param, // Parameter to ThreadMainStatic
  9349. 0x0, // Default creation flags.
  9350. &thread_id); // Need a valid pointer for the call to work under Win98.
  9351. GTEST_CHECK_(thread_handle != nullptr)
  9352. << "CreateThread failed with error " << ::GetLastError() << ".";
  9353. if (thread_handle == nullptr) {
  9354. delete param;
  9355. }
  9356. return thread_handle;
  9357. }
  9358. private:
  9359. struct ThreadMainParam {
  9360. ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
  9361. : runnable_(runnable),
  9362. thread_can_start_(thread_can_start) {
  9363. }
  9364. std::unique_ptr<Runnable> runnable_;
  9365. // Does not own.
  9366. Notification* thread_can_start_;
  9367. };
  9368. static DWORD WINAPI ThreadMain(void* ptr) {
  9369. // Transfers ownership.
  9370. std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
  9371. if (param->thread_can_start_ != nullptr)
  9372. param->thread_can_start_->WaitForNotification();
  9373. param->runnable_->Run();
  9374. return 0;
  9375. }
  9376. // Prohibit instantiation.
  9377. ThreadWithParamSupport();
  9378. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
  9379. };
  9380. } // namespace
  9381. ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
  9382. Notification* thread_can_start)
  9383. : thread_(ThreadWithParamSupport::CreateThread(runnable,
  9384. thread_can_start)) {
  9385. }
  9386. ThreadWithParamBase::~ThreadWithParamBase() {
  9387. Join();
  9388. }
  9389. void ThreadWithParamBase::Join() {
  9390. GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
  9391. << "Failed to join the thread with error " << ::GetLastError() << ".";
  9392. }
  9393. // Maps a thread to a set of ThreadIdToThreadLocals that have values
  9394. // instantiated on that thread and notifies them when the thread exits. A
  9395. // ThreadLocal instance is expected to persist until all threads it has
  9396. // values on have terminated.
  9397. class ThreadLocalRegistryImpl {
  9398. public:
  9399. // Registers thread_local_instance as having value on the current thread.
  9400. // Returns a value that can be used to identify the thread from other threads.
  9401. static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
  9402. const ThreadLocalBase* thread_local_instance) {
  9403. #ifdef _MSC_VER
  9404. MemoryIsNotDeallocated memory_is_not_deallocated;
  9405. #endif // _MSC_VER
  9406. DWORD current_thread = ::GetCurrentThreadId();
  9407. MutexLock lock(&mutex_);
  9408. ThreadIdToThreadLocals* const thread_to_thread_locals =
  9409. GetThreadLocalsMapLocked();
  9410. ThreadIdToThreadLocals::iterator thread_local_pos =
  9411. thread_to_thread_locals->find(current_thread);
  9412. if (thread_local_pos == thread_to_thread_locals->end()) {
  9413. thread_local_pos = thread_to_thread_locals->insert(
  9414. std::make_pair(current_thread, ThreadLocalValues())).first;
  9415. StartWatcherThreadFor(current_thread);
  9416. }
  9417. ThreadLocalValues& thread_local_values = thread_local_pos->second;
  9418. ThreadLocalValues::iterator value_pos =
  9419. thread_local_values.find(thread_local_instance);
  9420. if (value_pos == thread_local_values.end()) {
  9421. value_pos =
  9422. thread_local_values
  9423. .insert(std::make_pair(
  9424. thread_local_instance,
  9425. std::shared_ptr<ThreadLocalValueHolderBase>(
  9426. thread_local_instance->NewValueForCurrentThread())))
  9427. .first;
  9428. }
  9429. return value_pos->second.get();
  9430. }
  9431. static void OnThreadLocalDestroyed(
  9432. const ThreadLocalBase* thread_local_instance) {
  9433. std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
  9434. // Clean up the ThreadLocalValues data structure while holding the lock, but
  9435. // defer the destruction of the ThreadLocalValueHolderBases.
  9436. {
  9437. MutexLock lock(&mutex_);
  9438. ThreadIdToThreadLocals* const thread_to_thread_locals =
  9439. GetThreadLocalsMapLocked();
  9440. for (ThreadIdToThreadLocals::iterator it =
  9441. thread_to_thread_locals->begin();
  9442. it != thread_to_thread_locals->end();
  9443. ++it) {
  9444. ThreadLocalValues& thread_local_values = it->second;
  9445. ThreadLocalValues::iterator value_pos =
  9446. thread_local_values.find(thread_local_instance);
  9447. if (value_pos != thread_local_values.end()) {
  9448. value_holders.push_back(value_pos->second);
  9449. thread_local_values.erase(value_pos);
  9450. // This 'if' can only be successful at most once, so theoretically we
  9451. // could break out of the loop here, but we don't bother doing so.
  9452. }
  9453. }
  9454. }
  9455. // Outside the lock, let the destructor for 'value_holders' deallocate the
  9456. // ThreadLocalValueHolderBases.
  9457. }
  9458. static void OnThreadExit(DWORD thread_id) {
  9459. GTEST_CHECK_(thread_id != 0) << ::GetLastError();
  9460. std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
  9461. // Clean up the ThreadIdToThreadLocals data structure while holding the
  9462. // lock, but defer the destruction of the ThreadLocalValueHolderBases.
  9463. {
  9464. MutexLock lock(&mutex_);
  9465. ThreadIdToThreadLocals* const thread_to_thread_locals =
  9466. GetThreadLocalsMapLocked();
  9467. ThreadIdToThreadLocals::iterator thread_local_pos =
  9468. thread_to_thread_locals->find(thread_id);
  9469. if (thread_local_pos != thread_to_thread_locals->end()) {
  9470. ThreadLocalValues& thread_local_values = thread_local_pos->second;
  9471. for (ThreadLocalValues::iterator value_pos =
  9472. thread_local_values.begin();
  9473. value_pos != thread_local_values.end();
  9474. ++value_pos) {
  9475. value_holders.push_back(value_pos->second);
  9476. }
  9477. thread_to_thread_locals->erase(thread_local_pos);
  9478. }
  9479. }
  9480. // Outside the lock, let the destructor for 'value_holders' deallocate the
  9481. // ThreadLocalValueHolderBases.
  9482. }
  9483. private:
  9484. // In a particular thread, maps a ThreadLocal object to its value.
  9485. typedef std::map<const ThreadLocalBase*,
  9486. std::shared_ptr<ThreadLocalValueHolderBase> >
  9487. ThreadLocalValues;
  9488. // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
  9489. // thread's ID.
  9490. typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
  9491. // Holds the thread id and thread handle that we pass from
  9492. // StartWatcherThreadFor to WatcherThreadFunc.
  9493. typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
  9494. static void StartWatcherThreadFor(DWORD thread_id) {
  9495. // The returned handle will be kept in thread_map and closed by
  9496. // watcher_thread in WatcherThreadFunc.
  9497. HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
  9498. FALSE,
  9499. thread_id);
  9500. GTEST_CHECK_(thread != nullptr);
  9501. // We need to pass a valid thread ID pointer into CreateThread for it
  9502. // to work correctly under Win98.
  9503. DWORD watcher_thread_id;
  9504. HANDLE watcher_thread = ::CreateThread(
  9505. nullptr, // Default security.
  9506. 0, // Default stack size
  9507. &ThreadLocalRegistryImpl::WatcherThreadFunc,
  9508. reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
  9509. CREATE_SUSPENDED, &watcher_thread_id);
  9510. GTEST_CHECK_(watcher_thread != nullptr);
  9511. // Give the watcher thread the same priority as ours to avoid being
  9512. // blocked by it.
  9513. ::SetThreadPriority(watcher_thread,
  9514. ::GetThreadPriority(::GetCurrentThread()));
  9515. ::ResumeThread(watcher_thread);
  9516. ::CloseHandle(watcher_thread);
  9517. }
  9518. // Monitors exit from a given thread and notifies those
  9519. // ThreadIdToThreadLocals about thread termination.
  9520. static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
  9521. const ThreadIdAndHandle* tah =
  9522. reinterpret_cast<const ThreadIdAndHandle*>(param);
  9523. GTEST_CHECK_(
  9524. ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
  9525. OnThreadExit(tah->first);
  9526. ::CloseHandle(tah->second);
  9527. delete tah;
  9528. return 0;
  9529. }
  9530. // Returns map of thread local instances.
  9531. static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
  9532. mutex_.AssertHeld();
  9533. #ifdef _MSC_VER
  9534. MemoryIsNotDeallocated memory_is_not_deallocated;
  9535. #endif // _MSC_VER
  9536. static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
  9537. return map;
  9538. }
  9539. // Protects access to GetThreadLocalsMapLocked() and its return value.
  9540. static Mutex mutex_;
  9541. // Protects access to GetThreadMapLocked() and its return value.
  9542. static Mutex thread_map_mutex_;
  9543. };
  9544. Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
  9545. Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
  9546. ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
  9547. const ThreadLocalBase* thread_local_instance) {
  9548. return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
  9549. thread_local_instance);
  9550. }
  9551. void ThreadLocalRegistry::OnThreadLocalDestroyed(
  9552. const ThreadLocalBase* thread_local_instance) {
  9553. ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
  9554. }
  9555. #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
  9556. #if GTEST_USES_POSIX_RE
  9557. // Implements RE. Currently only needed for death tests.
  9558. RE::~RE() {
  9559. if (is_valid_) {
  9560. // regfree'ing an invalid regex might crash because the content
  9561. // of the regex is undefined. Since the regex's are essentially
  9562. // the same, one cannot be valid (or invalid) without the other
  9563. // being so too.
  9564. regfree(&partial_regex_);
  9565. regfree(&full_regex_);
  9566. }
  9567. free(const_cast<char*>(pattern_));
  9568. }
  9569. // Returns true if and only if regular expression re matches the entire str.
  9570. bool RE::FullMatch(const char* str, const RE& re) {
  9571. if (!re.is_valid_) return false;
  9572. regmatch_t match;
  9573. return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
  9574. }
  9575. // Returns true if and only if regular expression re matches a substring of
  9576. // str (including str itself).
  9577. bool RE::PartialMatch(const char* str, const RE& re) {
  9578. if (!re.is_valid_) return false;
  9579. regmatch_t match;
  9580. return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
  9581. }
  9582. // Initializes an RE from its string representation.
  9583. void RE::Init(const char* regex) {
  9584. pattern_ = posix::StrDup(regex);
  9585. // Reserves enough bytes to hold the regular expression used for a
  9586. // full match.
  9587. const size_t full_regex_len = strlen(regex) + 10;
  9588. char* const full_pattern = new char[full_regex_len];
  9589. snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
  9590. is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
  9591. // We want to call regcomp(&partial_regex_, ...) even if the
  9592. // previous expression returns false. Otherwise partial_regex_ may
  9593. // not be properly initialized can may cause trouble when it's
  9594. // freed.
  9595. //
  9596. // Some implementation of POSIX regex (e.g. on at least some
  9597. // versions of Cygwin) doesn't accept the empty string as a valid
  9598. // regex. We change it to an equivalent form "()" to be safe.
  9599. if (is_valid_) {
  9600. const char* const partial_regex = (*regex == '\0') ? "()" : regex;
  9601. is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
  9602. }
  9603. EXPECT_TRUE(is_valid_)
  9604. << "Regular expression \"" << regex
  9605. << "\" is not a valid POSIX Extended regular expression.";
  9606. delete[] full_pattern;
  9607. }
  9608. #elif GTEST_USES_SIMPLE_RE
  9609. // Returns true if and only if ch appears anywhere in str (excluding the
  9610. // terminating '\0' character).
  9611. bool IsInSet(char ch, const char* str) {
  9612. return ch != '\0' && strchr(str, ch) != nullptr;
  9613. }
  9614. // Returns true if and only if ch belongs to the given classification.
  9615. // Unlike similar functions in <ctype.h>, these aren't affected by the
  9616. // current locale.
  9617. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
  9618. bool IsAsciiPunct(char ch) {
  9619. return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
  9620. }
  9621. bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
  9622. bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
  9623. bool IsAsciiWordChar(char ch) {
  9624. return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
  9625. ('0' <= ch && ch <= '9') || ch == '_';
  9626. }
  9627. // Returns true if and only if "\\c" is a supported escape sequence.
  9628. bool IsValidEscape(char c) {
  9629. return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
  9630. }
  9631. // Returns true if and only if the given atom (specified by escaped and
  9632. // pattern) matches ch. The result is undefined if the atom is invalid.
  9633. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
  9634. if (escaped) { // "\\p" where p is pattern_char.
  9635. switch (pattern_char) {
  9636. case 'd': return IsAsciiDigit(ch);
  9637. case 'D': return !IsAsciiDigit(ch);
  9638. case 'f': return ch == '\f';
  9639. case 'n': return ch == '\n';
  9640. case 'r': return ch == '\r';
  9641. case 's': return IsAsciiWhiteSpace(ch);
  9642. case 'S': return !IsAsciiWhiteSpace(ch);
  9643. case 't': return ch == '\t';
  9644. case 'v': return ch == '\v';
  9645. case 'w': return IsAsciiWordChar(ch);
  9646. case 'W': return !IsAsciiWordChar(ch);
  9647. }
  9648. return IsAsciiPunct(pattern_char) && pattern_char == ch;
  9649. }
  9650. return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
  9651. }
  9652. // Helper function used by ValidateRegex() to format error messages.
  9653. static std::string FormatRegexSyntaxError(const char* regex, int index) {
  9654. return (Message() << "Syntax error at index " << index
  9655. << " in simple regular expression \"" << regex << "\": ").GetString();
  9656. }
  9657. // Generates non-fatal failures and returns false if regex is invalid;
  9658. // otherwise returns true.
  9659. bool ValidateRegex(const char* regex) {
  9660. if (regex == nullptr) {
  9661. ADD_FAILURE() << "NULL is not a valid simple regular expression.";
  9662. return false;
  9663. }
  9664. bool is_valid = true;
  9665. // True if and only if ?, *, or + can follow the previous atom.
  9666. bool prev_repeatable = false;
  9667. for (int i = 0; regex[i]; i++) {
  9668. if (regex[i] == '\\') { // An escape sequence
  9669. i++;
  9670. if (regex[i] == '\0') {
  9671. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  9672. << "'\\' cannot appear at the end.";
  9673. return false;
  9674. }
  9675. if (!IsValidEscape(regex[i])) {
  9676. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  9677. << "invalid escape sequence \"\\" << regex[i] << "\".";
  9678. is_valid = false;
  9679. }
  9680. prev_repeatable = true;
  9681. } else { // Not an escape sequence.
  9682. const char ch = regex[i];
  9683. if (ch == '^' && i > 0) {
  9684. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  9685. << "'^' can only appear at the beginning.";
  9686. is_valid = false;
  9687. } else if (ch == '$' && regex[i + 1] != '\0') {
  9688. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  9689. << "'$' can only appear at the end.";
  9690. is_valid = false;
  9691. } else if (IsInSet(ch, "()[]{}|")) {
  9692. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  9693. << "'" << ch << "' is unsupported.";
  9694. is_valid = false;
  9695. } else if (IsRepeat(ch) && !prev_repeatable) {
  9696. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  9697. << "'" << ch << "' can only follow a repeatable token.";
  9698. is_valid = false;
  9699. }
  9700. prev_repeatable = !IsInSet(ch, "^$?*+");
  9701. }
  9702. }
  9703. return is_valid;
  9704. }
  9705. // Matches a repeated regex atom followed by a valid simple regular
  9706. // expression. The regex atom is defined as c if escaped is false,
  9707. // or \c otherwise. repeat is the repetition meta character (?, *,
  9708. // or +). The behavior is undefined if str contains too many
  9709. // characters to be indexable by size_t, in which case the test will
  9710. // probably time out anyway. We are fine with this limitation as
  9711. // std::string has it too.
  9712. bool MatchRepetitionAndRegexAtHead(
  9713. bool escaped, char c, char repeat, const char* regex,
  9714. const char* str) {
  9715. const size_t min_count = (repeat == '+') ? 1 : 0;
  9716. const size_t max_count = (repeat == '?') ? 1 :
  9717. static_cast<size_t>(-1) - 1;
  9718. // We cannot call numeric_limits::max() as it conflicts with the
  9719. // max() macro on Windows.
  9720. for (size_t i = 0; i <= max_count; ++i) {
  9721. // We know that the atom matches each of the first i characters in str.
  9722. if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
  9723. // We have enough matches at the head, and the tail matches too.
  9724. // Since we only care about *whether* the pattern matches str
  9725. // (as opposed to *how* it matches), there is no need to find a
  9726. // greedy match.
  9727. return true;
  9728. }
  9729. if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
  9730. return false;
  9731. }
  9732. return false;
  9733. }
  9734. // Returns true if and only if regex matches a prefix of str. regex must
  9735. // be a valid simple regular expression and not start with "^", or the
  9736. // result is undefined.
  9737. bool MatchRegexAtHead(const char* regex, const char* str) {
  9738. if (*regex == '\0') // An empty regex matches a prefix of anything.
  9739. return true;
  9740. // "$" only matches the end of a string. Note that regex being
  9741. // valid guarantees that there's nothing after "$" in it.
  9742. if (*regex == '$')
  9743. return *str == '\0';
  9744. // Is the first thing in regex an escape sequence?
  9745. const bool escaped = *regex == '\\';
  9746. if (escaped)
  9747. ++regex;
  9748. if (IsRepeat(regex[1])) {
  9749. // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
  9750. // here's an indirect recursion. It terminates as the regex gets
  9751. // shorter in each recursion.
  9752. return MatchRepetitionAndRegexAtHead(
  9753. escaped, regex[0], regex[1], regex + 2, str);
  9754. } else {
  9755. // regex isn't empty, isn't "$", and doesn't start with a
  9756. // repetition. We match the first atom of regex with the first
  9757. // character of str and recurse.
  9758. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
  9759. MatchRegexAtHead(regex + 1, str + 1);
  9760. }
  9761. }
  9762. // Returns true if and only if regex matches any substring of str. regex must
  9763. // be a valid simple regular expression, or the result is undefined.
  9764. //
  9765. // The algorithm is recursive, but the recursion depth doesn't exceed
  9766. // the regex length, so we won't need to worry about running out of
  9767. // stack space normally. In rare cases the time complexity can be
  9768. // exponential with respect to the regex length + the string length,
  9769. // but usually it's must faster (often close to linear).
  9770. bool MatchRegexAnywhere(const char* regex, const char* str) {
  9771. if (regex == nullptr || str == nullptr) return false;
  9772. if (*regex == '^')
  9773. return MatchRegexAtHead(regex + 1, str);
  9774. // A successful match can be anywhere in str.
  9775. do {
  9776. if (MatchRegexAtHead(regex, str))
  9777. return true;
  9778. } while (*str++ != '\0');
  9779. return false;
  9780. }
  9781. // Implements the RE class.
  9782. RE::~RE() {
  9783. free(const_cast<char*>(pattern_));
  9784. free(const_cast<char*>(full_pattern_));
  9785. }
  9786. // Returns true if and only if regular expression re matches the entire str.
  9787. bool RE::FullMatch(const char* str, const RE& re) {
  9788. return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
  9789. }
  9790. // Returns true if and only if regular expression re matches a substring of
  9791. // str (including str itself).
  9792. bool RE::PartialMatch(const char* str, const RE& re) {
  9793. return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
  9794. }
  9795. // Initializes an RE from its string representation.
  9796. void RE::Init(const char* regex) {
  9797. pattern_ = full_pattern_ = nullptr;
  9798. if (regex != nullptr) {
  9799. pattern_ = posix::StrDup(regex);
  9800. }
  9801. is_valid_ = ValidateRegex(regex);
  9802. if (!is_valid_) {
  9803. // No need to calculate the full pattern when the regex is invalid.
  9804. return;
  9805. }
  9806. const size_t len = strlen(regex);
  9807. // Reserves enough bytes to hold the regular expression used for a
  9808. // full match: we need space to prepend a '^', append a '$', and
  9809. // terminate the string with '\0'.
  9810. char* buffer = static_cast<char*>(malloc(len + 3));
  9811. full_pattern_ = buffer;
  9812. if (*regex != '^')
  9813. *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
  9814. // We don't use snprintf or strncpy, as they trigger a warning when
  9815. // compiled with VC++ 8.0.
  9816. memcpy(buffer, regex, len);
  9817. buffer += len;
  9818. if (len == 0 || regex[len - 1] != '$')
  9819. *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
  9820. *buffer = '\0';
  9821. }
  9822. #endif // GTEST_USES_POSIX_RE
  9823. const char kUnknownFile[] = "unknown file";
  9824. // Formats a source file path and a line number as they would appear
  9825. // in an error message from the compiler used to compile this code.
  9826. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
  9827. const std::string file_name(file == nullptr ? kUnknownFile : file);
  9828. if (line < 0) {
  9829. return file_name + ":";
  9830. }
  9831. #ifdef _MSC_VER
  9832. return file_name + "(" + StreamableToString(line) + "):";
  9833. #else
  9834. return file_name + ":" + StreamableToString(line) + ":";
  9835. #endif // _MSC_VER
  9836. }
  9837. // Formats a file location for compiler-independent XML output.
  9838. // Although this function is not platform dependent, we put it next to
  9839. // FormatFileLocation in order to contrast the two functions.
  9840. // Note that FormatCompilerIndependentFileLocation() does NOT append colon
  9841. // to the file location it produces, unlike FormatFileLocation().
  9842. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
  9843. const char* file, int line) {
  9844. const std::string file_name(file == nullptr ? kUnknownFile : file);
  9845. if (line < 0)
  9846. return file_name;
  9847. else
  9848. return file_name + ":" + StreamableToString(line);
  9849. }
  9850. GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
  9851. : severity_(severity) {
  9852. const char* const marker =
  9853. severity == GTEST_INFO ? "[ INFO ]" :
  9854. severity == GTEST_WARNING ? "[WARNING]" :
  9855. severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
  9856. GetStream() << ::std::endl << marker << " "
  9857. << FormatFileLocation(file, line).c_str() << ": ";
  9858. }
  9859. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  9860. GTestLog::~GTestLog() {
  9861. GetStream() << ::std::endl;
  9862. if (severity_ == GTEST_FATAL) {
  9863. fflush(stderr);
  9864. posix::Abort();
  9865. }
  9866. }
  9867. // Disable Microsoft deprecation warnings for POSIX functions called from
  9868. // this class (creat, dup, dup2, and close)
  9869. GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
  9870. #if GTEST_HAS_STREAM_REDIRECTION
  9871. // Object that captures an output stream (stdout/stderr).
  9872. class CapturedStream {
  9873. public:
  9874. // The ctor redirects the stream to a temporary file.
  9875. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
  9876. # if GTEST_OS_WINDOWS
  9877. char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  9878. char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  9879. ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
  9880. const UINT success = ::GetTempFileNameA(temp_dir_path,
  9881. "gtest_redir",
  9882. 0, // Generate unique file name.
  9883. temp_file_path);
  9884. GTEST_CHECK_(success != 0)
  9885. << "Unable to create a temporary file in " << temp_dir_path;
  9886. const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
  9887. GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
  9888. << temp_file_path;
  9889. filename_ = temp_file_path;
  9890. # else
  9891. // There's no guarantee that a test has write access to the current
  9892. // directory, so we create the temporary file in the /tmp directory
  9893. // instead. We use /tmp on most systems, and /sdcard on Android.
  9894. // That's because Android doesn't have /tmp.
  9895. # if GTEST_OS_LINUX_ANDROID
  9896. // Note: Android applications are expected to call the framework's
  9897. // Context.getExternalStorageDirectory() method through JNI to get
  9898. // the location of the world-writable SD Card directory. However,
  9899. // this requires a Context handle, which cannot be retrieved
  9900. // globally from native code. Doing so also precludes running the
  9901. // code as part of a regular standalone executable, which doesn't
  9902. // run in a Dalvik process (e.g. when running it through 'adb shell').
  9903. //
  9904. // The location /data/local/tmp is directly accessible from native code.
  9905. // '/sdcard' and other variants cannot be relied on, as they are not
  9906. // guaranteed to be mounted, or may have a delay in mounting.
  9907. char name_template[] = "/data/local/tmp/gtest_captured_stream.XXXXXX";
  9908. # else
  9909. char name_template[] = "/tmp/captured_stream.XXXXXX";
  9910. # endif // GTEST_OS_LINUX_ANDROID
  9911. const int captured_fd = mkstemp(name_template);
  9912. if (captured_fd == -1) {
  9913. GTEST_LOG_(WARNING)
  9914. << "Failed to create tmp file " << name_template
  9915. << " for test; does the test have access to the /tmp directory?";
  9916. }
  9917. filename_ = name_template;
  9918. # endif // GTEST_OS_WINDOWS
  9919. fflush(nullptr);
  9920. dup2(captured_fd, fd_);
  9921. close(captured_fd);
  9922. }
  9923. ~CapturedStream() {
  9924. remove(filename_.c_str());
  9925. }
  9926. std::string GetCapturedString() {
  9927. if (uncaptured_fd_ != -1) {
  9928. // Restores the original stream.
  9929. fflush(nullptr);
  9930. dup2(uncaptured_fd_, fd_);
  9931. close(uncaptured_fd_);
  9932. uncaptured_fd_ = -1;
  9933. }
  9934. FILE* const file = posix::FOpen(filename_.c_str(), "r");
  9935. if (file == nullptr) {
  9936. GTEST_LOG_(FATAL) << "Failed to open tmp file " << filename_
  9937. << " for capturing stream.";
  9938. }
  9939. const std::string content = ReadEntireFile(file);
  9940. posix::FClose(file);
  9941. return content;
  9942. }
  9943. private:
  9944. const int fd_; // A stream to capture.
  9945. int uncaptured_fd_;
  9946. // Name of the temporary file holding the stderr output.
  9947. ::std::string filename_;
  9948. GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
  9949. };
  9950. GTEST_DISABLE_MSC_DEPRECATED_POP_()
  9951. static CapturedStream* g_captured_stderr = nullptr;
  9952. static CapturedStream* g_captured_stdout = nullptr;
  9953. // Starts capturing an output stream (stdout/stderr).
  9954. static void CaptureStream(int fd, const char* stream_name,
  9955. CapturedStream** stream) {
  9956. if (*stream != nullptr) {
  9957. GTEST_LOG_(FATAL) << "Only one " << stream_name
  9958. << " capturer can exist at a time.";
  9959. }
  9960. *stream = new CapturedStream(fd);
  9961. }
  9962. // Stops capturing the output stream and returns the captured string.
  9963. static std::string GetCapturedStream(CapturedStream** captured_stream) {
  9964. const std::string content = (*captured_stream)->GetCapturedString();
  9965. delete *captured_stream;
  9966. *captured_stream = nullptr;
  9967. return content;
  9968. }
  9969. // Starts capturing stdout.
  9970. void CaptureStdout() {
  9971. CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
  9972. }
  9973. // Starts capturing stderr.
  9974. void CaptureStderr() {
  9975. CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
  9976. }
  9977. // Stops capturing stdout and returns the captured string.
  9978. std::string GetCapturedStdout() {
  9979. return GetCapturedStream(&g_captured_stdout);
  9980. }
  9981. // Stops capturing stderr and returns the captured string.
  9982. std::string GetCapturedStderr() {
  9983. return GetCapturedStream(&g_captured_stderr);
  9984. }
  9985. #endif // GTEST_HAS_STREAM_REDIRECTION
  9986. size_t GetFileSize(FILE* file) {
  9987. fseek(file, 0, SEEK_END);
  9988. return static_cast<size_t>(ftell(file));
  9989. }
  9990. std::string ReadEntireFile(FILE* file) {
  9991. const size_t file_size = GetFileSize(file);
  9992. char* const buffer = new char[file_size];
  9993. size_t bytes_last_read = 0; // # of bytes read in the last fread()
  9994. size_t bytes_read = 0; // # of bytes read so far
  9995. fseek(file, 0, SEEK_SET);
  9996. // Keeps reading the file until we cannot read further or the
  9997. // pre-determined file size is reached.
  9998. do {
  9999. bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
  10000. bytes_read += bytes_last_read;
  10001. } while (bytes_last_read > 0 && bytes_read < file_size);
  10002. const std::string content(buffer, bytes_read);
  10003. delete[] buffer;
  10004. return content;
  10005. }
  10006. #if GTEST_HAS_DEATH_TEST
  10007. static const std::vector<std::string>* g_injected_test_argvs =
  10008. nullptr; // Owned.
  10009. std::vector<std::string> GetInjectableArgvs() {
  10010. if (g_injected_test_argvs != nullptr) {
  10011. return *g_injected_test_argvs;
  10012. }
  10013. return GetArgvs();
  10014. }
  10015. void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
  10016. if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
  10017. g_injected_test_argvs = new_argvs;
  10018. }
  10019. void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
  10020. SetInjectableArgvs(
  10021. new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
  10022. }
  10023. void ClearInjectableArgvs() {
  10024. delete g_injected_test_argvs;
  10025. g_injected_test_argvs = nullptr;
  10026. }
  10027. #endif // GTEST_HAS_DEATH_TEST
  10028. #if GTEST_OS_WINDOWS_MOBILE
  10029. namespace posix {
  10030. void Abort() {
  10031. DebugBreak();
  10032. TerminateProcess(GetCurrentProcess(), 1);
  10033. }
  10034. } // namespace posix
  10035. #endif // GTEST_OS_WINDOWS_MOBILE
  10036. // Returns the name of the environment variable corresponding to the
  10037. // given flag. For example, FlagToEnvVar("foo") will return
  10038. // "GTEST_FOO" in the open-source version.
  10039. static std::string FlagToEnvVar(const char* flag) {
  10040. const std::string full_flag =
  10041. (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
  10042. Message env_var;
  10043. for (size_t i = 0; i != full_flag.length(); i++) {
  10044. env_var << ToUpper(full_flag.c_str()[i]);
  10045. }
  10046. return env_var.GetString();
  10047. }
  10048. // Parses 'str' for a 32-bit signed integer. If successful, writes
  10049. // the result to *value and returns true; otherwise leaves *value
  10050. // unchanged and returns false.
  10051. bool ParseInt32(const Message& src_text, const char* str, int32_t* value) {
  10052. // Parses the environment variable as a decimal integer.
  10053. char* end = nullptr;
  10054. const long long_value = strtol(str, &end, 10); // NOLINT
  10055. // Has strtol() consumed all characters in the string?
  10056. if (*end != '\0') {
  10057. // No - an invalid character was encountered.
  10058. Message msg;
  10059. msg << "WARNING: " << src_text
  10060. << " is expected to be a 32-bit integer, but actually"
  10061. << " has value \"" << str << "\".\n";
  10062. printf("%s", msg.GetString().c_str());
  10063. fflush(stdout);
  10064. return false;
  10065. }
  10066. // Is the parsed value in the range of an int32_t?
  10067. const auto result = static_cast<int32_t>(long_value);
  10068. if (long_value == LONG_MAX || long_value == LONG_MIN ||
  10069. // The parsed value overflows as a long. (strtol() returns
  10070. // LONG_MAX or LONG_MIN when the input overflows.)
  10071. result != long_value
  10072. // The parsed value overflows as an int32_t.
  10073. ) {
  10074. Message msg;
  10075. msg << "WARNING: " << src_text
  10076. << " is expected to be a 32-bit integer, but actually"
  10077. << " has value " << str << ", which overflows.\n";
  10078. printf("%s", msg.GetString().c_str());
  10079. fflush(stdout);
  10080. return false;
  10081. }
  10082. *value = result;
  10083. return true;
  10084. }
  10085. // Reads and returns the Boolean environment variable corresponding to
  10086. // the given flag; if it's not set, returns default_value.
  10087. //
  10088. // The value is considered true if and only if it's not "0".
  10089. bool BoolFromGTestEnv(const char* flag, bool default_value) {
  10090. #if defined(GTEST_GET_BOOL_FROM_ENV_)
  10091. return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
  10092. #else
  10093. const std::string env_var = FlagToEnvVar(flag);
  10094. const char* const string_value = posix::GetEnv(env_var.c_str());
  10095. return string_value == nullptr ? default_value
  10096. : strcmp(string_value, "0") != 0;
  10097. #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
  10098. }
  10099. // Reads and returns a 32-bit integer stored in the environment
  10100. // variable corresponding to the given flag; if it isn't set or
  10101. // doesn't represent a valid 32-bit integer, returns default_value.
  10102. int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {
  10103. #if defined(GTEST_GET_INT32_FROM_ENV_)
  10104. return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
  10105. #else
  10106. const std::string env_var = FlagToEnvVar(flag);
  10107. const char* const string_value = posix::GetEnv(env_var.c_str());
  10108. if (string_value == nullptr) {
  10109. // The environment variable is not set.
  10110. return default_value;
  10111. }
  10112. int32_t result = default_value;
  10113. if (!ParseInt32(Message() << "Environment variable " << env_var,
  10114. string_value, &result)) {
  10115. printf("The default value %s is used.\n",
  10116. (Message() << default_value).GetString().c_str());
  10117. fflush(stdout);
  10118. return default_value;
  10119. }
  10120. return result;
  10121. #endif // defined(GTEST_GET_INT32_FROM_ENV_)
  10122. }
  10123. // As a special case for the 'output' flag, if GTEST_OUTPUT is not
  10124. // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
  10125. // system. The value of XML_OUTPUT_FILE is a filename without the
  10126. // "xml:" prefix of GTEST_OUTPUT.
  10127. // Note that this is meant to be called at the call site so it does
  10128. // not check that the flag is 'output'
  10129. // In essence this checks an env variable called XML_OUTPUT_FILE
  10130. // and if it is set we prepend "xml:" to its value, if it not set we return ""
  10131. std::string OutputFlagAlsoCheckEnvVar(){
  10132. std::string default_value_for_output_flag = "";
  10133. const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
  10134. if (nullptr != xml_output_file_env) {
  10135. default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
  10136. }
  10137. return default_value_for_output_flag;
  10138. }
  10139. // Reads and returns the string environment variable corresponding to
  10140. // the given flag; if it's not set, returns default_value.
  10141. const char* StringFromGTestEnv(const char* flag, const char* default_value) {
  10142. #if defined(GTEST_GET_STRING_FROM_ENV_)
  10143. return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
  10144. #else
  10145. const std::string env_var = FlagToEnvVar(flag);
  10146. const char* const value = posix::GetEnv(env_var.c_str());
  10147. return value == nullptr ? default_value : value;
  10148. #endif // defined(GTEST_GET_STRING_FROM_ENV_)
  10149. }
  10150. } // namespace internal
  10151. } // namespace testing
  10152. // Copyright 2007, Google Inc.
  10153. // All rights reserved.
  10154. //
  10155. // Redistribution and use in source and binary forms, with or without
  10156. // modification, are permitted provided that the following conditions are
  10157. // met:
  10158. //
  10159. // * Redistributions of source code must retain the above copyright
  10160. // notice, this list of conditions and the following disclaimer.
  10161. // * Redistributions in binary form must reproduce the above
  10162. // copyright notice, this list of conditions and the following disclaimer
  10163. // in the documentation and/or other materials provided with the
  10164. // distribution.
  10165. // * Neither the name of Google Inc. nor the names of its
  10166. // contributors may be used to endorse or promote products derived from
  10167. // this software without specific prior written permission.
  10168. //
  10169. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  10170. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  10171. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  10172. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  10173. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10174. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  10175. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10176. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10177. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  10178. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  10179. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  10180. // Google Test - The Google C++ Testing and Mocking Framework
  10181. //
  10182. // This file implements a universal value printer that can print a
  10183. // value of any type T:
  10184. //
  10185. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  10186. //
  10187. // It uses the << operator when possible, and prints the bytes in the
  10188. // object otherwise. A user can override its behavior for a class
  10189. // type Foo by defining either operator<<(::std::ostream&, const Foo&)
  10190. // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
  10191. // defines Foo.
  10192. #include <stdio.h>
  10193. #include <cctype>
  10194. #include <cstdint>
  10195. #include <cwchar>
  10196. #include <ostream> // NOLINT
  10197. #include <string>
  10198. #include <type_traits>
  10199. namespace testing {
  10200. namespace {
  10201. using ::std::ostream;
  10202. // Prints a segment of bytes in the given object.
  10203. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  10204. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  10205. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  10206. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  10207. void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
  10208. size_t count, ostream* os) {
  10209. char text[5] = "";
  10210. for (size_t i = 0; i != count; i++) {
  10211. const size_t j = start + i;
  10212. if (i != 0) {
  10213. // Organizes the bytes into groups of 2 for easy parsing by
  10214. // human.
  10215. if ((j % 2) == 0)
  10216. *os << ' ';
  10217. else
  10218. *os << '-';
  10219. }
  10220. GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
  10221. *os << text;
  10222. }
  10223. }
  10224. // Prints the bytes in the given value to the given ostream.
  10225. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
  10226. ostream* os) {
  10227. // Tells the user how big the object is.
  10228. *os << count << "-byte object <";
  10229. const size_t kThreshold = 132;
  10230. const size_t kChunkSize = 64;
  10231. // If the object size is bigger than kThreshold, we'll have to omit
  10232. // some details by printing only the first and the last kChunkSize
  10233. // bytes.
  10234. if (count < kThreshold) {
  10235. PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
  10236. } else {
  10237. PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
  10238. *os << " ... ";
  10239. // Rounds up to 2-byte boundary.
  10240. const size_t resume_pos = (count - kChunkSize + 1)/2*2;
  10241. PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
  10242. }
  10243. *os << ">";
  10244. }
  10245. // Helpers for widening a character to char32_t. Since the standard does not
  10246. // specify if char / wchar_t is signed or unsigned, it is important to first
  10247. // convert it to the unsigned type of the same width before widening it to
  10248. // char32_t.
  10249. template <typename CharType>
  10250. char32_t ToChar32(CharType in) {
  10251. return static_cast<char32_t>(
  10252. static_cast<typename std::make_unsigned<CharType>::type>(in));
  10253. }
  10254. } // namespace
  10255. namespace internal {
  10256. // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
  10257. // given object. The delegation simplifies the implementation, which
  10258. // uses the << operator and thus is easier done outside of the
  10259. // ::testing::internal namespace, which contains a << operator that
  10260. // sometimes conflicts with the one in STL.
  10261. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
  10262. ostream* os) {
  10263. PrintBytesInObjectToImpl(obj_bytes, count, os);
  10264. }
  10265. // Depending on the value of a char (or wchar_t), we print it in one
  10266. // of three formats:
  10267. // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
  10268. // - as a hexadecimal escape sequence (e.g. '\x7F'), or
  10269. // - as a special escape sequence (e.g. '\r', '\n').
  10270. enum CharFormat {
  10271. kAsIs,
  10272. kHexEscape,
  10273. kSpecialEscape
  10274. };
  10275. // Returns true if c is a printable ASCII character. We test the
  10276. // value of c directly instead of calling isprint(), which is buggy on
  10277. // Windows Mobile.
  10278. inline bool IsPrintableAscii(char32_t c) { return 0x20 <= c && c <= 0x7E; }
  10279. // Prints c (of type char, char8_t, char16_t, char32_t, or wchar_t) as a
  10280. // character literal without the quotes, escaping it when necessary; returns how
  10281. // c was formatted.
  10282. template <typename Char>
  10283. static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
  10284. const char32_t u_c = ToChar32(c);
  10285. switch (u_c) {
  10286. case L'\0':
  10287. *os << "\\0";
  10288. break;
  10289. case L'\'':
  10290. *os << "\\'";
  10291. break;
  10292. case L'\\':
  10293. *os << "\\\\";
  10294. break;
  10295. case L'\a':
  10296. *os << "\\a";
  10297. break;
  10298. case L'\b':
  10299. *os << "\\b";
  10300. break;
  10301. case L'\f':
  10302. *os << "\\f";
  10303. break;
  10304. case L'\n':
  10305. *os << "\\n";
  10306. break;
  10307. case L'\r':
  10308. *os << "\\r";
  10309. break;
  10310. case L'\t':
  10311. *os << "\\t";
  10312. break;
  10313. case L'\v':
  10314. *os << "\\v";
  10315. break;
  10316. default:
  10317. if (IsPrintableAscii(u_c)) {
  10318. *os << static_cast<char>(c);
  10319. return kAsIs;
  10320. } else {
  10321. ostream::fmtflags flags = os->flags();
  10322. *os << "\\x" << std::hex << std::uppercase << static_cast<int>(u_c);
  10323. os->flags(flags);
  10324. return kHexEscape;
  10325. }
  10326. }
  10327. return kSpecialEscape;
  10328. }
  10329. // Prints a char32_t c as if it's part of a string literal, escaping it when
  10330. // necessary; returns how c was formatted.
  10331. static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {
  10332. switch (c) {
  10333. case L'\'':
  10334. *os << "'";
  10335. return kAsIs;
  10336. case L'"':
  10337. *os << "\\\"";
  10338. return kSpecialEscape;
  10339. default:
  10340. return PrintAsCharLiteralTo(c, os);
  10341. }
  10342. }
  10343. static const char* GetCharWidthPrefix(char) {
  10344. return "";
  10345. }
  10346. static const char* GetCharWidthPrefix(signed char) {
  10347. return "";
  10348. }
  10349. static const char* GetCharWidthPrefix(unsigned char) {
  10350. return "";
  10351. }
  10352. #ifdef __cpp_char8_t
  10353. static const char* GetCharWidthPrefix(char8_t) {
  10354. return "u8";
  10355. }
  10356. #endif
  10357. static const char* GetCharWidthPrefix(char16_t) {
  10358. return "u";
  10359. }
  10360. static const char* GetCharWidthPrefix(char32_t) {
  10361. return "U";
  10362. }
  10363. static const char* GetCharWidthPrefix(wchar_t) {
  10364. return "L";
  10365. }
  10366. // Prints a char c as if it's part of a string literal, escaping it when
  10367. // necessary; returns how c was formatted.
  10368. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
  10369. return PrintAsStringLiteralTo(ToChar32(c), os);
  10370. }
  10371. #ifdef __cpp_char8_t
  10372. static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {
  10373. return PrintAsStringLiteralTo(ToChar32(c), os);
  10374. }
  10375. #endif
  10376. static CharFormat PrintAsStringLiteralTo(char16_t c, ostream* os) {
  10377. return PrintAsStringLiteralTo(ToChar32(c), os);
  10378. }
  10379. static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
  10380. return PrintAsStringLiteralTo(ToChar32(c), os);
  10381. }
  10382. // Prints a character c (of type char, char8_t, char16_t, char32_t, or wchar_t)
  10383. // and its code. '\0' is printed as "'\\0'", other unprintable characters are
  10384. // also properly escaped using the standard C++ escape sequence.
  10385. template <typename Char>
  10386. void PrintCharAndCodeTo(Char c, ostream* os) {
  10387. // First, print c as a literal in the most readable form we can find.
  10388. *os << GetCharWidthPrefix(c) << "'";
  10389. const CharFormat format = PrintAsCharLiteralTo(c, os);
  10390. *os << "'";
  10391. // To aid user debugging, we also print c's code in decimal, unless
  10392. // it's 0 (in which case c was printed as '\\0', making the code
  10393. // obvious).
  10394. if (c == 0)
  10395. return;
  10396. *os << " (" << static_cast<int>(c);
  10397. // For more convenience, we print c's code again in hexadecimal,
  10398. // unless c was already printed in the form '\x##' or the code is in
  10399. // [1, 9].
  10400. if (format == kHexEscape || (1 <= c && c <= 9)) {
  10401. // Do nothing.
  10402. } else {
  10403. *os << ", 0x" << String::FormatHexInt(static_cast<int>(c));
  10404. }
  10405. *os << ")";
  10406. }
  10407. void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
  10408. void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
  10409. // Prints a wchar_t as a symbol if it is printable or as its internal
  10410. // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
  10411. void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); }
  10412. // TODO(dcheng): Consider making this delegate to PrintCharAndCodeTo() as well.
  10413. void PrintTo(char32_t c, ::std::ostream* os) {
  10414. *os << std::hex << "U+" << std::uppercase << std::setfill('0') << std::setw(4)
  10415. << static_cast<uint32_t>(c);
  10416. }
  10417. // Prints the given array of characters to the ostream. CharType must be either
  10418. // char, char8_t, char16_t, char32_t, or wchar_t.
  10419. // The array starts at begin, the length is len, it may include '\0' characters
  10420. // and may not be NUL-terminated.
  10421. template <typename CharType>
  10422. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  10423. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  10424. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  10425. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  10426. static CharFormat PrintCharsAsStringTo(
  10427. const CharType* begin, size_t len, ostream* os) {
  10428. const char* const quote_prefix = GetCharWidthPrefix(*begin);
  10429. *os << quote_prefix << "\"";
  10430. bool is_previous_hex = false;
  10431. CharFormat print_format = kAsIs;
  10432. for (size_t index = 0; index < len; ++index) {
  10433. const CharType cur = begin[index];
  10434. if (is_previous_hex && IsXDigit(cur)) {
  10435. // Previous character is of '\x..' form and this character can be
  10436. // interpreted as another hexadecimal digit in its number. Break string to
  10437. // disambiguate.
  10438. *os << "\" " << quote_prefix << "\"";
  10439. }
  10440. is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
  10441. // Remember if any characters required hex escaping.
  10442. if (is_previous_hex) {
  10443. print_format = kHexEscape;
  10444. }
  10445. }
  10446. *os << "\"";
  10447. return print_format;
  10448. }
  10449. // Prints a (const) char/wchar_t array of 'len' elements, starting at address
  10450. // 'begin'. CharType must be either char or wchar_t.
  10451. template <typename CharType>
  10452. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  10453. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  10454. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  10455. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  10456. static void UniversalPrintCharArray(
  10457. const CharType* begin, size_t len, ostream* os) {
  10458. // The code
  10459. // const char kFoo[] = "foo";
  10460. // generates an array of 4, not 3, elements, with the last one being '\0'.
  10461. //
  10462. // Therefore when printing a char array, we don't print the last element if
  10463. // it's '\0', such that the output matches the string literal as it's
  10464. // written in the source code.
  10465. if (len > 0 && begin[len - 1] == '\0') {
  10466. PrintCharsAsStringTo(begin, len - 1, os);
  10467. return;
  10468. }
  10469. // If, however, the last element in the array is not '\0', e.g.
  10470. // const char kFoo[] = { 'f', 'o', 'o' };
  10471. // we must print the entire array. We also print a message to indicate
  10472. // that the array is not NUL-terminated.
  10473. PrintCharsAsStringTo(begin, len, os);
  10474. *os << " (no terminating NUL)";
  10475. }
  10476. // Prints a (const) char array of 'len' elements, starting at address 'begin'.
  10477. void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
  10478. UniversalPrintCharArray(begin, len, os);
  10479. }
  10480. #ifdef __cpp_char8_t
  10481. // Prints a (const) char8_t array of 'len' elements, starting at address
  10482. // 'begin'.
  10483. void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {
  10484. UniversalPrintCharArray(begin, len, os);
  10485. }
  10486. #endif
  10487. // Prints a (const) char16_t array of 'len' elements, starting at address
  10488. // 'begin'.
  10489. void UniversalPrintArray(const char16_t* begin, size_t len, ostream* os) {
  10490. UniversalPrintCharArray(begin, len, os);
  10491. }
  10492. // Prints a (const) char32_t array of 'len' elements, starting at address
  10493. // 'begin'.
  10494. void UniversalPrintArray(const char32_t* begin, size_t len, ostream* os) {
  10495. UniversalPrintCharArray(begin, len, os);
  10496. }
  10497. // Prints a (const) wchar_t array of 'len' elements, starting at address
  10498. // 'begin'.
  10499. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
  10500. UniversalPrintCharArray(begin, len, os);
  10501. }
  10502. namespace {
  10503. // Prints a null-terminated C-style string to the ostream.
  10504. template <typename Char>
  10505. void PrintCStringTo(const Char* s, ostream* os) {
  10506. if (s == nullptr) {
  10507. *os << "NULL";
  10508. } else {
  10509. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  10510. PrintCharsAsStringTo(s, std::char_traits<Char>::length(s), os);
  10511. }
  10512. }
  10513. } // anonymous namespace
  10514. void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }
  10515. #ifdef __cpp_char8_t
  10516. void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }
  10517. #endif
  10518. void PrintTo(const char16_t* s, ostream* os) { PrintCStringTo(s, os); }
  10519. void PrintTo(const char32_t* s, ostream* os) { PrintCStringTo(s, os); }
  10520. // MSVC compiler can be configured to define whar_t as a typedef
  10521. // of unsigned short. Defining an overload for const wchar_t* in that case
  10522. // would cause pointers to unsigned shorts be printed as wide strings,
  10523. // possibly accessing more memory than intended and causing invalid
  10524. // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
  10525. // wchar_t is implemented as a native type.
  10526. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  10527. // Prints the given wide C string to the ostream.
  10528. void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }
  10529. #endif // wchar_t is native
  10530. namespace {
  10531. bool ContainsUnprintableControlCodes(const char* str, size_t length) {
  10532. const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
  10533. for (size_t i = 0; i < length; i++) {
  10534. unsigned char ch = *s++;
  10535. if (std::iscntrl(ch)) {
  10536. switch (ch) {
  10537. case '\t':
  10538. case '\n':
  10539. case '\r':
  10540. break;
  10541. default:
  10542. return true;
  10543. }
  10544. }
  10545. }
  10546. return false;
  10547. }
  10548. bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
  10549. bool IsValidUTF8(const char* str, size_t length) {
  10550. const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
  10551. for (size_t i = 0; i < length;) {
  10552. unsigned char lead = s[i++];
  10553. if (lead <= 0x7f) {
  10554. continue; // single-byte character (ASCII) 0..7F
  10555. }
  10556. if (lead < 0xc2) {
  10557. return false; // trail byte or non-shortest form
  10558. } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
  10559. ++i; // 2-byte character
  10560. } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
  10561. IsUTF8TrailByte(s[i]) &&
  10562. IsUTF8TrailByte(s[i + 1]) &&
  10563. // check for non-shortest form and surrogate
  10564. (lead != 0xe0 || s[i] >= 0xa0) &&
  10565. (lead != 0xed || s[i] < 0xa0)) {
  10566. i += 2; // 3-byte character
  10567. } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
  10568. IsUTF8TrailByte(s[i]) &&
  10569. IsUTF8TrailByte(s[i + 1]) &&
  10570. IsUTF8TrailByte(s[i + 2]) &&
  10571. // check for non-shortest form
  10572. (lead != 0xf0 || s[i] >= 0x90) &&
  10573. (lead != 0xf4 || s[i] < 0x90)) {
  10574. i += 3; // 4-byte character
  10575. } else {
  10576. return false;
  10577. }
  10578. }
  10579. return true;
  10580. }
  10581. void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
  10582. if (!ContainsUnprintableControlCodes(str, length) &&
  10583. IsValidUTF8(str, length)) {
  10584. *os << "\n As Text: \"" << str << "\"";
  10585. }
  10586. }
  10587. } // anonymous namespace
  10588. void PrintStringTo(const ::std::string& s, ostream* os) {
  10589. if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
  10590. if (GTEST_FLAG(print_utf8)) {
  10591. ConditionalPrintAsText(s.data(), s.size(), os);
  10592. }
  10593. }
  10594. }
  10595. #ifdef __cpp_char8_t
  10596. void PrintU8StringTo(const ::std::u8string& s, ostream* os) {
  10597. PrintCharsAsStringTo(s.data(), s.size(), os);
  10598. }
  10599. #endif
  10600. void PrintU16StringTo(const ::std::u16string& s, ostream* os) {
  10601. PrintCharsAsStringTo(s.data(), s.size(), os);
  10602. }
  10603. void PrintU32StringTo(const ::std::u32string& s, ostream* os) {
  10604. PrintCharsAsStringTo(s.data(), s.size(), os);
  10605. }
  10606. #if GTEST_HAS_STD_WSTRING
  10607. void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
  10608. PrintCharsAsStringTo(s.data(), s.size(), os);
  10609. }
  10610. #endif // GTEST_HAS_STD_WSTRING
  10611. } // namespace internal
  10612. } // namespace testing
  10613. // Copyright 2008, Google Inc.
  10614. // All rights reserved.
  10615. //
  10616. // Redistribution and use in source and binary forms, with or without
  10617. // modification, are permitted provided that the following conditions are
  10618. // met:
  10619. //
  10620. // * Redistributions of source code must retain the above copyright
  10621. // notice, this list of conditions and the following disclaimer.
  10622. // * Redistributions in binary form must reproduce the above
  10623. // copyright notice, this list of conditions and the following disclaimer
  10624. // in the documentation and/or other materials provided with the
  10625. // distribution.
  10626. // * Neither the name of Google Inc. nor the names of its
  10627. // contributors may be used to endorse or promote products derived from
  10628. // this software without specific prior written permission.
  10629. //
  10630. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  10631. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  10632. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  10633. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  10634. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10635. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  10636. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10637. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10638. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  10639. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  10640. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  10641. //
  10642. // The Google C++ Testing and Mocking Framework (Google Test)
  10643. namespace testing {
  10644. using internal::GetUnitTestImpl;
  10645. // Gets the summary of the failure message by omitting the stack trace
  10646. // in it.
  10647. std::string TestPartResult::ExtractSummary(const char* message) {
  10648. const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
  10649. return stack_trace == nullptr ? message : std::string(message, stack_trace);
  10650. }
  10651. // Prints a TestPartResult object.
  10652. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
  10653. return os << internal::FormatFileLocation(result.file_name(),
  10654. result.line_number())
  10655. << " "
  10656. << (result.type() == TestPartResult::kSuccess
  10657. ? "Success"
  10658. : result.type() == TestPartResult::kSkip
  10659. ? "Skipped"
  10660. : result.type() == TestPartResult::kFatalFailure
  10661. ? "Fatal failure"
  10662. : "Non-fatal failure")
  10663. << ":\n"
  10664. << result.message() << std::endl;
  10665. }
  10666. // Appends a TestPartResult to the array.
  10667. void TestPartResultArray::Append(const TestPartResult& result) {
  10668. array_.push_back(result);
  10669. }
  10670. // Returns the TestPartResult at the given index (0-based).
  10671. const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
  10672. if (index < 0 || index >= size()) {
  10673. printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
  10674. internal::posix::Abort();
  10675. }
  10676. return array_[static_cast<size_t>(index)];
  10677. }
  10678. // Returns the number of TestPartResult objects in the array.
  10679. int TestPartResultArray::size() const {
  10680. return static_cast<int>(array_.size());
  10681. }
  10682. namespace internal {
  10683. HasNewFatalFailureHelper::HasNewFatalFailureHelper()
  10684. : has_new_fatal_failure_(false),
  10685. original_reporter_(GetUnitTestImpl()->
  10686. GetTestPartResultReporterForCurrentThread()) {
  10687. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
  10688. }
  10689. HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
  10690. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
  10691. original_reporter_);
  10692. }
  10693. void HasNewFatalFailureHelper::ReportTestPartResult(
  10694. const TestPartResult& result) {
  10695. if (result.fatally_failed())
  10696. has_new_fatal_failure_ = true;
  10697. original_reporter_->ReportTestPartResult(result);
  10698. }
  10699. } // namespace internal
  10700. } // namespace testing
  10701. // Copyright 2008 Google Inc.
  10702. // All Rights Reserved.
  10703. //
  10704. // Redistribution and use in source and binary forms, with or without
  10705. // modification, are permitted provided that the following conditions are
  10706. // met:
  10707. //
  10708. // * Redistributions of source code must retain the above copyright
  10709. // notice, this list of conditions and the following disclaimer.
  10710. // * Redistributions in binary form must reproduce the above
  10711. // copyright notice, this list of conditions and the following disclaimer
  10712. // in the documentation and/or other materials provided with the
  10713. // distribution.
  10714. // * Neither the name of Google Inc. nor the names of its
  10715. // contributors may be used to endorse or promote products derived from
  10716. // this software without specific prior written permission.
  10717. //
  10718. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  10719. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  10720. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  10721. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  10722. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10723. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  10724. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10725. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10726. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  10727. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  10728. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  10729. namespace testing {
  10730. namespace internal {
  10731. // Skips to the first non-space char in str. Returns an empty string if str
  10732. // contains only whitespace characters.
  10733. static const char* SkipSpaces(const char* str) {
  10734. while (IsSpace(*str))
  10735. str++;
  10736. return str;
  10737. }
  10738. static std::vector<std::string> SplitIntoTestNames(const char* src) {
  10739. std::vector<std::string> name_vec;
  10740. src = SkipSpaces(src);
  10741. for (; src != nullptr; src = SkipComma(src)) {
  10742. name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
  10743. }
  10744. return name_vec;
  10745. }
  10746. // Verifies that registered_tests match the test names in
  10747. // registered_tests_; returns registered_tests if successful, or
  10748. // aborts the program otherwise.
  10749. const char* TypedTestSuitePState::VerifyRegisteredTestNames(
  10750. const char* test_suite_name, const char* file, int line,
  10751. const char* registered_tests) {
  10752. RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line));
  10753. typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
  10754. registered_ = true;
  10755. std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
  10756. Message errors;
  10757. std::set<std::string> tests;
  10758. for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
  10759. name_it != name_vec.end(); ++name_it) {
  10760. const std::string& name = *name_it;
  10761. if (tests.count(name) != 0) {
  10762. errors << "Test " << name << " is listed more than once.\n";
  10763. continue;
  10764. }
  10765. if (registered_tests_.count(name) != 0) {
  10766. tests.insert(name);
  10767. } else {
  10768. errors << "No test named " << name
  10769. << " can be found in this test suite.\n";
  10770. }
  10771. }
  10772. for (RegisteredTestIter it = registered_tests_.begin();
  10773. it != registered_tests_.end();
  10774. ++it) {
  10775. if (tests.count(it->first) == 0) {
  10776. errors << "You forgot to list test " << it->first << ".\n";
  10777. }
  10778. }
  10779. const std::string& errors_str = errors.GetString();
  10780. if (errors_str != "") {
  10781. fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
  10782. errors_str.c_str());
  10783. fflush(stderr);
  10784. posix::Abort();
  10785. }
  10786. return registered_tests;
  10787. }
  10788. } // namespace internal
  10789. } // namespace testing
  10790. // Copyright 2008, Google Inc.
  10791. // All rights reserved.
  10792. //
  10793. // Redistribution and use in source and binary forms, with or without
  10794. // modification, are permitted provided that the following conditions are
  10795. // met:
  10796. //
  10797. // * Redistributions of source code must retain the above copyright
  10798. // notice, this list of conditions and the following disclaimer.
  10799. // * Redistributions in binary form must reproduce the above
  10800. // copyright notice, this list of conditions and the following disclaimer
  10801. // in the documentation and/or other materials provided with the
  10802. // distribution.
  10803. // * Neither the name of Google Inc. nor the names of its
  10804. // contributors may be used to endorse or promote products derived from
  10805. // this software without specific prior written permission.
  10806. //
  10807. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  10808. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  10809. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  10810. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  10811. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10812. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  10813. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10814. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10815. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  10816. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  10817. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  10818. //
  10819. // Google C++ Mocking Framework (Google Mock)
  10820. //
  10821. // This file #includes all Google Mock implementation .cc files. The
  10822. // purpose is to allow a user to build Google Mock by compiling this
  10823. // file alone.
  10824. // This line ensures that gmock.h can be compiled on its own, even
  10825. // when it's fused.
  10826. #include "gmock/gmock.h"
  10827. // The following lines pull in the real gmock *.cc files.
  10828. // Copyright 2007, Google Inc.
  10829. // All rights reserved.
  10830. //
  10831. // Redistribution and use in source and binary forms, with or without
  10832. // modification, are permitted provided that the following conditions are
  10833. // met:
  10834. //
  10835. // * Redistributions of source code must retain the above copyright
  10836. // notice, this list of conditions and the following disclaimer.
  10837. // * Redistributions in binary form must reproduce the above
  10838. // copyright notice, this list of conditions and the following disclaimer
  10839. // in the documentation and/or other materials provided with the
  10840. // distribution.
  10841. // * Neither the name of Google Inc. nor the names of its
  10842. // contributors may be used to endorse or promote products derived from
  10843. // this software without specific prior written permission.
  10844. //
  10845. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  10846. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  10847. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  10848. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  10849. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10850. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  10851. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10852. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10853. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  10854. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  10855. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  10856. // Google Mock - a framework for writing C++ mock classes.
  10857. //
  10858. // This file implements cardinalities.
  10859. #include <limits.h>
  10860. #include <ostream> // NOLINT
  10861. #include <sstream>
  10862. #include <string>
  10863. namespace testing {
  10864. namespace {
  10865. // Implements the Between(m, n) cardinality.
  10866. class BetweenCardinalityImpl : public CardinalityInterface {
  10867. public:
  10868. BetweenCardinalityImpl(int min, int max)
  10869. : min_(min >= 0 ? min : 0),
  10870. max_(max >= min_ ? max : min_) {
  10871. std::stringstream ss;
  10872. if (min < 0) {
  10873. ss << "The invocation lower bound must be >= 0, "
  10874. << "but is actually " << min << ".";
  10875. internal::Expect(false, __FILE__, __LINE__, ss.str());
  10876. } else if (max < 0) {
  10877. ss << "The invocation upper bound must be >= 0, "
  10878. << "but is actually " << max << ".";
  10879. internal::Expect(false, __FILE__, __LINE__, ss.str());
  10880. } else if (min > max) {
  10881. ss << "The invocation upper bound (" << max
  10882. << ") must be >= the invocation lower bound (" << min
  10883. << ").";
  10884. internal::Expect(false, __FILE__, __LINE__, ss.str());
  10885. }
  10886. }
  10887. // Conservative estimate on the lower/upper bound of the number of
  10888. // calls allowed.
  10889. int ConservativeLowerBound() const override { return min_; }
  10890. int ConservativeUpperBound() const override { return max_; }
  10891. bool IsSatisfiedByCallCount(int call_count) const override {
  10892. return min_ <= call_count && call_count <= max_;
  10893. }
  10894. bool IsSaturatedByCallCount(int call_count) const override {
  10895. return call_count >= max_;
  10896. }
  10897. void DescribeTo(::std::ostream* os) const override;
  10898. private:
  10899. const int min_;
  10900. const int max_;
  10901. GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
  10902. };
  10903. // Formats "n times" in a human-friendly way.
  10904. inline std::string FormatTimes(int n) {
  10905. if (n == 1) {
  10906. return "once";
  10907. } else if (n == 2) {
  10908. return "twice";
  10909. } else {
  10910. std::stringstream ss;
  10911. ss << n << " times";
  10912. return ss.str();
  10913. }
  10914. }
  10915. // Describes the Between(m, n) cardinality in human-friendly text.
  10916. void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
  10917. if (min_ == 0) {
  10918. if (max_ == 0) {
  10919. *os << "never called";
  10920. } else if (max_ == INT_MAX) {
  10921. *os << "called any number of times";
  10922. } else {
  10923. *os << "called at most " << FormatTimes(max_);
  10924. }
  10925. } else if (min_ == max_) {
  10926. *os << "called " << FormatTimes(min_);
  10927. } else if (max_ == INT_MAX) {
  10928. *os << "called at least " << FormatTimes(min_);
  10929. } else {
  10930. // 0 < min_ < max_ < INT_MAX
  10931. *os << "called between " << min_ << " and " << max_ << " times";
  10932. }
  10933. }
  10934. } // Unnamed namespace
  10935. // Describes the given call count to an ostream.
  10936. void Cardinality::DescribeActualCallCountTo(int actual_call_count,
  10937. ::std::ostream* os) {
  10938. if (actual_call_count > 0) {
  10939. *os << "called " << FormatTimes(actual_call_count);
  10940. } else {
  10941. *os << "never called";
  10942. }
  10943. }
  10944. // Creates a cardinality that allows at least n calls.
  10945. GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
  10946. // Creates a cardinality that allows at most n calls.
  10947. GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
  10948. // Creates a cardinality that allows any number of calls.
  10949. GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }
  10950. // Creates a cardinality that allows between min and max calls.
  10951. GTEST_API_ Cardinality Between(int min, int max) {
  10952. return Cardinality(new BetweenCardinalityImpl(min, max));
  10953. }
  10954. // Creates a cardinality that allows exactly n calls.
  10955. GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
  10956. } // namespace testing
  10957. // Copyright 2007, Google Inc.
  10958. // All rights reserved.
  10959. //
  10960. // Redistribution and use in source and binary forms, with or without
  10961. // modification, are permitted provided that the following conditions are
  10962. // met:
  10963. //
  10964. // * Redistributions of source code must retain the above copyright
  10965. // notice, this list of conditions and the following disclaimer.
  10966. // * Redistributions in binary form must reproduce the above
  10967. // copyright notice, this list of conditions and the following disclaimer
  10968. // in the documentation and/or other materials provided with the
  10969. // distribution.
  10970. // * Neither the name of Google Inc. nor the names of its
  10971. // contributors may be used to endorse or promote products derived from
  10972. // this software without specific prior written permission.
  10973. //
  10974. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  10975. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  10976. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  10977. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  10978. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10979. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  10980. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10981. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10982. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  10983. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  10984. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  10985. // Google Mock - a framework for writing C++ mock classes.
  10986. //
  10987. // This file defines some utilities useful for implementing Google
  10988. // Mock. They are subject to change without notice, so please DO NOT
  10989. // USE THEM IN USER CODE.
  10990. #include <ctype.h>
  10991. #include <ostream> // NOLINT
  10992. #include <string>
  10993. namespace testing {
  10994. namespace internal {
  10995. // Joins a vector of strings as if they are fields of a tuple; returns
  10996. // the joined string.
  10997. GTEST_API_ std::string JoinAsTuple(const Strings& fields) {
  10998. switch (fields.size()) {
  10999. case 0:
  11000. return "";
  11001. case 1:
  11002. return fields[0];
  11003. default:
  11004. std::string result = "(" + fields[0];
  11005. for (size_t i = 1; i < fields.size(); i++) {
  11006. result += ", ";
  11007. result += fields[i];
  11008. }
  11009. result += ")";
  11010. return result;
  11011. }
  11012. }
  11013. // Converts an identifier name to a space-separated list of lower-case
  11014. // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
  11015. // treated as one word. For example, both "FooBar123" and
  11016. // "foo_bar_123" are converted to "foo bar 123".
  11017. GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
  11018. std::string result;
  11019. char prev_char = '\0';
  11020. for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
  11021. // We don't care about the current locale as the input is
  11022. // guaranteed to be a valid C++ identifier name.
  11023. const bool starts_new_word = IsUpper(*p) ||
  11024. (!IsAlpha(prev_char) && IsLower(*p)) ||
  11025. (!IsDigit(prev_char) && IsDigit(*p));
  11026. if (IsAlNum(*p)) {
  11027. if (starts_new_word && result != "")
  11028. result += ' ';
  11029. result += ToLower(*p);
  11030. }
  11031. }
  11032. return result;
  11033. }
  11034. // This class reports Google Mock failures as Google Test failures. A
  11035. // user can define another class in a similar fashion if they intend to
  11036. // use Google Mock with a testing framework other than Google Test.
  11037. class GoogleTestFailureReporter : public FailureReporterInterface {
  11038. public:
  11039. void ReportFailure(FailureType type, const char* file, int line,
  11040. const std::string& message) override {
  11041. AssertHelper(type == kFatal ?
  11042. TestPartResult::kFatalFailure :
  11043. TestPartResult::kNonFatalFailure,
  11044. file,
  11045. line,
  11046. message.c_str()) = Message();
  11047. if (type == kFatal) {
  11048. posix::Abort();
  11049. }
  11050. }
  11051. };
  11052. // Returns the global failure reporter. Will create a
  11053. // GoogleTestFailureReporter and return it the first time called.
  11054. GTEST_API_ FailureReporterInterface* GetFailureReporter() {
  11055. // Points to the global failure reporter used by Google Mock. gcc
  11056. // guarantees that the following use of failure_reporter is
  11057. // thread-safe. We may need to add additional synchronization to
  11058. // protect failure_reporter if we port Google Mock to other
  11059. // compilers.
  11060. static FailureReporterInterface* const failure_reporter =
  11061. new GoogleTestFailureReporter();
  11062. return failure_reporter;
  11063. }
  11064. // Protects global resources (stdout in particular) used by Log().
  11065. static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
  11066. // Returns true if and only if a log with the given severity is visible
  11067. // according to the --gmock_verbose flag.
  11068. GTEST_API_ bool LogIsVisible(LogSeverity severity) {
  11069. if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
  11070. // Always show the log if --gmock_verbose=info.
  11071. return true;
  11072. } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
  11073. // Always hide it if --gmock_verbose=error.
  11074. return false;
  11075. } else {
  11076. // If --gmock_verbose is neither "info" nor "error", we treat it
  11077. // as "warning" (its default value).
  11078. return severity == kWarning;
  11079. }
  11080. }
  11081. // Prints the given message to stdout if and only if 'severity' >= the level
  11082. // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
  11083. // 0, also prints the stack trace excluding the top
  11084. // stack_frames_to_skip frames. In opt mode, any positive
  11085. // stack_frames_to_skip is treated as 0, since we don't know which
  11086. // function calls will be inlined by the compiler and need to be
  11087. // conservative.
  11088. GTEST_API_ void Log(LogSeverity severity, const std::string& message,
  11089. int stack_frames_to_skip) {
  11090. if (!LogIsVisible(severity))
  11091. return;
  11092. // Ensures that logs from different threads don't interleave.
  11093. MutexLock l(&g_log_mutex);
  11094. if (severity == kWarning) {
  11095. // Prints a GMOCK WARNING marker to make the warnings easily searchable.
  11096. std::cout << "\nGMOCK WARNING:";
  11097. }
  11098. // Pre-pends a new-line to message if it doesn't start with one.
  11099. if (message.empty() || message[0] != '\n') {
  11100. std::cout << "\n";
  11101. }
  11102. std::cout << message;
  11103. if (stack_frames_to_skip >= 0) {
  11104. #ifdef NDEBUG
  11105. // In opt mode, we have to be conservative and skip no stack frame.
  11106. const int actual_to_skip = 0;
  11107. #else
  11108. // In dbg mode, we can do what the caller tell us to do (plus one
  11109. // for skipping this function's stack frame).
  11110. const int actual_to_skip = stack_frames_to_skip + 1;
  11111. #endif // NDEBUG
  11112. // Appends a new-line to message if it doesn't end with one.
  11113. if (!message.empty() && *message.rbegin() != '\n') {
  11114. std::cout << "\n";
  11115. }
  11116. std::cout << "Stack trace:\n"
  11117. << ::testing::internal::GetCurrentOsStackTraceExceptTop(
  11118. ::testing::UnitTest::GetInstance(), actual_to_skip);
  11119. }
  11120. std::cout << ::std::flush;
  11121. }
  11122. GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
  11123. GTEST_API_ void IllegalDoDefault(const char* file, int line) {
  11124. internal::Assert(
  11125. false, file, line,
  11126. "You are using DoDefault() inside a composite action like "
  11127. "DoAll() or WithArgs(). This is not supported for technical "
  11128. "reasons. Please instead spell out the default action, or "
  11129. "assign the default action to an Action variable and use "
  11130. "the variable in various places.");
  11131. }
  11132. } // namespace internal
  11133. } // namespace testing
  11134. // Copyright 2007, Google Inc.
  11135. // All rights reserved.
  11136. //
  11137. // Redistribution and use in source and binary forms, with or without
  11138. // modification, are permitted provided that the following conditions are
  11139. // met:
  11140. //
  11141. // * Redistributions of source code must retain the above copyright
  11142. // notice, this list of conditions and the following disclaimer.
  11143. // * Redistributions in binary form must reproduce the above
  11144. // copyright notice, this list of conditions and the following disclaimer
  11145. // in the documentation and/or other materials provided with the
  11146. // distribution.
  11147. // * Neither the name of Google Inc. nor the names of its
  11148. // contributors may be used to endorse or promote products derived from
  11149. // this software without specific prior written permission.
  11150. //
  11151. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  11152. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  11153. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  11154. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  11155. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  11156. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  11157. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  11158. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11159. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  11160. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  11161. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  11162. // Google Mock - a framework for writing C++ mock classes.
  11163. //
  11164. // This file implements Matcher<const string&>, Matcher<string>, and
  11165. // utilities for defining matchers.
  11166. #include <string.h>
  11167. #include <iostream>
  11168. #include <sstream>
  11169. #include <string>
  11170. namespace testing {
  11171. namespace internal {
  11172. // Returns the description for a matcher defined using the MATCHER*()
  11173. // macro where the user-supplied description string is "", if
  11174. // 'negation' is false; otherwise returns the description of the
  11175. // negation of the matcher. 'param_values' contains a list of strings
  11176. // that are the print-out of the matcher's parameters.
  11177. GTEST_API_ std::string FormatMatcherDescription(bool negation,
  11178. const char* matcher_name,
  11179. const Strings& param_values) {
  11180. std::string result = ConvertIdentifierNameToWords(matcher_name);
  11181. if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values);
  11182. return negation ? "not (" + result + ")" : result;
  11183. }
  11184. // FindMaxBipartiteMatching and its helper class.
  11185. //
  11186. // Uses the well-known Ford-Fulkerson max flow method to find a maximum
  11187. // bipartite matching. Flow is considered to be from left to right.
  11188. // There is an implicit source node that is connected to all of the left
  11189. // nodes, and an implicit sink node that is connected to all of the
  11190. // right nodes. All edges have unit capacity.
  11191. //
  11192. // Neither the flow graph nor the residual flow graph are represented
  11193. // explicitly. Instead, they are implied by the information in 'graph' and
  11194. // a vector<int> called 'left_' whose elements are initialized to the
  11195. // value kUnused. This represents the initial state of the algorithm,
  11196. // where the flow graph is empty, and the residual flow graph has the
  11197. // following edges:
  11198. // - An edge from source to each left_ node
  11199. // - An edge from each right_ node to sink
  11200. // - An edge from each left_ node to each right_ node, if the
  11201. // corresponding edge exists in 'graph'.
  11202. //
  11203. // When the TryAugment() method adds a flow, it sets left_[l] = r for some
  11204. // nodes l and r. This induces the following changes:
  11205. // - The edges (source, l), (l, r), and (r, sink) are added to the
  11206. // flow graph.
  11207. // - The same three edges are removed from the residual flow graph.
  11208. // - The reverse edges (l, source), (r, l), and (sink, r) are added
  11209. // to the residual flow graph, which is a directional graph
  11210. // representing unused flow capacity.
  11211. //
  11212. // When the method augments a flow (moving left_[l] from some r1 to some
  11213. // other r2), this can be thought of as "undoing" the above steps with
  11214. // respect to r1 and "redoing" them with respect to r2.
  11215. //
  11216. // It bears repeating that the flow graph and residual flow graph are
  11217. // never represented explicitly, but can be derived by looking at the
  11218. // information in 'graph' and in left_.
  11219. //
  11220. // As an optimization, there is a second vector<int> called right_ which
  11221. // does not provide any new information. Instead, it enables more
  11222. // efficient queries about edges entering or leaving the right-side nodes
  11223. // of the flow or residual flow graphs. The following invariants are
  11224. // maintained:
  11225. //
  11226. // left[l] == kUnused or right[left[l]] == l
  11227. // right[r] == kUnused or left[right[r]] == r
  11228. //
  11229. // . [ source ] .
  11230. // . ||| .
  11231. // . ||| .
  11232. // . ||\--> left[0]=1 ---\ right[0]=-1 ----\ .
  11233. // . || | | .
  11234. // . |\---> left[1]=-1 \--> right[1]=0 ---\| .
  11235. // . | || .
  11236. // . \----> left[2]=2 ------> right[2]=2 --\|| .
  11237. // . ||| .
  11238. // . elements matchers vvv .
  11239. // . [ sink ] .
  11240. //
  11241. // See Also:
  11242. // [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
  11243. // "Introduction to Algorithms (Second ed.)", pp. 651-664.
  11244. // [2] "Ford-Fulkerson algorithm", Wikipedia,
  11245. // 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
  11246. class MaxBipartiteMatchState {
  11247. public:
  11248. explicit MaxBipartiteMatchState(const MatchMatrix& graph)
  11249. : graph_(&graph),
  11250. left_(graph_->LhsSize(), kUnused),
  11251. right_(graph_->RhsSize(), kUnused) {}
  11252. // Returns the edges of a maximal match, each in the form {left, right}.
  11253. ElementMatcherPairs Compute() {
  11254. // 'seen' is used for path finding { 0: unseen, 1: seen }.
  11255. ::std::vector<char> seen;
  11256. // Searches the residual flow graph for a path from each left node to
  11257. // the sink in the residual flow graph, and if one is found, add flow
  11258. // to the graph. It's okay to search through the left nodes once. The
  11259. // edge from the implicit source node to each previously-visited left
  11260. // node will have flow if that left node has any path to the sink
  11261. // whatsoever. Subsequent augmentations can only add flow to the
  11262. // network, and cannot take away that previous flow unit from the source.
  11263. // Since the source-to-left edge can only carry one flow unit (or,
  11264. // each element can be matched to only one matcher), there is no need
  11265. // to visit the left nodes more than once looking for augmented paths.
  11266. // The flow is known to be possible or impossible by looking at the
  11267. // node once.
  11268. for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
  11269. // Reset the path-marking vector and try to find a path from
  11270. // source to sink starting at the left_[ilhs] node.
  11271. GTEST_CHECK_(left_[ilhs] == kUnused)
  11272. << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
  11273. // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
  11274. seen.assign(graph_->RhsSize(), 0);
  11275. TryAugment(ilhs, &seen);
  11276. }
  11277. ElementMatcherPairs result;
  11278. for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
  11279. size_t irhs = left_[ilhs];
  11280. if (irhs == kUnused) continue;
  11281. result.push_back(ElementMatcherPair(ilhs, irhs));
  11282. }
  11283. return result;
  11284. }
  11285. private:
  11286. static const size_t kUnused = static_cast<size_t>(-1);
  11287. // Perform a depth-first search from left node ilhs to the sink. If a
  11288. // path is found, flow is added to the network by linking the left and
  11289. // right vector elements corresponding each segment of the path.
  11290. // Returns true if a path to sink was found, which means that a unit of
  11291. // flow was added to the network. The 'seen' vector elements correspond
  11292. // to right nodes and are marked to eliminate cycles from the search.
  11293. //
  11294. // Left nodes will only be explored at most once because they
  11295. // are accessible from at most one right node in the residual flow
  11296. // graph.
  11297. //
  11298. // Note that left_[ilhs] is the only element of left_ that TryAugment will
  11299. // potentially transition from kUnused to another value. Any other
  11300. // left_ element holding kUnused before TryAugment will be holding it
  11301. // when TryAugment returns.
  11302. //
  11303. bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
  11304. for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
  11305. if ((*seen)[irhs]) continue;
  11306. if (!graph_->HasEdge(ilhs, irhs)) continue;
  11307. // There's an available edge from ilhs to irhs.
  11308. (*seen)[irhs] = 1;
  11309. // Next a search is performed to determine whether
  11310. // this edge is a dead end or leads to the sink.
  11311. //
  11312. // right_[irhs] == kUnused means that there is residual flow from
  11313. // right node irhs to the sink, so we can use that to finish this
  11314. // flow path and return success.
  11315. //
  11316. // Otherwise there is residual flow to some ilhs. We push flow
  11317. // along that path and call ourselves recursively to see if this
  11318. // ultimately leads to sink.
  11319. if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
  11320. // Add flow from left_[ilhs] to right_[irhs].
  11321. left_[ilhs] = irhs;
  11322. right_[irhs] = ilhs;
  11323. return true;
  11324. }
  11325. }
  11326. return false;
  11327. }
  11328. const MatchMatrix* graph_; // not owned
  11329. // Each element of the left_ vector represents a left hand side node
  11330. // (i.e. an element) and each element of right_ is a right hand side
  11331. // node (i.e. a matcher). The values in the left_ vector indicate
  11332. // outflow from that node to a node on the right_ side. The values
  11333. // in the right_ indicate inflow, and specify which left_ node is
  11334. // feeding that right_ node, if any. For example, left_[3] == 1 means
  11335. // there's a flow from element #3 to matcher #1. Such a flow would also
  11336. // be redundantly represented in the right_ vector as right_[1] == 3.
  11337. // Elements of left_ and right_ are either kUnused or mutually
  11338. // referent. Mutually referent means that left_[right_[i]] = i and
  11339. // right_[left_[i]] = i.
  11340. ::std::vector<size_t> left_;
  11341. ::std::vector<size_t> right_;
  11342. };
  11343. const size_t MaxBipartiteMatchState::kUnused;
  11344. GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) {
  11345. return MaxBipartiteMatchState(g).Compute();
  11346. }
  11347. static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
  11348. ::std::ostream* stream) {
  11349. typedef ElementMatcherPairs::const_iterator Iter;
  11350. ::std::ostream& os = *stream;
  11351. os << "{";
  11352. const char* sep = "";
  11353. for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
  11354. os << sep << "\n ("
  11355. << "element #" << it->first << ", "
  11356. << "matcher #" << it->second << ")";
  11357. sep = ",";
  11358. }
  11359. os << "\n}";
  11360. }
  11361. bool MatchMatrix::NextGraph() {
  11362. for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
  11363. for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
  11364. char& b = matched_[SpaceIndex(ilhs, irhs)];
  11365. if (!b) {
  11366. b = 1;
  11367. return true;
  11368. }
  11369. b = 0;
  11370. }
  11371. }
  11372. return false;
  11373. }
  11374. void MatchMatrix::Randomize() {
  11375. for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
  11376. for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
  11377. char& b = matched_[SpaceIndex(ilhs, irhs)];
  11378. b = static_cast<char>(rand() & 1); // NOLINT
  11379. }
  11380. }
  11381. }
  11382. std::string MatchMatrix::DebugString() const {
  11383. ::std::stringstream ss;
  11384. const char* sep = "";
  11385. for (size_t i = 0; i < LhsSize(); ++i) {
  11386. ss << sep;
  11387. for (size_t j = 0; j < RhsSize(); ++j) {
  11388. ss << HasEdge(i, j);
  11389. }
  11390. sep = ";";
  11391. }
  11392. return ss.str();
  11393. }
  11394. void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
  11395. ::std::ostream* os) const {
  11396. switch (match_flags()) {
  11397. case UnorderedMatcherRequire::ExactMatch:
  11398. if (matcher_describers_.empty()) {
  11399. *os << "is empty";
  11400. return;
  11401. }
  11402. if (matcher_describers_.size() == 1) {
  11403. *os << "has " << Elements(1) << " and that element ";
  11404. matcher_describers_[0]->DescribeTo(os);
  11405. return;
  11406. }
  11407. *os << "has " << Elements(matcher_describers_.size())
  11408. << " and there exists some permutation of elements such that:\n";
  11409. break;
  11410. case UnorderedMatcherRequire::Superset:
  11411. *os << "a surjection from elements to requirements exists such that:\n";
  11412. break;
  11413. case UnorderedMatcherRequire::Subset:
  11414. *os << "an injection from elements to requirements exists such that:\n";
  11415. break;
  11416. }
  11417. const char* sep = "";
  11418. for (size_t i = 0; i != matcher_describers_.size(); ++i) {
  11419. *os << sep;
  11420. if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
  11421. *os << " - element #" << i << " ";
  11422. } else {
  11423. *os << " - an element ";
  11424. }
  11425. matcher_describers_[i]->DescribeTo(os);
  11426. if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
  11427. sep = ", and\n";
  11428. } else {
  11429. sep = "\n";
  11430. }
  11431. }
  11432. }
  11433. void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
  11434. ::std::ostream* os) const {
  11435. switch (match_flags()) {
  11436. case UnorderedMatcherRequire::ExactMatch:
  11437. if (matcher_describers_.empty()) {
  11438. *os << "isn't empty";
  11439. return;
  11440. }
  11441. if (matcher_describers_.size() == 1) {
  11442. *os << "doesn't have " << Elements(1) << ", or has " << Elements(1)
  11443. << " that ";
  11444. matcher_describers_[0]->DescribeNegationTo(os);
  11445. return;
  11446. }
  11447. *os << "doesn't have " << Elements(matcher_describers_.size())
  11448. << ", or there exists no permutation of elements such that:\n";
  11449. break;
  11450. case UnorderedMatcherRequire::Superset:
  11451. *os << "no surjection from elements to requirements exists such that:\n";
  11452. break;
  11453. case UnorderedMatcherRequire::Subset:
  11454. *os << "no injection from elements to requirements exists such that:\n";
  11455. break;
  11456. }
  11457. const char* sep = "";
  11458. for (size_t i = 0; i != matcher_describers_.size(); ++i) {
  11459. *os << sep;
  11460. if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
  11461. *os << " - element #" << i << " ";
  11462. } else {
  11463. *os << " - an element ";
  11464. }
  11465. matcher_describers_[i]->DescribeTo(os);
  11466. if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
  11467. sep = ", and\n";
  11468. } else {
  11469. sep = "\n";
  11470. }
  11471. }
  11472. }
  11473. // Checks that all matchers match at least one element, and that all
  11474. // elements match at least one matcher. This enables faster matching
  11475. // and better error reporting.
  11476. // Returns false, writing an explanation to 'listener', if and only
  11477. // if the success criteria are not met.
  11478. bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix(
  11479. const ::std::vector<std::string>& element_printouts,
  11480. const MatchMatrix& matrix, MatchResultListener* listener) const {
  11481. bool result = true;
  11482. ::std::vector<char> element_matched(matrix.LhsSize(), 0);
  11483. ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
  11484. for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
  11485. for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
  11486. char matched = matrix.HasEdge(ilhs, irhs);
  11487. element_matched[ilhs] |= matched;
  11488. matcher_matched[irhs] |= matched;
  11489. }
  11490. }
  11491. if (match_flags() & UnorderedMatcherRequire::Superset) {
  11492. const char* sep =
  11493. "where the following matchers don't match any elements:\n";
  11494. for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
  11495. if (matcher_matched[mi]) continue;
  11496. result = false;
  11497. if (listener->IsInterested()) {
  11498. *listener << sep << "matcher #" << mi << ": ";
  11499. matcher_describers_[mi]->DescribeTo(listener->stream());
  11500. sep = ",\n";
  11501. }
  11502. }
  11503. }
  11504. if (match_flags() & UnorderedMatcherRequire::Subset) {
  11505. const char* sep =
  11506. "where the following elements don't match any matchers:\n";
  11507. const char* outer_sep = "";
  11508. if (!result) {
  11509. outer_sep = "\nand ";
  11510. }
  11511. for (size_t ei = 0; ei < element_matched.size(); ++ei) {
  11512. if (element_matched[ei]) continue;
  11513. result = false;
  11514. if (listener->IsInterested()) {
  11515. *listener << outer_sep << sep << "element #" << ei << ": "
  11516. << element_printouts[ei];
  11517. sep = ",\n";
  11518. outer_sep = "";
  11519. }
  11520. }
  11521. }
  11522. return result;
  11523. }
  11524. bool UnorderedElementsAreMatcherImplBase::FindPairing(
  11525. const MatchMatrix& matrix, MatchResultListener* listener) const {
  11526. ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
  11527. size_t max_flow = matches.size();
  11528. if ((match_flags() & UnorderedMatcherRequire::Superset) &&
  11529. max_flow < matrix.RhsSize()) {
  11530. if (listener->IsInterested()) {
  11531. *listener << "where no permutation of the elements can satisfy all "
  11532. "matchers, and the closest match is "
  11533. << max_flow << " of " << matrix.RhsSize()
  11534. << " matchers with the pairings:\n";
  11535. LogElementMatcherPairVec(matches, listener->stream());
  11536. }
  11537. return false;
  11538. }
  11539. if ((match_flags() & UnorderedMatcherRequire::Subset) &&
  11540. max_flow < matrix.LhsSize()) {
  11541. if (listener->IsInterested()) {
  11542. *listener
  11543. << "where not all elements can be matched, and the closest match is "
  11544. << max_flow << " of " << matrix.RhsSize()
  11545. << " matchers with the pairings:\n";
  11546. LogElementMatcherPairVec(matches, listener->stream());
  11547. }
  11548. return false;
  11549. }
  11550. if (matches.size() > 1) {
  11551. if (listener->IsInterested()) {
  11552. const char* sep = "where:\n";
  11553. for (size_t mi = 0; mi < matches.size(); ++mi) {
  11554. *listener << sep << " - element #" << matches[mi].first
  11555. << " is matched by matcher #" << matches[mi].second;
  11556. sep = ",\n";
  11557. }
  11558. }
  11559. }
  11560. return true;
  11561. }
  11562. } // namespace internal
  11563. } // namespace testing
  11564. // Copyright 2007, Google Inc.
  11565. // All rights reserved.
  11566. //
  11567. // Redistribution and use in source and binary forms, with or without
  11568. // modification, are permitted provided that the following conditions are
  11569. // met:
  11570. //
  11571. // * Redistributions of source code must retain the above copyright
  11572. // notice, this list of conditions and the following disclaimer.
  11573. // * Redistributions in binary form must reproduce the above
  11574. // copyright notice, this list of conditions and the following disclaimer
  11575. // in the documentation and/or other materials provided with the
  11576. // distribution.
  11577. // * Neither the name of Google Inc. nor the names of its
  11578. // contributors may be used to endorse or promote products derived from
  11579. // this software without specific prior written permission.
  11580. //
  11581. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  11582. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  11583. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  11584. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  11585. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  11586. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  11587. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  11588. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11589. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  11590. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  11591. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  11592. // Google Mock - a framework for writing C++ mock classes.
  11593. //
  11594. // This file implements the spec builder syntax (ON_CALL and
  11595. // EXPECT_CALL).
  11596. #include <stdlib.h>
  11597. #include <iostream> // NOLINT
  11598. #include <map>
  11599. #include <memory>
  11600. #include <set>
  11601. #include <string>
  11602. #include <vector>
  11603. #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
  11604. # include <unistd.h> // NOLINT
  11605. #endif
  11606. // Silence C4800 (C4800: 'int *const ': forcing value
  11607. // to bool 'true' or 'false') for MSVC 15
  11608. #ifdef _MSC_VER
  11609. #if _MSC_VER == 1900
  11610. # pragma warning(push)
  11611. # pragma warning(disable:4800)
  11612. #endif
  11613. #endif
  11614. namespace testing {
  11615. namespace internal {
  11616. // Protects the mock object registry (in class Mock), all function
  11617. // mockers, and all expectations.
  11618. GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
  11619. // Logs a message including file and line number information.
  11620. GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
  11621. const char* file, int line,
  11622. const std::string& message) {
  11623. ::std::ostringstream s;
  11624. s << internal::FormatFileLocation(file, line) << " " << message
  11625. << ::std::endl;
  11626. Log(severity, s.str(), 0);
  11627. }
  11628. // Constructs an ExpectationBase object.
  11629. ExpectationBase::ExpectationBase(const char* a_file, int a_line,
  11630. const std::string& a_source_text)
  11631. : file_(a_file),
  11632. line_(a_line),
  11633. source_text_(a_source_text),
  11634. cardinality_specified_(false),
  11635. cardinality_(Exactly(1)),
  11636. call_count_(0),
  11637. retired_(false),
  11638. extra_matcher_specified_(false),
  11639. repeated_action_specified_(false),
  11640. retires_on_saturation_(false),
  11641. last_clause_(kNone),
  11642. action_count_checked_(false) {}
  11643. // Destructs an ExpectationBase object.
  11644. ExpectationBase::~ExpectationBase() {}
  11645. // Explicitly specifies the cardinality of this expectation. Used by
  11646. // the subclasses to implement the .Times() clause.
  11647. void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
  11648. cardinality_specified_ = true;
  11649. cardinality_ = a_cardinality;
  11650. }
  11651. // Retires all pre-requisites of this expectation.
  11652. void ExpectationBase::RetireAllPreRequisites()
  11653. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  11654. if (is_retired()) {
  11655. // We can take this short-cut as we never retire an expectation
  11656. // until we have retired all its pre-requisites.
  11657. return;
  11658. }
  11659. ::std::vector<ExpectationBase*> expectations(1, this);
  11660. while (!expectations.empty()) {
  11661. ExpectationBase* exp = expectations.back();
  11662. expectations.pop_back();
  11663. for (ExpectationSet::const_iterator it =
  11664. exp->immediate_prerequisites_.begin();
  11665. it != exp->immediate_prerequisites_.end(); ++it) {
  11666. ExpectationBase* next = it->expectation_base().get();
  11667. if (!next->is_retired()) {
  11668. next->Retire();
  11669. expectations.push_back(next);
  11670. }
  11671. }
  11672. }
  11673. }
  11674. // Returns true if and only if all pre-requisites of this expectation
  11675. // have been satisfied.
  11676. bool ExpectationBase::AllPrerequisitesAreSatisfied() const
  11677. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  11678. g_gmock_mutex.AssertHeld();
  11679. ::std::vector<const ExpectationBase*> expectations(1, this);
  11680. while (!expectations.empty()) {
  11681. const ExpectationBase* exp = expectations.back();
  11682. expectations.pop_back();
  11683. for (ExpectationSet::const_iterator it =
  11684. exp->immediate_prerequisites_.begin();
  11685. it != exp->immediate_prerequisites_.end(); ++it) {
  11686. const ExpectationBase* next = it->expectation_base().get();
  11687. if (!next->IsSatisfied()) return false;
  11688. expectations.push_back(next);
  11689. }
  11690. }
  11691. return true;
  11692. }
  11693. // Adds unsatisfied pre-requisites of this expectation to 'result'.
  11694. void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
  11695. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  11696. g_gmock_mutex.AssertHeld();
  11697. ::std::vector<const ExpectationBase*> expectations(1, this);
  11698. while (!expectations.empty()) {
  11699. const ExpectationBase* exp = expectations.back();
  11700. expectations.pop_back();
  11701. for (ExpectationSet::const_iterator it =
  11702. exp->immediate_prerequisites_.begin();
  11703. it != exp->immediate_prerequisites_.end(); ++it) {
  11704. const ExpectationBase* next = it->expectation_base().get();
  11705. if (next->IsSatisfied()) {
  11706. // If *it is satisfied and has a call count of 0, some of its
  11707. // pre-requisites may not be satisfied yet.
  11708. if (next->call_count_ == 0) {
  11709. expectations.push_back(next);
  11710. }
  11711. } else {
  11712. // Now that we know next is unsatisfied, we are not so interested
  11713. // in whether its pre-requisites are satisfied. Therefore we
  11714. // don't iterate into it here.
  11715. *result += *it;
  11716. }
  11717. }
  11718. }
  11719. }
  11720. // Describes how many times a function call matching this
  11721. // expectation has occurred.
  11722. void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
  11723. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  11724. g_gmock_mutex.AssertHeld();
  11725. // Describes how many times the function is expected to be called.
  11726. *os << " Expected: to be ";
  11727. cardinality().DescribeTo(os);
  11728. *os << "\n Actual: ";
  11729. Cardinality::DescribeActualCallCountTo(call_count(), os);
  11730. // Describes the state of the expectation (e.g. is it satisfied?
  11731. // is it active?).
  11732. *os << " - " << (IsOverSaturated() ? "over-saturated" :
  11733. IsSaturated() ? "saturated" :
  11734. IsSatisfied() ? "satisfied" : "unsatisfied")
  11735. << " and "
  11736. << (is_retired() ? "retired" : "active");
  11737. }
  11738. // Checks the action count (i.e. the number of WillOnce() and
  11739. // WillRepeatedly() clauses) against the cardinality if this hasn't
  11740. // been done before. Prints a warning if there are too many or too
  11741. // few actions.
  11742. void ExpectationBase::CheckActionCountIfNotDone() const
  11743. GTEST_LOCK_EXCLUDED_(mutex_) {
  11744. bool should_check = false;
  11745. {
  11746. MutexLock l(&mutex_);
  11747. if (!action_count_checked_) {
  11748. action_count_checked_ = true;
  11749. should_check = true;
  11750. }
  11751. }
  11752. if (should_check) {
  11753. if (!cardinality_specified_) {
  11754. // The cardinality was inferred - no need to check the action
  11755. // count against it.
  11756. return;
  11757. }
  11758. // The cardinality was explicitly specified.
  11759. const int action_count = static_cast<int>(untyped_actions_.size());
  11760. const int upper_bound = cardinality().ConservativeUpperBound();
  11761. const int lower_bound = cardinality().ConservativeLowerBound();
  11762. bool too_many; // True if there are too many actions, or false
  11763. // if there are too few.
  11764. if (action_count > upper_bound ||
  11765. (action_count == upper_bound && repeated_action_specified_)) {
  11766. too_many = true;
  11767. } else if (0 < action_count && action_count < lower_bound &&
  11768. !repeated_action_specified_) {
  11769. too_many = false;
  11770. } else {
  11771. return;
  11772. }
  11773. ::std::stringstream ss;
  11774. DescribeLocationTo(&ss);
  11775. ss << "Too " << (too_many ? "many" : "few")
  11776. << " actions specified in " << source_text() << "...\n"
  11777. << "Expected to be ";
  11778. cardinality().DescribeTo(&ss);
  11779. ss << ", but has " << (too_many ? "" : "only ")
  11780. << action_count << " WillOnce()"
  11781. << (action_count == 1 ? "" : "s");
  11782. if (repeated_action_specified_) {
  11783. ss << " and a WillRepeatedly()";
  11784. }
  11785. ss << ".";
  11786. Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".
  11787. }
  11788. }
  11789. // Implements the .Times() clause.
  11790. void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
  11791. if (last_clause_ == kTimes) {
  11792. ExpectSpecProperty(false,
  11793. ".Times() cannot appear "
  11794. "more than once in an EXPECT_CALL().");
  11795. } else {
  11796. ExpectSpecProperty(last_clause_ < kTimes,
  11797. ".Times() cannot appear after "
  11798. ".InSequence(), .WillOnce(), .WillRepeatedly(), "
  11799. "or .RetiresOnSaturation().");
  11800. }
  11801. last_clause_ = kTimes;
  11802. SpecifyCardinality(a_cardinality);
  11803. }
  11804. // Points to the implicit sequence introduced by a living InSequence
  11805. // object (if any) in the current thread or NULL.
  11806. GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
  11807. // Reports an uninteresting call (whose description is in msg) in the
  11808. // manner specified by 'reaction'.
  11809. void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
  11810. // Include a stack trace only if --gmock_verbose=info is specified.
  11811. const int stack_frames_to_skip =
  11812. GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
  11813. switch (reaction) {
  11814. case kAllow:
  11815. Log(kInfo, msg, stack_frames_to_skip);
  11816. break;
  11817. case kWarn:
  11818. Log(kWarning,
  11819. msg +
  11820. "\nNOTE: You can safely ignore the above warning unless this "
  11821. "call should not happen. Do not suppress it by blindly adding "
  11822. "an EXPECT_CALL() if you don't mean to enforce the call. "
  11823. "See "
  11824. "https://github.com/google/googletest/blob/master/docs/"
  11825. "gmock_cook_book.md#"
  11826. "knowing-when-to-expect for details.\n",
  11827. stack_frames_to_skip);
  11828. break;
  11829. default: // FAIL
  11830. Expect(false, nullptr, -1, msg);
  11831. }
  11832. }
  11833. UntypedFunctionMockerBase::UntypedFunctionMockerBase()
  11834. : mock_obj_(nullptr), name_("") {}
  11835. UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
  11836. // Sets the mock object this mock method belongs to, and registers
  11837. // this information in the global mock registry. Will be called
  11838. // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
  11839. // method.
  11840. void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
  11841. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  11842. {
  11843. MutexLock l(&g_gmock_mutex);
  11844. mock_obj_ = mock_obj;
  11845. }
  11846. Mock::Register(mock_obj, this);
  11847. }
  11848. // Sets the mock object this mock method belongs to, and sets the name
  11849. // of the mock function. Will be called upon each invocation of this
  11850. // mock function.
  11851. void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
  11852. const char* name)
  11853. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  11854. // We protect name_ under g_gmock_mutex in case this mock function
  11855. // is called from two threads concurrently.
  11856. MutexLock l(&g_gmock_mutex);
  11857. mock_obj_ = mock_obj;
  11858. name_ = name;
  11859. }
  11860. // Returns the name of the function being mocked. Must be called
  11861. // after RegisterOwner() or SetOwnerAndName() has been called.
  11862. const void* UntypedFunctionMockerBase::MockObject() const
  11863. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  11864. const void* mock_obj;
  11865. {
  11866. // We protect mock_obj_ under g_gmock_mutex in case this mock
  11867. // function is called from two threads concurrently.
  11868. MutexLock l(&g_gmock_mutex);
  11869. Assert(mock_obj_ != nullptr, __FILE__, __LINE__,
  11870. "MockObject() must not be called before RegisterOwner() or "
  11871. "SetOwnerAndName() has been called.");
  11872. mock_obj = mock_obj_;
  11873. }
  11874. return mock_obj;
  11875. }
  11876. // Returns the name of this mock method. Must be called after
  11877. // SetOwnerAndName() has been called.
  11878. const char* UntypedFunctionMockerBase::Name() const
  11879. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  11880. const char* name;
  11881. {
  11882. // We protect name_ under g_gmock_mutex in case this mock
  11883. // function is called from two threads concurrently.
  11884. MutexLock l(&g_gmock_mutex);
  11885. Assert(name_ != nullptr, __FILE__, __LINE__,
  11886. "Name() must not be called before SetOwnerAndName() has "
  11887. "been called.");
  11888. name = name_;
  11889. }
  11890. return name;
  11891. }
  11892. // Calculates the result of invoking this mock function with the given
  11893. // arguments, prints it, and returns it. The caller is responsible
  11894. // for deleting the result.
  11895. UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
  11896. void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  11897. // See the definition of untyped_expectations_ for why access to it
  11898. // is unprotected here.
  11899. if (untyped_expectations_.size() == 0) {
  11900. // No expectation is set on this mock method - we have an
  11901. // uninteresting call.
  11902. // We must get Google Mock's reaction on uninteresting calls
  11903. // made on this mock object BEFORE performing the action,
  11904. // because the action may DELETE the mock object and make the
  11905. // following expression meaningless.
  11906. const CallReaction reaction =
  11907. Mock::GetReactionOnUninterestingCalls(MockObject());
  11908. // True if and only if we need to print this call's arguments and return
  11909. // value. This definition must be kept in sync with
  11910. // the behavior of ReportUninterestingCall().
  11911. const bool need_to_report_uninteresting_call =
  11912. // If the user allows this uninteresting call, we print it
  11913. // only when they want informational messages.
  11914. reaction == kAllow ? LogIsVisible(kInfo) :
  11915. // If the user wants this to be a warning, we print
  11916. // it only when they want to see warnings.
  11917. reaction == kWarn
  11918. ? LogIsVisible(kWarning)
  11919. :
  11920. // Otherwise, the user wants this to be an error, and we
  11921. // should always print detailed information in the error.
  11922. true;
  11923. if (!need_to_report_uninteresting_call) {
  11924. // Perform the action without printing the call information.
  11925. return this->UntypedPerformDefaultAction(
  11926. untyped_args, "Function call: " + std::string(Name()));
  11927. }
  11928. // Warns about the uninteresting call.
  11929. ::std::stringstream ss;
  11930. this->UntypedDescribeUninterestingCall(untyped_args, &ss);
  11931. // Calculates the function result.
  11932. UntypedActionResultHolderBase* const result =
  11933. this->UntypedPerformDefaultAction(untyped_args, ss.str());
  11934. // Prints the function result.
  11935. if (result != nullptr) result->PrintAsActionResult(&ss);
  11936. ReportUninterestingCall(reaction, ss.str());
  11937. return result;
  11938. }
  11939. bool is_excessive = false;
  11940. ::std::stringstream ss;
  11941. ::std::stringstream why;
  11942. ::std::stringstream loc;
  11943. const void* untyped_action = nullptr;
  11944. // The UntypedFindMatchingExpectation() function acquires and
  11945. // releases g_gmock_mutex.
  11946. const ExpectationBase* const untyped_expectation =
  11947. this->UntypedFindMatchingExpectation(untyped_args, &untyped_action,
  11948. &is_excessive, &ss, &why);
  11949. const bool found = untyped_expectation != nullptr;
  11950. // True if and only if we need to print the call's arguments
  11951. // and return value.
  11952. // This definition must be kept in sync with the uses of Expect()
  11953. // and Log() in this function.
  11954. const bool need_to_report_call =
  11955. !found || is_excessive || LogIsVisible(kInfo);
  11956. if (!need_to_report_call) {
  11957. // Perform the action without printing the call information.
  11958. return untyped_action == nullptr
  11959. ? this->UntypedPerformDefaultAction(untyped_args, "")
  11960. : this->UntypedPerformAction(untyped_action, untyped_args);
  11961. }
  11962. ss << " Function call: " << Name();
  11963. this->UntypedPrintArgs(untyped_args, &ss);
  11964. // In case the action deletes a piece of the expectation, we
  11965. // generate the message beforehand.
  11966. if (found && !is_excessive) {
  11967. untyped_expectation->DescribeLocationTo(&loc);
  11968. }
  11969. UntypedActionResultHolderBase* result = nullptr;
  11970. auto perform_action = [&] {
  11971. return untyped_action == nullptr
  11972. ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
  11973. : this->UntypedPerformAction(untyped_action, untyped_args);
  11974. };
  11975. auto handle_failures = [&] {
  11976. ss << "\n" << why.str();
  11977. if (!found) {
  11978. // No expectation matches this call - reports a failure.
  11979. Expect(false, nullptr, -1, ss.str());
  11980. } else if (is_excessive) {
  11981. // We had an upper-bound violation and the failure message is in ss.
  11982. Expect(false, untyped_expectation->file(), untyped_expectation->line(),
  11983. ss.str());
  11984. } else {
  11985. // We had an expected call and the matching expectation is
  11986. // described in ss.
  11987. Log(kInfo, loc.str() + ss.str(), 2);
  11988. }
  11989. };
  11990. #if GTEST_HAS_EXCEPTIONS
  11991. try {
  11992. result = perform_action();
  11993. } catch (...) {
  11994. handle_failures();
  11995. throw;
  11996. }
  11997. #else
  11998. result = perform_action();
  11999. #endif
  12000. if (result != nullptr) result->PrintAsActionResult(&ss);
  12001. handle_failures();
  12002. return result;
  12003. }
  12004. // Returns an Expectation object that references and co-owns exp,
  12005. // which must be an expectation on this mock function.
  12006. Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
  12007. // See the definition of untyped_expectations_ for why access to it
  12008. // is unprotected here.
  12009. for (UntypedExpectations::const_iterator it =
  12010. untyped_expectations_.begin();
  12011. it != untyped_expectations_.end(); ++it) {
  12012. if (it->get() == exp) {
  12013. return Expectation(*it);
  12014. }
  12015. }
  12016. Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
  12017. return Expectation();
  12018. // The above statement is just to make the code compile, and will
  12019. // never be executed.
  12020. }
  12021. // Verifies that all expectations on this mock function have been
  12022. // satisfied. Reports one or more Google Test non-fatal failures
  12023. // and returns false if not.
  12024. bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
  12025. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  12026. g_gmock_mutex.AssertHeld();
  12027. bool expectations_met = true;
  12028. for (UntypedExpectations::const_iterator it =
  12029. untyped_expectations_.begin();
  12030. it != untyped_expectations_.end(); ++it) {
  12031. ExpectationBase* const untyped_expectation = it->get();
  12032. if (untyped_expectation->IsOverSaturated()) {
  12033. // There was an upper-bound violation. Since the error was
  12034. // already reported when it occurred, there is no need to do
  12035. // anything here.
  12036. expectations_met = false;
  12037. } else if (!untyped_expectation->IsSatisfied()) {
  12038. expectations_met = false;
  12039. ::std::stringstream ss;
  12040. ss << "Actual function call count doesn't match "
  12041. << untyped_expectation->source_text() << "...\n";
  12042. // No need to show the source file location of the expectation
  12043. // in the description, as the Expect() call that follows already
  12044. // takes care of it.
  12045. untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
  12046. untyped_expectation->DescribeCallCountTo(&ss);
  12047. Expect(false, untyped_expectation->file(),
  12048. untyped_expectation->line(), ss.str());
  12049. }
  12050. }
  12051. // Deleting our expectations may trigger other mock objects to be deleted, for
  12052. // example if an action contains a reference counted smart pointer to that
  12053. // mock object, and that is the last reference. So if we delete our
  12054. // expectations within the context of the global mutex we may deadlock when
  12055. // this method is called again. Instead, make a copy of the set of
  12056. // expectations to delete, clear our set within the mutex, and then clear the
  12057. // copied set outside of it.
  12058. UntypedExpectations expectations_to_delete;
  12059. untyped_expectations_.swap(expectations_to_delete);
  12060. g_gmock_mutex.Unlock();
  12061. expectations_to_delete.clear();
  12062. g_gmock_mutex.Lock();
  12063. return expectations_met;
  12064. }
  12065. CallReaction intToCallReaction(int mock_behavior) {
  12066. if (mock_behavior >= kAllow && mock_behavior <= kFail) {
  12067. return static_cast<internal::CallReaction>(mock_behavior);
  12068. }
  12069. return kWarn;
  12070. }
  12071. } // namespace internal
  12072. // Class Mock.
  12073. namespace {
  12074. typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
  12075. // The current state of a mock object. Such information is needed for
  12076. // detecting leaked mock objects and explicitly verifying a mock's
  12077. // expectations.
  12078. struct MockObjectState {
  12079. MockObjectState()
  12080. : first_used_file(nullptr), first_used_line(-1), leakable(false) {}
  12081. // Where in the source file an ON_CALL or EXPECT_CALL is first
  12082. // invoked on this mock object.
  12083. const char* first_used_file;
  12084. int first_used_line;
  12085. ::std::string first_used_test_suite;
  12086. ::std::string first_used_test;
  12087. bool leakable; // true if and only if it's OK to leak the object.
  12088. FunctionMockers function_mockers; // All registered methods of the object.
  12089. };
  12090. // A global registry holding the state of all mock objects that are
  12091. // alive. A mock object is added to this registry the first time
  12092. // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
  12093. // is removed from the registry in the mock object's destructor.
  12094. class MockObjectRegistry {
  12095. public:
  12096. // Maps a mock object (identified by its address) to its state.
  12097. typedef std::map<const void*, MockObjectState> StateMap;
  12098. // This destructor will be called when a program exits, after all
  12099. // tests in it have been run. By then, there should be no mock
  12100. // object alive. Therefore we report any living object as test
  12101. // failure, unless the user explicitly asked us to ignore it.
  12102. ~MockObjectRegistry() {
  12103. if (!GMOCK_FLAG(catch_leaked_mocks))
  12104. return;
  12105. int leaked_count = 0;
  12106. for (StateMap::const_iterator it = states_.begin(); it != states_.end();
  12107. ++it) {
  12108. if (it->second.leakable) // The user said it's fine to leak this object.
  12109. continue;
  12110. // FIXME: Print the type of the leaked object.
  12111. // This can help the user identify the leaked object.
  12112. std::cout << "\n";
  12113. const MockObjectState& state = it->second;
  12114. std::cout << internal::FormatFileLocation(state.first_used_file,
  12115. state.first_used_line);
  12116. std::cout << " ERROR: this mock object";
  12117. if (state.first_used_test != "") {
  12118. std::cout << " (used in test " << state.first_used_test_suite << "."
  12119. << state.first_used_test << ")";
  12120. }
  12121. std::cout << " should be deleted but never is. Its address is @"
  12122. << it->first << ".";
  12123. leaked_count++;
  12124. }
  12125. if (leaked_count > 0) {
  12126. std::cout << "\nERROR: " << leaked_count << " leaked mock "
  12127. << (leaked_count == 1 ? "object" : "objects")
  12128. << " found at program exit. Expectations on a mock object are "
  12129. "verified when the object is destructed. Leaking a mock "
  12130. "means that its expectations aren't verified, which is "
  12131. "usually a test bug. If you really intend to leak a mock, "
  12132. "you can suppress this error using "
  12133. "testing::Mock::AllowLeak(mock_object), or you may use a "
  12134. "fake or stub instead of a mock.\n";
  12135. std::cout.flush();
  12136. ::std::cerr.flush();
  12137. // RUN_ALL_TESTS() has already returned when this destructor is
  12138. // called. Therefore we cannot use the normal Google Test
  12139. // failure reporting mechanism.
  12140. _exit(1); // We cannot call exit() as it is not reentrant and
  12141. // may already have been called.
  12142. }
  12143. }
  12144. StateMap& states() { return states_; }
  12145. private:
  12146. StateMap states_;
  12147. };
  12148. // Protected by g_gmock_mutex.
  12149. MockObjectRegistry g_mock_object_registry;
  12150. // Maps a mock object to the reaction Google Mock should have when an
  12151. // uninteresting method is called. Protected by g_gmock_mutex.
  12152. std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
  12153. // Sets the reaction Google Mock should have when an uninteresting
  12154. // method of the given mock object is called.
  12155. void SetReactionOnUninterestingCalls(const void* mock_obj,
  12156. internal::CallReaction reaction)
  12157. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12158. internal::MutexLock l(&internal::g_gmock_mutex);
  12159. g_uninteresting_call_reaction[mock_obj] = reaction;
  12160. }
  12161. } // namespace
  12162. // Tells Google Mock to allow uninteresting calls on the given mock
  12163. // object.
  12164. void Mock::AllowUninterestingCalls(const void* mock_obj)
  12165. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12166. SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
  12167. }
  12168. // Tells Google Mock to warn the user about uninteresting calls on the
  12169. // given mock object.
  12170. void Mock::WarnUninterestingCalls(const void* mock_obj)
  12171. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12172. SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
  12173. }
  12174. // Tells Google Mock to fail uninteresting calls on the given mock
  12175. // object.
  12176. void Mock::FailUninterestingCalls(const void* mock_obj)
  12177. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12178. SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
  12179. }
  12180. // Tells Google Mock the given mock object is being destroyed and its
  12181. // entry in the call-reaction table should be removed.
  12182. void Mock::UnregisterCallReaction(const void* mock_obj)
  12183. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12184. internal::MutexLock l(&internal::g_gmock_mutex);
  12185. g_uninteresting_call_reaction.erase(mock_obj);
  12186. }
  12187. // Returns the reaction Google Mock will have on uninteresting calls
  12188. // made on the given mock object.
  12189. internal::CallReaction Mock::GetReactionOnUninterestingCalls(
  12190. const void* mock_obj)
  12191. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12192. internal::MutexLock l(&internal::g_gmock_mutex);
  12193. return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
  12194. internal::intToCallReaction(GMOCK_FLAG(default_mock_behavior)) :
  12195. g_uninteresting_call_reaction[mock_obj];
  12196. }
  12197. // Tells Google Mock to ignore mock_obj when checking for leaked mock
  12198. // objects.
  12199. void Mock::AllowLeak(const void* mock_obj)
  12200. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12201. internal::MutexLock l(&internal::g_gmock_mutex);
  12202. g_mock_object_registry.states()[mock_obj].leakable = true;
  12203. }
  12204. // Verifies and clears all expectations on the given mock object. If
  12205. // the expectations aren't satisfied, generates one or more Google
  12206. // Test non-fatal failures and returns false.
  12207. bool Mock::VerifyAndClearExpectations(void* mock_obj)
  12208. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12209. internal::MutexLock l(&internal::g_gmock_mutex);
  12210. return VerifyAndClearExpectationsLocked(mock_obj);
  12211. }
  12212. // Verifies all expectations on the given mock object and clears its
  12213. // default actions and expectations. Returns true if and only if the
  12214. // verification was successful.
  12215. bool Mock::VerifyAndClear(void* mock_obj)
  12216. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12217. internal::MutexLock l(&internal::g_gmock_mutex);
  12218. ClearDefaultActionsLocked(mock_obj);
  12219. return VerifyAndClearExpectationsLocked(mock_obj);
  12220. }
  12221. // Verifies and clears all expectations on the given mock object. If
  12222. // the expectations aren't satisfied, generates one or more Google
  12223. // Test non-fatal failures and returns false.
  12224. bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
  12225. GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
  12226. internal::g_gmock_mutex.AssertHeld();
  12227. if (g_mock_object_registry.states().count(mock_obj) == 0) {
  12228. // No EXPECT_CALL() was set on the given mock object.
  12229. return true;
  12230. }
  12231. // Verifies and clears the expectations on each mock method in the
  12232. // given mock object.
  12233. bool expectations_met = true;
  12234. FunctionMockers& mockers =
  12235. g_mock_object_registry.states()[mock_obj].function_mockers;
  12236. for (FunctionMockers::const_iterator it = mockers.begin();
  12237. it != mockers.end(); ++it) {
  12238. if (!(*it)->VerifyAndClearExpectationsLocked()) {
  12239. expectations_met = false;
  12240. }
  12241. }
  12242. // We don't clear the content of mockers, as they may still be
  12243. // needed by ClearDefaultActionsLocked().
  12244. return expectations_met;
  12245. }
  12246. bool Mock::IsNaggy(void* mock_obj)
  12247. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12248. return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;
  12249. }
  12250. bool Mock::IsNice(void* mock_obj)
  12251. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12252. return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;
  12253. }
  12254. bool Mock::IsStrict(void* mock_obj)
  12255. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12256. return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;
  12257. }
  12258. // Registers a mock object and a mock method it owns.
  12259. void Mock::Register(const void* mock_obj,
  12260. internal::UntypedFunctionMockerBase* mocker)
  12261. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12262. internal::MutexLock l(&internal::g_gmock_mutex);
  12263. g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
  12264. }
  12265. // Tells Google Mock where in the source code mock_obj is used in an
  12266. // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
  12267. // information helps the user identify which object it is.
  12268. void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
  12269. const char* file, int line)
  12270. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
  12271. internal::MutexLock l(&internal::g_gmock_mutex);
  12272. MockObjectState& state = g_mock_object_registry.states()[mock_obj];
  12273. if (state.first_used_file == nullptr) {
  12274. state.first_used_file = file;
  12275. state.first_used_line = line;
  12276. const TestInfo* const test_info =
  12277. UnitTest::GetInstance()->current_test_info();
  12278. if (test_info != nullptr) {
  12279. state.first_used_test_suite = test_info->test_suite_name();
  12280. state.first_used_test = test_info->name();
  12281. }
  12282. }
  12283. }
  12284. // Unregisters a mock method; removes the owning mock object from the
  12285. // registry when the last mock method associated with it has been
  12286. // unregistered. This is called only in the destructor of
  12287. // FunctionMockerBase.
  12288. void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
  12289. GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
  12290. internal::g_gmock_mutex.AssertHeld();
  12291. for (MockObjectRegistry::StateMap::iterator it =
  12292. g_mock_object_registry.states().begin();
  12293. it != g_mock_object_registry.states().end(); ++it) {
  12294. FunctionMockers& mockers = it->second.function_mockers;
  12295. if (mockers.erase(mocker) > 0) {
  12296. // mocker was in mockers and has been just removed.
  12297. if (mockers.empty()) {
  12298. g_mock_object_registry.states().erase(it);
  12299. }
  12300. return;
  12301. }
  12302. }
  12303. }
  12304. // Clears all ON_CALL()s set on the given mock object.
  12305. void Mock::ClearDefaultActionsLocked(void* mock_obj)
  12306. GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
  12307. internal::g_gmock_mutex.AssertHeld();
  12308. if (g_mock_object_registry.states().count(mock_obj) == 0) {
  12309. // No ON_CALL() was set on the given mock object.
  12310. return;
  12311. }
  12312. // Clears the default actions for each mock method in the given mock
  12313. // object.
  12314. FunctionMockers& mockers =
  12315. g_mock_object_registry.states()[mock_obj].function_mockers;
  12316. for (FunctionMockers::const_iterator it = mockers.begin();
  12317. it != mockers.end(); ++it) {
  12318. (*it)->ClearDefaultActionsLocked();
  12319. }
  12320. // We don't clear the content of mockers, as they may still be
  12321. // needed by VerifyAndClearExpectationsLocked().
  12322. }
  12323. Expectation::Expectation() {}
  12324. Expectation::Expectation(
  12325. const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
  12326. : expectation_base_(an_expectation_base) {}
  12327. Expectation::~Expectation() {}
  12328. // Adds an expectation to a sequence.
  12329. void Sequence::AddExpectation(const Expectation& expectation) const {
  12330. if (*last_expectation_ != expectation) {
  12331. if (last_expectation_->expectation_base() != nullptr) {
  12332. expectation.expectation_base()->immediate_prerequisites_
  12333. += *last_expectation_;
  12334. }
  12335. *last_expectation_ = expectation;
  12336. }
  12337. }
  12338. // Creates the implicit sequence if there isn't one.
  12339. InSequence::InSequence() {
  12340. if (internal::g_gmock_implicit_sequence.get() == nullptr) {
  12341. internal::g_gmock_implicit_sequence.set(new Sequence);
  12342. sequence_created_ = true;
  12343. } else {
  12344. sequence_created_ = false;
  12345. }
  12346. }
  12347. // Deletes the implicit sequence if it was created by the constructor
  12348. // of this object.
  12349. InSequence::~InSequence() {
  12350. if (sequence_created_) {
  12351. delete internal::g_gmock_implicit_sequence.get();
  12352. internal::g_gmock_implicit_sequence.set(nullptr);
  12353. }
  12354. }
  12355. } // namespace testing
  12356. #ifdef _MSC_VER
  12357. #if _MSC_VER == 1900
  12358. # pragma warning(pop)
  12359. #endif
  12360. #endif
  12361. // Copyright 2008, Google Inc.
  12362. // All rights reserved.
  12363. //
  12364. // Redistribution and use in source and binary forms, with or without
  12365. // modification, are permitted provided that the following conditions are
  12366. // met:
  12367. //
  12368. // * Redistributions of source code must retain the above copyright
  12369. // notice, this list of conditions and the following disclaimer.
  12370. // * Redistributions in binary form must reproduce the above
  12371. // copyright notice, this list of conditions and the following disclaimer
  12372. // in the documentation and/or other materials provided with the
  12373. // distribution.
  12374. // * Neither the name of Google Inc. nor the names of its
  12375. // contributors may be used to endorse or promote products derived from
  12376. // this software without specific prior written permission.
  12377. //
  12378. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  12379. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  12380. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  12381. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  12382. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  12383. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  12384. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  12385. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  12386. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12387. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  12388. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  12389. namespace testing {
  12390. GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
  12391. "true if and only if Google Mock should report leaked "
  12392. "mock objects as failures.");
  12393. GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
  12394. "Controls how verbose Google Mock's output is."
  12395. " Valid values:\n"
  12396. " info - prints all messages.\n"
  12397. " warning - prints warnings and errors.\n"
  12398. " error - prints errors only.");
  12399. GMOCK_DEFINE_int32_(default_mock_behavior, 1,
  12400. "Controls the default behavior of mocks."
  12401. " Valid values:\n"
  12402. " 0 - by default, mocks act as NiceMocks.\n"
  12403. " 1 - by default, mocks act as NaggyMocks.\n"
  12404. " 2 - by default, mocks act as StrictMocks.");
  12405. namespace internal {
  12406. // Parses a string as a command line flag. The string should have the
  12407. // format "--gmock_flag=value". When def_optional is true, the
  12408. // "=value" part can be omitted.
  12409. //
  12410. // Returns the value of the flag, or NULL if the parsing failed.
  12411. static const char* ParseGoogleMockFlagValue(const char* str,
  12412. const char* flag,
  12413. bool def_optional) {
  12414. // str and flag must not be NULL.
  12415. if (str == nullptr || flag == nullptr) return nullptr;
  12416. // The flag must start with "--gmock_".
  12417. const std::string flag_str = std::string("--gmock_") + flag;
  12418. const size_t flag_len = flag_str.length();
  12419. if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
  12420. // Skips the flag name.
  12421. const char* flag_end = str + flag_len;
  12422. // When def_optional is true, it's OK to not have a "=value" part.
  12423. if (def_optional && (flag_end[0] == '\0')) {
  12424. return flag_end;
  12425. }
  12426. // If def_optional is true and there are more characters after the
  12427. // flag name, or if def_optional is false, there must be a '=' after
  12428. // the flag name.
  12429. if (flag_end[0] != '=') return nullptr;
  12430. // Returns the string after "=".
  12431. return flag_end + 1;
  12432. }
  12433. // Parses a string for a Google Mock bool flag, in the form of
  12434. // "--gmock_flag=value".
  12435. //
  12436. // On success, stores the value of the flag in *value, and returns
  12437. // true. On failure, returns false without changing *value.
  12438. static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
  12439. bool* value) {
  12440. // Gets the value of the flag as a string.
  12441. const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
  12442. // Aborts if the parsing failed.
  12443. if (value_str == nullptr) return false;
  12444. // Converts the string value to a bool.
  12445. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  12446. return true;
  12447. }
  12448. // Parses a string for a Google Mock string flag, in the form of
  12449. // "--gmock_flag=value".
  12450. //
  12451. // On success, stores the value of the flag in *value, and returns
  12452. // true. On failure, returns false without changing *value.
  12453. template <typename String>
  12454. static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
  12455. String* value) {
  12456. // Gets the value of the flag as a string.
  12457. const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
  12458. // Aborts if the parsing failed.
  12459. if (value_str == nullptr) return false;
  12460. // Sets *value to the value of the flag.
  12461. *value = value_str;
  12462. return true;
  12463. }
  12464. static bool ParseGoogleMockIntFlag(const char* str, const char* flag,
  12465. int32_t* value) {
  12466. // Gets the value of the flag as a string.
  12467. const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
  12468. // Aborts if the parsing failed.
  12469. if (value_str == nullptr) return false;
  12470. // Sets *value to the value of the flag.
  12471. return ParseInt32(Message() << "The value of flag --" << flag,
  12472. value_str, value);
  12473. }
  12474. // The internal implementation of InitGoogleMock().
  12475. //
  12476. // The type parameter CharType can be instantiated to either char or
  12477. // wchar_t.
  12478. template <typename CharType>
  12479. void InitGoogleMockImpl(int* argc, CharType** argv) {
  12480. // Makes sure Google Test is initialized. InitGoogleTest() is
  12481. // idempotent, so it's fine if the user has already called it.
  12482. InitGoogleTest(argc, argv);
  12483. if (*argc <= 0) return;
  12484. for (int i = 1; i != *argc; i++) {
  12485. const std::string arg_string = StreamableToString(argv[i]);
  12486. const char* const arg = arg_string.c_str();
  12487. // Do we see a Google Mock flag?
  12488. if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
  12489. &GMOCK_FLAG(catch_leaked_mocks)) ||
  12490. ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose)) ||
  12491. ParseGoogleMockIntFlag(arg, "default_mock_behavior",
  12492. &GMOCK_FLAG(default_mock_behavior))) {
  12493. // Yes. Shift the remainder of the argv list left by one. Note
  12494. // that argv has (*argc + 1) elements, the last one always being
  12495. // NULL. The following loop moves the trailing NULL element as
  12496. // well.
  12497. for (int j = i; j != *argc; j++) {
  12498. argv[j] = argv[j + 1];
  12499. }
  12500. // Decrements the argument count.
  12501. (*argc)--;
  12502. // We also need to decrement the iterator as we just removed
  12503. // an element.
  12504. i--;
  12505. }
  12506. }
  12507. }
  12508. } // namespace internal
  12509. // Initializes Google Mock. This must be called before running the
  12510. // tests. In particular, it parses a command line for the flags that
  12511. // Google Mock recognizes. Whenever a Google Mock flag is seen, it is
  12512. // removed from argv, and *argc is decremented.
  12513. //
  12514. // No value is returned. Instead, the Google Mock flag variables are
  12515. // updated.
  12516. //
  12517. // Since Google Test is needed for Google Mock to work, this function
  12518. // also initializes Google Test and parses its flags, if that hasn't
  12519. // been done.
  12520. GTEST_API_ void InitGoogleMock(int* argc, char** argv) {
  12521. internal::InitGoogleMockImpl(argc, argv);
  12522. }
  12523. // This overloaded version can be used in Windows programs compiled in
  12524. // UNICODE mode.
  12525. GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
  12526. internal::InitGoogleMockImpl(argc, argv);
  12527. }
  12528. // This overloaded version can be used on Arduino/embedded platforms where
  12529. // there is no argc/argv.
  12530. GTEST_API_ void InitGoogleMock() {
  12531. // Since Arduino doesn't have a command line, fake out the argc/argv arguments
  12532. int argc = 1;
  12533. const auto arg0 = "dummy";
  12534. char* argv0 = const_cast<char*>(arg0);
  12535. char** argv = &argv0;
  12536. internal::InitGoogleMockImpl(&argc, argv);
  12537. }
  12538. } // namespace testing