gtest-all.cc 406 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426
  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 GTEST_INCLUDE_GTEST_GTEST_SPI_H_
  101. #define GTEST_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. virtual ~ScopedFakeTestPartResultReporter();
  132. // Appends the TestPartResult object to the TestPartResultArray
  133. // received in the constructor.
  134. //
  135. // This method is from the TestPartResultReporterInterface
  136. // interface.
  137. virtual void ReportTestPartResult(const TestPartResult& result);
  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 // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
  280. #include <ctype.h>
  281. #include <math.h>
  282. #include <stdarg.h>
  283. #include <stdio.h>
  284. #include <stdlib.h>
  285. #include <time.h>
  286. #include <wchar.h>
  287. #include <wctype.h>
  288. #include <algorithm>
  289. #include <iomanip>
  290. #include <limits>
  291. #include <list>
  292. #include <map>
  293. #include <ostream> // NOLINT
  294. #include <sstream>
  295. #include <vector>
  296. #if GTEST_OS_LINUX
  297. // FIXME: Use autoconf to detect availability of
  298. // gettimeofday().
  299. # define GTEST_HAS_GETTIMEOFDAY_ 1
  300. # include <fcntl.h> // NOLINT
  301. # include <limits.h> // NOLINT
  302. # include <sched.h> // NOLINT
  303. // Declares vsnprintf(). This header is not available on Windows.
  304. # include <strings.h> // NOLINT
  305. # include <sys/mman.h> // NOLINT
  306. # include <sys/time.h> // NOLINT
  307. # include <unistd.h> // NOLINT
  308. # include <string>
  309. #elif GTEST_OS_SYMBIAN
  310. # define GTEST_HAS_GETTIMEOFDAY_ 1
  311. # include <sys/time.h> // NOLINT
  312. #elif GTEST_OS_ZOS
  313. # define GTEST_HAS_GETTIMEOFDAY_ 1
  314. # include <sys/time.h> // NOLINT
  315. // On z/OS we additionally need strings.h for strcasecmp.
  316. # include <strings.h> // NOLINT
  317. #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
  318. # include <windows.h> // NOLINT
  319. # undef min
  320. #elif GTEST_OS_WINDOWS // We are on Windows proper.
  321. # include <io.h> // NOLINT
  322. # include <sys/timeb.h> // NOLINT
  323. # include <sys/types.h> // NOLINT
  324. # include <sys/stat.h> // NOLINT
  325. # if GTEST_OS_WINDOWS_MINGW
  326. // MinGW has gettimeofday() but not _ftime64().
  327. // FIXME: Use autoconf to detect availability of
  328. // gettimeofday().
  329. // FIXME: There are other ways to get the time on
  330. // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
  331. // supports these. consider using them instead.
  332. # define GTEST_HAS_GETTIMEOFDAY_ 1
  333. # include <sys/time.h> // NOLINT
  334. # endif // GTEST_OS_WINDOWS_MINGW
  335. // cpplint thinks that the header is already included, so we want to
  336. // silence it.
  337. # include <windows.h> // NOLINT
  338. # undef min
  339. #else
  340. // Assume other platforms have gettimeofday().
  341. // FIXME: Use autoconf to detect availability of
  342. // gettimeofday().
  343. # define GTEST_HAS_GETTIMEOFDAY_ 1
  344. // cpplint thinks that the header is already included, so we want to
  345. // silence it.
  346. # include <sys/time.h> // NOLINT
  347. # include <unistd.h> // NOLINT
  348. #endif // GTEST_OS_LINUX
  349. #if GTEST_HAS_EXCEPTIONS
  350. # include <stdexcept>
  351. #endif
  352. #if GTEST_CAN_STREAM_RESULTS_
  353. # include <arpa/inet.h> // NOLINT
  354. # include <netdb.h> // NOLINT
  355. # include <sys/socket.h> // NOLINT
  356. # include <sys/types.h> // NOLINT
  357. #endif
  358. // Copyright 2005, Google Inc.
  359. // All rights reserved.
  360. //
  361. // Redistribution and use in source and binary forms, with or without
  362. // modification, are permitted provided that the following conditions are
  363. // met:
  364. //
  365. // * Redistributions of source code must retain the above copyright
  366. // notice, this list of conditions and the following disclaimer.
  367. // * Redistributions in binary form must reproduce the above
  368. // copyright notice, this list of conditions and the following disclaimer
  369. // in the documentation and/or other materials provided with the
  370. // distribution.
  371. // * Neither the name of Google Inc. nor the names of its
  372. // contributors may be used to endorse or promote products derived from
  373. // this software without specific prior written permission.
  374. //
  375. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  376. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  377. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  378. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  379. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  380. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  381. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  382. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  383. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  384. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  385. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  386. // Utility functions and classes used by the Google C++ testing framework.//
  387. // This file contains purely Google Test's internal implementation. Please
  388. // DO NOT #INCLUDE IT IN A USER PROGRAM.
  389. #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
  390. #define GTEST_SRC_GTEST_INTERNAL_INL_H_
  391. #ifndef _WIN32_WCE
  392. # include <errno.h>
  393. #endif // !_WIN32_WCE
  394. #include <stddef.h>
  395. #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
  396. #include <string.h> // For memmove.
  397. #include <algorithm>
  398. #include <string>
  399. #include <vector>
  400. #if GTEST_CAN_STREAM_RESULTS_
  401. # include <arpa/inet.h> // NOLINT
  402. # include <netdb.h> // NOLINT
  403. #endif
  404. #if GTEST_OS_WINDOWS
  405. # include <windows.h> // NOLINT
  406. #endif // GTEST_OS_WINDOWS
  407. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  408. /* class A needs to have dll-interface to be used by clients of class B */)
  409. namespace testing {
  410. // Declares the flags.
  411. //
  412. // We don't want the users to modify this flag in the code, but want
  413. // Google Test's own unit tests to be able to access it. Therefore we
  414. // declare it here as opposed to in gtest.h.
  415. GTEST_DECLARE_bool_(death_test_use_fork);
  416. namespace internal {
  417. template <typename RawType>
  418. AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
  419. const char* rhs_expression,
  420. RawType lhs_value, RawType rhs_value) {
  421. const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
  422. if (lhs.AlmostEquals(rhs)) {
  423. return AssertionSuccess();
  424. }
  425. ::std::stringstream lhs_ss;
  426. lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  427. << lhs_value;
  428. ::std::stringstream rhs_ss;
  429. rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  430. << rhs_value;
  431. return EqFailure(lhs_expression, rhs_expression,
  432. StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss),
  433. false);
  434. }
  435. template
  436. AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
  437. const char* rhs_expression,
  438. float lhs_value, float rhs_value);
  439. template
  440. AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
  441. const char* rhs_expression,
  442. double lhs_value, double rhs_value);
  443. // The value of GetTestTypeId() as seen from within the Google Test
  444. // library. This is solely for testing GetTestTypeId().
  445. GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
  446. // Names of the flags (needed for parsing Google Test flags).
  447. const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
  448. const char kBreakOnFailureFlag[] = "break_on_failure";
  449. const char kCatchExceptionsFlag[] = "catch_exceptions";
  450. const char kColorFlag[] = "color";
  451. const char kFilterFlag[] = "filter";
  452. const char kListTestsFlag[] = "list_tests";
  453. const char kOutputFlag[] = "output";
  454. const char kPrintTimeFlag[] = "print_time";
  455. const char kPrintUTF8Flag[] = "print_utf8";
  456. const char kRandomSeedFlag[] = "random_seed";
  457. const char kRepeatFlag[] = "repeat";
  458. const char kShuffleFlag[] = "shuffle";
  459. const char kStackTraceDepthFlag[] = "stack_trace_depth";
  460. const char kStreamResultToFlag[] = "stream_result_to";
  461. const char kThrowOnFailureFlag[] = "throw_on_failure";
  462. const char kFlagfileFlag[] = "flagfile";
  463. // A valid random seed must be in [1, kMaxRandomSeed].
  464. const int kMaxRandomSeed = 99999;
  465. // g_help_flag is true iff the --help flag or an equivalent form is
  466. // specified on the command line.
  467. GTEST_API_ extern bool g_help_flag;
  468. // Returns the current time in milliseconds.
  469. GTEST_API_ TimeInMillis GetTimeInMillis();
  470. // Returns true iff Google Test should use colors in the output.
  471. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
  472. // Formats the given time in milliseconds as seconds.
  473. GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
  474. // Converts the given time in milliseconds to a date string in the ISO 8601
  475. // format, without the timezone information. N.B.: due to the use the
  476. // non-reentrant localtime() function, this function is not thread safe. Do
  477. // not use it in any code that can be called from multiple threads.
  478. GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
  479. // Parses a string for an Int32 flag, in the form of "--flag=value".
  480. //
  481. // On success, stores the value of the flag in *value, and returns
  482. // true. On failure, returns false without changing *value.
  483. GTEST_API_ bool ParseInt32Flag(
  484. const char* str, const char* flag, Int32* value);
  485. // Returns a random seed in range [1, kMaxRandomSeed] based on the
  486. // given --gtest_random_seed flag value.
  487. inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
  488. const unsigned int raw_seed = (random_seed_flag == 0) ?
  489. static_cast<unsigned int>(GetTimeInMillis()) :
  490. static_cast<unsigned int>(random_seed_flag);
  491. // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
  492. // it's easy to type.
  493. const int normalized_seed =
  494. static_cast<int>((raw_seed - 1U) %
  495. static_cast<unsigned int>(kMaxRandomSeed)) + 1;
  496. return normalized_seed;
  497. }
  498. // Returns the first valid random seed after 'seed'. The behavior is
  499. // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
  500. // considered to be 1.
  501. inline int GetNextRandomSeed(int seed) {
  502. GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
  503. << "Invalid random seed " << seed << " - must be in [1, "
  504. << kMaxRandomSeed << "].";
  505. const int next_seed = seed + 1;
  506. return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
  507. }
  508. // This class saves the values of all Google Test flags in its c'tor, and
  509. // restores them in its d'tor.
  510. class GTestFlagSaver {
  511. public:
  512. // The c'tor.
  513. GTestFlagSaver() {
  514. also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
  515. break_on_failure_ = GTEST_FLAG(break_on_failure);
  516. catch_exceptions_ = GTEST_FLAG(catch_exceptions);
  517. color_ = GTEST_FLAG(color);
  518. death_test_style_ = GTEST_FLAG(death_test_style);
  519. death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
  520. filter_ = GTEST_FLAG(filter);
  521. internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
  522. list_tests_ = GTEST_FLAG(list_tests);
  523. output_ = GTEST_FLAG(output);
  524. print_time_ = GTEST_FLAG(print_time);
  525. print_utf8_ = GTEST_FLAG(print_utf8);
  526. random_seed_ = GTEST_FLAG(random_seed);
  527. repeat_ = GTEST_FLAG(repeat);
  528. shuffle_ = GTEST_FLAG(shuffle);
  529. stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
  530. stream_result_to_ = GTEST_FLAG(stream_result_to);
  531. throw_on_failure_ = GTEST_FLAG(throw_on_failure);
  532. }
  533. // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
  534. ~GTestFlagSaver() {
  535. GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
  536. GTEST_FLAG(break_on_failure) = break_on_failure_;
  537. GTEST_FLAG(catch_exceptions) = catch_exceptions_;
  538. GTEST_FLAG(color) = color_;
  539. GTEST_FLAG(death_test_style) = death_test_style_;
  540. GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
  541. GTEST_FLAG(filter) = filter_;
  542. GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
  543. GTEST_FLAG(list_tests) = list_tests_;
  544. GTEST_FLAG(output) = output_;
  545. GTEST_FLAG(print_time) = print_time_;
  546. GTEST_FLAG(print_utf8) = print_utf8_;
  547. GTEST_FLAG(random_seed) = random_seed_;
  548. GTEST_FLAG(repeat) = repeat_;
  549. GTEST_FLAG(shuffle) = shuffle_;
  550. GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
  551. GTEST_FLAG(stream_result_to) = stream_result_to_;
  552. GTEST_FLAG(throw_on_failure) = throw_on_failure_;
  553. }
  554. private:
  555. // Fields for saving the original values of flags.
  556. bool also_run_disabled_tests_;
  557. bool break_on_failure_;
  558. bool catch_exceptions_;
  559. std::string color_;
  560. std::string death_test_style_;
  561. bool death_test_use_fork_;
  562. std::string filter_;
  563. std::string internal_run_death_test_;
  564. bool list_tests_;
  565. std::string output_;
  566. bool print_time_;
  567. bool print_utf8_;
  568. internal::Int32 random_seed_;
  569. internal::Int32 repeat_;
  570. bool shuffle_;
  571. internal::Int32 stack_trace_depth_;
  572. std::string stream_result_to_;
  573. bool throw_on_failure_;
  574. } GTEST_ATTRIBUTE_UNUSED_;
  575. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  576. // code_point parameter is of type UInt32 because wchar_t may not be
  577. // wide enough to contain a code point.
  578. // If the code_point is not a valid Unicode code point
  579. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  580. // to "(Invalid Unicode 0xXXXXXXXX)".
  581. GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
  582. // Converts a wide string to a narrow string in UTF-8 encoding.
  583. // The wide string is assumed to have the following encoding:
  584. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
  585. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  586. // Parameter str points to a null-terminated wide string.
  587. // Parameter num_chars may additionally limit the number
  588. // of wchar_t characters processed. -1 is used when the entire string
  589. // should be processed.
  590. // If the string contains code points that are not valid Unicode code points
  591. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  592. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  593. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  594. // will be encoded as individual Unicode characters from Basic Normal Plane.
  595. GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
  596. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  597. // if the variable is present. If a file already exists at this location, this
  598. // function will write over it. If the variable is present, but the file cannot
  599. // be created, prints an error and exits.
  600. void WriteToShardStatusFileIfNeeded();
  601. // Checks whether sharding is enabled by examining the relevant
  602. // environment variable values. If the variables are present,
  603. // but inconsistent (e.g., shard_index >= total_shards), prints
  604. // an error and exits. If in_subprocess_for_death_test, sharding is
  605. // disabled because it must only be applied to the original test
  606. // process. Otherwise, we could filter out death tests we intended to execute.
  607. GTEST_API_ bool ShouldShard(const char* total_shards_str,
  608. const char* shard_index_str,
  609. bool in_subprocess_for_death_test);
  610. // Parses the environment variable var as an Int32. If it is unset,
  611. // returns default_val. If it is not an Int32, prints an error and
  612. // and aborts.
  613. GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
  614. // Given the total number of shards, the shard index, and the test id,
  615. // returns true iff the test should be run on this shard. The test id is
  616. // some arbitrary but unique non-negative integer assigned to each test
  617. // method. Assumes that 0 <= shard_index < total_shards.
  618. GTEST_API_ bool ShouldRunTestOnShard(
  619. int total_shards, int shard_index, int test_id);
  620. // STL container utilities.
  621. // Returns the number of elements in the given container that satisfy
  622. // the given predicate.
  623. template <class Container, typename Predicate>
  624. inline int CountIf(const Container& c, Predicate predicate) {
  625. // Implemented as an explicit loop since std::count_if() in libCstd on
  626. // Solaris has a non-standard signature.
  627. int count = 0;
  628. for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
  629. if (predicate(*it))
  630. ++count;
  631. }
  632. return count;
  633. }
  634. // Applies a function/functor to each element in the container.
  635. template <class Container, typename Functor>
  636. void ForEach(const Container& c, Functor functor) {
  637. std::for_each(c.begin(), c.end(), functor);
  638. }
  639. // Returns the i-th element of the vector, or default_value if i is not
  640. // in range [0, v.size()).
  641. template <typename E>
  642. inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
  643. return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
  644. }
  645. // Performs an in-place shuffle of a range of the vector's elements.
  646. // 'begin' and 'end' are element indices as an STL-style range;
  647. // i.e. [begin, end) are shuffled, where 'end' == size() means to
  648. // shuffle to the end of the vector.
  649. template <typename E>
  650. void ShuffleRange(internal::Random* random, int begin, int end,
  651. std::vector<E>* v) {
  652. const int size = static_cast<int>(v->size());
  653. GTEST_CHECK_(0 <= begin && begin <= size)
  654. << "Invalid shuffle range start " << begin << ": must be in range [0, "
  655. << size << "].";
  656. GTEST_CHECK_(begin <= end && end <= size)
  657. << "Invalid shuffle range finish " << end << ": must be in range ["
  658. << begin << ", " << size << "].";
  659. // Fisher-Yates shuffle, from
  660. // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  661. for (int range_width = end - begin; range_width >= 2; range_width--) {
  662. const int last_in_range = begin + range_width - 1;
  663. const int selected = begin + random->Generate(range_width);
  664. std::swap((*v)[selected], (*v)[last_in_range]);
  665. }
  666. }
  667. // Performs an in-place shuffle of the vector's elements.
  668. template <typename E>
  669. inline void Shuffle(internal::Random* random, std::vector<E>* v) {
  670. ShuffleRange(random, 0, static_cast<int>(v->size()), v);
  671. }
  672. // A function for deleting an object. Handy for being used as a
  673. // functor.
  674. template <typename T>
  675. static void Delete(T* x) {
  676. delete x;
  677. }
  678. // A predicate that checks the key of a TestProperty against a known key.
  679. //
  680. // TestPropertyKeyIs is copyable.
  681. class TestPropertyKeyIs {
  682. public:
  683. // Constructor.
  684. //
  685. // TestPropertyKeyIs has NO default constructor.
  686. explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
  687. // Returns true iff the test name of test property matches on key_.
  688. bool operator()(const TestProperty& test_property) const {
  689. return test_property.key() == key_;
  690. }
  691. private:
  692. std::string key_;
  693. };
  694. // Class UnitTestOptions.
  695. //
  696. // This class contains functions for processing options the user
  697. // specifies when running the tests. It has only static members.
  698. //
  699. // In most cases, the user can specify an option using either an
  700. // environment variable or a command line flag. E.g. you can set the
  701. // test filter using either GTEST_FILTER or --gtest_filter. If both
  702. // the variable and the flag are present, the latter overrides the
  703. // former.
  704. class GTEST_API_ UnitTestOptions {
  705. public:
  706. // Functions for processing the gtest_output flag.
  707. // Returns the output format, or "" for normal printed output.
  708. static std::string GetOutputFormat();
  709. // Returns the absolute path of the requested output file, or the
  710. // default (test_detail.xml in the original working directory) if
  711. // none was explicitly specified.
  712. static std::string GetAbsolutePathToOutputFile();
  713. // Functions for processing the gtest_filter flag.
  714. // Returns true iff the wildcard pattern matches the string. The
  715. // first ':' or '\0' character in pattern marks the end of it.
  716. //
  717. // This recursive algorithm isn't very efficient, but is clear and
  718. // works well enough for matching test names, which are short.
  719. static bool PatternMatchesString(const char *pattern, const char *str);
  720. // Returns true iff the user-specified filter matches the test case
  721. // name and the test name.
  722. static bool FilterMatchesTest(const std::string &test_case_name,
  723. const std::string &test_name);
  724. #if GTEST_OS_WINDOWS
  725. // Function for supporting the gtest_catch_exception flag.
  726. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  727. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  728. // This function is useful as an __except condition.
  729. static int GTestShouldProcessSEH(DWORD exception_code);
  730. #endif // GTEST_OS_WINDOWS
  731. // Returns true if "name" matches the ':' separated list of glob-style
  732. // filters in "filter".
  733. static bool MatchesFilter(const std::string& name, const char* filter);
  734. };
  735. // Returns the current application's name, removing directory path if that
  736. // is present. Used by UnitTestOptions::GetOutputFile.
  737. GTEST_API_ FilePath GetCurrentExecutableName();
  738. // The role interface for getting the OS stack trace as a string.
  739. class OsStackTraceGetterInterface {
  740. public:
  741. OsStackTraceGetterInterface() {}
  742. virtual ~OsStackTraceGetterInterface() {}
  743. // Returns the current OS stack trace as an std::string. Parameters:
  744. //
  745. // max_depth - the maximum number of stack frames to be included
  746. // in the trace.
  747. // skip_count - the number of top frames to be skipped; doesn't count
  748. // against max_depth.
  749. virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
  750. // UponLeavingGTest() should be called immediately before Google Test calls
  751. // user code. It saves some information about the current stack that
  752. // CurrentStackTrace() will use to find and hide Google Test stack frames.
  753. virtual void UponLeavingGTest() = 0;
  754. // This string is inserted in place of stack frames that are part of
  755. // Google Test's implementation.
  756. static const char* const kElidedFramesMarker;
  757. private:
  758. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
  759. };
  760. // A working implementation of the OsStackTraceGetterInterface interface.
  761. class OsStackTraceGetter : public OsStackTraceGetterInterface {
  762. public:
  763. OsStackTraceGetter() {}
  764. virtual std::string CurrentStackTrace(int max_depth, int skip_count);
  765. virtual void UponLeavingGTest();
  766. private:
  767. #if GTEST_HAS_ABSL
  768. Mutex mutex_; // Protects all internal state.
  769. // We save the stack frame below the frame that calls user code.
  770. // We do this because the address of the frame immediately below
  771. // the user code changes between the call to UponLeavingGTest()
  772. // and any calls to the stack trace code from within the user code.
  773. void* caller_frame_ = nullptr;
  774. #endif // GTEST_HAS_ABSL
  775. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
  776. };
  777. // Information about a Google Test trace point.
  778. struct TraceInfo {
  779. const char* file;
  780. int line;
  781. std::string message;
  782. };
  783. // This is the default global test part result reporter used in UnitTestImpl.
  784. // This class should only be used by UnitTestImpl.
  785. class DefaultGlobalTestPartResultReporter
  786. : public TestPartResultReporterInterface {
  787. public:
  788. explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
  789. // Implements the TestPartResultReporterInterface. Reports the test part
  790. // result in the current test.
  791. virtual void ReportTestPartResult(const TestPartResult& result);
  792. private:
  793. UnitTestImpl* const unit_test_;
  794. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
  795. };
  796. // This is the default per thread test part result reporter used in
  797. // UnitTestImpl. This class should only be used by UnitTestImpl.
  798. class DefaultPerThreadTestPartResultReporter
  799. : public TestPartResultReporterInterface {
  800. public:
  801. explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
  802. // Implements the TestPartResultReporterInterface. The implementation just
  803. // delegates to the current global test part result reporter of *unit_test_.
  804. virtual void ReportTestPartResult(const TestPartResult& result);
  805. private:
  806. UnitTestImpl* const unit_test_;
  807. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
  808. };
  809. // The private implementation of the UnitTest class. We don't protect
  810. // the methods under a mutex, as this class is not accessible by a
  811. // user and the UnitTest class that delegates work to this class does
  812. // proper locking.
  813. class GTEST_API_ UnitTestImpl {
  814. public:
  815. explicit UnitTestImpl(UnitTest* parent);
  816. virtual ~UnitTestImpl();
  817. // There are two different ways to register your own TestPartResultReporter.
  818. // You can register your own repoter to listen either only for test results
  819. // from the current thread or for results from all threads.
  820. // By default, each per-thread test result repoter just passes a new
  821. // TestPartResult to the global test result reporter, which registers the
  822. // test part result for the currently running test.
  823. // Returns the global test part result reporter.
  824. TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
  825. // Sets the global test part result reporter.
  826. void SetGlobalTestPartResultReporter(
  827. TestPartResultReporterInterface* reporter);
  828. // Returns the test part result reporter for the current thread.
  829. TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
  830. // Sets the test part result reporter for the current thread.
  831. void SetTestPartResultReporterForCurrentThread(
  832. TestPartResultReporterInterface* reporter);
  833. // Gets the number of successful test cases.
  834. int successful_test_case_count() const;
  835. // Gets the number of failed test cases.
  836. int failed_test_case_count() const;
  837. // Gets the number of all test cases.
  838. int total_test_case_count() const;
  839. // Gets the number of all test cases that contain at least one test
  840. // that should run.
  841. int test_case_to_run_count() const;
  842. // Gets the number of successful tests.
  843. int successful_test_count() const;
  844. // Gets the number of failed tests.
  845. int failed_test_count() const;
  846. // Gets the number of disabled tests that will be reported in the XML report.
  847. int reportable_disabled_test_count() const;
  848. // Gets the number of disabled tests.
  849. int disabled_test_count() const;
  850. // Gets the number of tests to be printed in the XML report.
  851. int reportable_test_count() const;
  852. // Gets the number of all tests.
  853. int total_test_count() const;
  854. // Gets the number of tests that should run.
  855. int test_to_run_count() const;
  856. // Gets the time of the test program start, in ms from the start of the
  857. // UNIX epoch.
  858. TimeInMillis start_timestamp() const { return start_timestamp_; }
  859. // Gets the elapsed time, in milliseconds.
  860. TimeInMillis elapsed_time() const { return elapsed_time_; }
  861. // Returns true iff the unit test passed (i.e. all test cases passed).
  862. bool Passed() const { return !Failed(); }
  863. // Returns true iff the unit test failed (i.e. some test case failed
  864. // or something outside of all tests failed).
  865. bool Failed() const {
  866. return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
  867. }
  868. // Gets the i-th test case among all the test cases. i can range from 0 to
  869. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  870. const TestCase* GetTestCase(int i) const {
  871. const int index = GetElementOr(test_case_indices_, i, -1);
  872. return index < 0 ? NULL : test_cases_[i];
  873. }
  874. // Gets the i-th test case among all the test cases. i can range from 0 to
  875. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  876. TestCase* GetMutableTestCase(int i) {
  877. const int index = GetElementOr(test_case_indices_, i, -1);
  878. return index < 0 ? NULL : test_cases_[index];
  879. }
  880. // Provides access to the event listener list.
  881. TestEventListeners* listeners() { return &listeners_; }
  882. // Returns the TestResult for the test that's currently running, or
  883. // the TestResult for the ad hoc test if no test is running.
  884. TestResult* current_test_result();
  885. // Returns the TestResult for the ad hoc test.
  886. const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
  887. // Sets the OS stack trace getter.
  888. //
  889. // Does nothing if the input and the current OS stack trace getter
  890. // are the same; otherwise, deletes the old getter and makes the
  891. // input the current getter.
  892. void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
  893. // Returns the current OS stack trace getter if it is not NULL;
  894. // otherwise, creates an OsStackTraceGetter, makes it the current
  895. // getter, and returns it.
  896. OsStackTraceGetterInterface* os_stack_trace_getter();
  897. // Returns the current OS stack trace as an std::string.
  898. //
  899. // The maximum number of stack frames to be included is specified by
  900. // the gtest_stack_trace_depth flag. The skip_count parameter
  901. // specifies the number of top frames to be skipped, which doesn't
  902. // count against the number of frames to be included.
  903. //
  904. // For example, if Foo() calls Bar(), which in turn calls
  905. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  906. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  907. std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
  908. // Finds and returns a TestCase with the given name. If one doesn't
  909. // exist, creates one and returns it.
  910. //
  911. // Arguments:
  912. //
  913. // test_case_name: name of the test case
  914. // type_param: the name of the test's type parameter, or NULL if
  915. // this is not a typed or a type-parameterized test.
  916. // set_up_tc: pointer to the function that sets up the test case
  917. // tear_down_tc: pointer to the function that tears down the test case
  918. TestCase* GetTestCase(const char* test_case_name,
  919. const char* type_param,
  920. Test::SetUpTestCaseFunc set_up_tc,
  921. Test::TearDownTestCaseFunc tear_down_tc);
  922. // Adds a TestInfo to the unit test.
  923. //
  924. // Arguments:
  925. //
  926. // set_up_tc: pointer to the function that sets up the test case
  927. // tear_down_tc: pointer to the function that tears down the test case
  928. // test_info: the TestInfo object
  929. void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
  930. Test::TearDownTestCaseFunc tear_down_tc,
  931. TestInfo* test_info) {
  932. // In order to support thread-safe death tests, we need to
  933. // remember the original working directory when the test program
  934. // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
  935. // the user may have changed the current directory before calling
  936. // RUN_ALL_TESTS(). Therefore we capture the current directory in
  937. // AddTestInfo(), which is called to register a TEST or TEST_F
  938. // before main() is reached.
  939. if (original_working_dir_.IsEmpty()) {
  940. original_working_dir_.Set(FilePath::GetCurrentDir());
  941. GTEST_CHECK_(!original_working_dir_.IsEmpty())
  942. << "Failed to get the current working directory.";
  943. }
  944. GetTestCase(test_info->test_case_name(),
  945. test_info->type_param(),
  946. set_up_tc,
  947. tear_down_tc)->AddTestInfo(test_info);
  948. }
  949. // Returns ParameterizedTestCaseRegistry object used to keep track of
  950. // value-parameterized tests and instantiate and register them.
  951. internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
  952. return parameterized_test_registry_;
  953. }
  954. // Sets the TestCase object for the test that's currently running.
  955. void set_current_test_case(TestCase* a_current_test_case) {
  956. current_test_case_ = a_current_test_case;
  957. }
  958. // Sets the TestInfo object for the test that's currently running. If
  959. // current_test_info is NULL, the assertion results will be stored in
  960. // ad_hoc_test_result_.
  961. void set_current_test_info(TestInfo* a_current_test_info) {
  962. current_test_info_ = a_current_test_info;
  963. }
  964. // Registers all parameterized tests defined using TEST_P and
  965. // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
  966. // combination. This method can be called more then once; it has guards
  967. // protecting from registering the tests more then once. If
  968. // value-parameterized tests are disabled, RegisterParameterizedTests is
  969. // present but does nothing.
  970. void RegisterParameterizedTests();
  971. // Runs all tests in this UnitTest object, prints the result, and
  972. // returns true if all tests are successful. If any exception is
  973. // thrown during a test, this test is considered to be failed, but
  974. // the rest of the tests will still be run.
  975. bool RunAllTests();
  976. // Clears the results of all tests, except the ad hoc tests.
  977. void ClearNonAdHocTestResult() {
  978. ForEach(test_cases_, TestCase::ClearTestCaseResult);
  979. }
  980. // Clears the results of ad-hoc test assertions.
  981. void ClearAdHocTestResult() {
  982. ad_hoc_test_result_.Clear();
  983. }
  984. // Adds a TestProperty to the current TestResult object when invoked in a
  985. // context of a test or a test case, or to the global property set. If the
  986. // result already contains a property with the same key, the value will be
  987. // updated.
  988. void RecordProperty(const TestProperty& test_property);
  989. enum ReactionToSharding {
  990. HONOR_SHARDING_PROTOCOL,
  991. IGNORE_SHARDING_PROTOCOL
  992. };
  993. // Matches the full name of each test against the user-specified
  994. // filter to decide whether the test should run, then records the
  995. // result in each TestCase and TestInfo object.
  996. // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
  997. // based on sharding variables in the environment.
  998. // Returns the number of tests that should run.
  999. int FilterTests(ReactionToSharding shard_tests);
  1000. // Prints the names of the tests matching the user-specified filter flag.
  1001. void ListTestsMatchingFilter();
  1002. const TestCase* current_test_case() const { return current_test_case_; }
  1003. TestInfo* current_test_info() { return current_test_info_; }
  1004. const TestInfo* current_test_info() const { return current_test_info_; }
  1005. // Returns the vector of environments that need to be set-up/torn-down
  1006. // before/after the tests are run.
  1007. std::vector<Environment*>& environments() { return environments_; }
  1008. // Getters for the per-thread Google Test trace stack.
  1009. std::vector<TraceInfo>& gtest_trace_stack() {
  1010. return *(gtest_trace_stack_.pointer());
  1011. }
  1012. const std::vector<TraceInfo>& gtest_trace_stack() const {
  1013. return gtest_trace_stack_.get();
  1014. }
  1015. #if GTEST_HAS_DEATH_TEST
  1016. void InitDeathTestSubprocessControlInfo() {
  1017. internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
  1018. }
  1019. // Returns a pointer to the parsed --gtest_internal_run_death_test
  1020. // flag, or NULL if that flag was not specified.
  1021. // This information is useful only in a death test child process.
  1022. // Must not be called before a call to InitGoogleTest.
  1023. const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
  1024. return internal_run_death_test_flag_.get();
  1025. }
  1026. // Returns a pointer to the current death test factory.
  1027. internal::DeathTestFactory* death_test_factory() {
  1028. return death_test_factory_.get();
  1029. }
  1030. void SuppressTestEventsIfInSubprocess();
  1031. friend class ReplaceDeathTestFactory;
  1032. #endif // GTEST_HAS_DEATH_TEST
  1033. // Initializes the event listener performing XML output as specified by
  1034. // UnitTestOptions. Must not be called before InitGoogleTest.
  1035. void ConfigureXmlOutput();
  1036. #if GTEST_CAN_STREAM_RESULTS_
  1037. // Initializes the event listener for streaming test results to a socket.
  1038. // Must not be called before InitGoogleTest.
  1039. void ConfigureStreamingOutput();
  1040. #endif
  1041. // Performs initialization dependent upon flag values obtained in
  1042. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  1043. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  1044. // this function is also called from RunAllTests. Since this function can be
  1045. // called more than once, it has to be idempotent.
  1046. void PostFlagParsingInit();
  1047. // Gets the random seed used at the start of the current test iteration.
  1048. int random_seed() const { return random_seed_; }
  1049. // Gets the random number generator.
  1050. internal::Random* random() { return &random_; }
  1051. // Shuffles all test cases, and the tests within each test case,
  1052. // making sure that death tests are still run first.
  1053. void ShuffleTests();
  1054. // Restores the test cases and tests to their order before the first shuffle.
  1055. void UnshuffleTests();
  1056. // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
  1057. // UnitTest::Run() starts.
  1058. bool catch_exceptions() const { return catch_exceptions_; }
  1059. private:
  1060. friend class ::testing::UnitTest;
  1061. // Used by UnitTest::Run() to capture the state of
  1062. // GTEST_FLAG(catch_exceptions) at the moment it starts.
  1063. void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
  1064. // The UnitTest object that owns this implementation object.
  1065. UnitTest* const parent_;
  1066. // The working directory when the first TEST() or TEST_F() was
  1067. // executed.
  1068. internal::FilePath original_working_dir_;
  1069. // The default test part result reporters.
  1070. DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
  1071. DefaultPerThreadTestPartResultReporter
  1072. default_per_thread_test_part_result_reporter_;
  1073. // Points to (but doesn't own) the global test part result reporter.
  1074. TestPartResultReporterInterface* global_test_part_result_repoter_;
  1075. // Protects read and write access to global_test_part_result_reporter_.
  1076. internal::Mutex global_test_part_result_reporter_mutex_;
  1077. // Points to (but doesn't own) the per-thread test part result reporter.
  1078. internal::ThreadLocal<TestPartResultReporterInterface*>
  1079. per_thread_test_part_result_reporter_;
  1080. // The vector of environments that need to be set-up/torn-down
  1081. // before/after the tests are run.
  1082. std::vector<Environment*> environments_;
  1083. // The vector of TestCases in their original order. It owns the
  1084. // elements in the vector.
  1085. std::vector<TestCase*> test_cases_;
  1086. // Provides a level of indirection for the test case list to allow
  1087. // easy shuffling and restoring the test case order. The i-th
  1088. // element of this vector is the index of the i-th test case in the
  1089. // shuffled order.
  1090. std::vector<int> test_case_indices_;
  1091. // ParameterizedTestRegistry object used to register value-parameterized
  1092. // tests.
  1093. internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
  1094. // Indicates whether RegisterParameterizedTests() has been called already.
  1095. bool parameterized_tests_registered_;
  1096. // Index of the last death test case registered. Initially -1.
  1097. int last_death_test_case_;
  1098. // This points to the TestCase for the currently running test. It
  1099. // changes as Google Test goes through one test case after another.
  1100. // When no test is running, this is set to NULL and Google Test
  1101. // stores assertion results in ad_hoc_test_result_. Initially NULL.
  1102. TestCase* current_test_case_;
  1103. // This points to the TestInfo for the currently running test. It
  1104. // changes as Google Test goes through one test after another. When
  1105. // no test is running, this is set to NULL and Google Test stores
  1106. // assertion results in ad_hoc_test_result_. Initially NULL.
  1107. TestInfo* current_test_info_;
  1108. // Normally, a user only writes assertions inside a TEST or TEST_F,
  1109. // or inside a function called by a TEST or TEST_F. Since Google
  1110. // Test keeps track of which test is current running, it can
  1111. // associate such an assertion with the test it belongs to.
  1112. //
  1113. // If an assertion is encountered when no TEST or TEST_F is running,
  1114. // Google Test attributes the assertion result to an imaginary "ad hoc"
  1115. // test, and records the result in ad_hoc_test_result_.
  1116. TestResult ad_hoc_test_result_;
  1117. // The list of event listeners that can be used to track events inside
  1118. // Google Test.
  1119. TestEventListeners listeners_;
  1120. // The OS stack trace getter. Will be deleted when the UnitTest
  1121. // object is destructed. By default, an OsStackTraceGetter is used,
  1122. // but the user can set this field to use a custom getter if that is
  1123. // desired.
  1124. OsStackTraceGetterInterface* os_stack_trace_getter_;
  1125. // True iff PostFlagParsingInit() has been called.
  1126. bool post_flag_parse_init_performed_;
  1127. // The random number seed used at the beginning of the test run.
  1128. int random_seed_;
  1129. // Our random number generator.
  1130. internal::Random random_;
  1131. // The time of the test program start, in ms from the start of the
  1132. // UNIX epoch.
  1133. TimeInMillis start_timestamp_;
  1134. // How long the test took to run, in milliseconds.
  1135. TimeInMillis elapsed_time_;
  1136. #if GTEST_HAS_DEATH_TEST
  1137. // The decomposed components of the gtest_internal_run_death_test flag,
  1138. // parsed when RUN_ALL_TESTS is called.
  1139. internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
  1140. internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
  1141. #endif // GTEST_HAS_DEATH_TEST
  1142. // A per-thread stack of traces created by the SCOPED_TRACE() macro.
  1143. internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
  1144. // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
  1145. // starts.
  1146. bool catch_exceptions_;
  1147. GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
  1148. }; // class UnitTestImpl
  1149. // Convenience function for accessing the global UnitTest
  1150. // implementation object.
  1151. inline UnitTestImpl* GetUnitTestImpl() {
  1152. return UnitTest::GetInstance()->impl();
  1153. }
  1154. #if GTEST_USES_SIMPLE_RE
  1155. // Internal helper functions for implementing the simple regular
  1156. // expression matcher.
  1157. GTEST_API_ bool IsInSet(char ch, const char* str);
  1158. GTEST_API_ bool IsAsciiDigit(char ch);
  1159. GTEST_API_ bool IsAsciiPunct(char ch);
  1160. GTEST_API_ bool IsRepeat(char ch);
  1161. GTEST_API_ bool IsAsciiWhiteSpace(char ch);
  1162. GTEST_API_ bool IsAsciiWordChar(char ch);
  1163. GTEST_API_ bool IsValidEscape(char ch);
  1164. GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
  1165. GTEST_API_ bool ValidateRegex(const char* regex);
  1166. GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
  1167. GTEST_API_ bool MatchRepetitionAndRegexAtHead(
  1168. bool escaped, char ch, char repeat, const char* regex, const char* str);
  1169. GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
  1170. #endif // GTEST_USES_SIMPLE_RE
  1171. // Parses the command line for Google Test flags, without initializing
  1172. // other parts of Google Test.
  1173. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
  1174. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
  1175. #if GTEST_HAS_DEATH_TEST
  1176. // Returns the message describing the last system error, regardless of the
  1177. // platform.
  1178. GTEST_API_ std::string GetLastErrnoDescription();
  1179. // Attempts to parse a string into a positive integer pointed to by the
  1180. // number parameter. Returns true if that is possible.
  1181. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
  1182. // it here.
  1183. template <typename Integer>
  1184. bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
  1185. // Fail fast if the given string does not begin with a digit;
  1186. // this bypasses strtoXXX's "optional leading whitespace and plus
  1187. // or minus sign" semantics, which are undesirable here.
  1188. if (str.empty() || !IsDigit(str[0])) {
  1189. return false;
  1190. }
  1191. errno = 0;
  1192. char* end;
  1193. // BiggestConvertible is the largest integer type that system-provided
  1194. // string-to-number conversion routines can return.
  1195. # if GTEST_OS_WINDOWS && !defined(__GNUC__)
  1196. // MSVC and C++ Builder define __int64 instead of the standard long long.
  1197. typedef unsigned __int64 BiggestConvertible;
  1198. const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
  1199. # else
  1200. typedef unsigned long long BiggestConvertible; // NOLINT
  1201. const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
  1202. # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
  1203. const bool parse_success = *end == '\0' && errno == 0;
  1204. // FIXME: Convert this to compile time assertion when it is
  1205. // available.
  1206. GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
  1207. const Integer result = static_cast<Integer>(parsed);
  1208. if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
  1209. *number = result;
  1210. return true;
  1211. }
  1212. return false;
  1213. }
  1214. #endif // GTEST_HAS_DEATH_TEST
  1215. // TestResult contains some private methods that should be hidden from
  1216. // Google Test user but are required for testing. This class allow our tests
  1217. // to access them.
  1218. //
  1219. // This class is supplied only for the purpose of testing Google Test's own
  1220. // constructs. Do not use it in user tests, either directly or indirectly.
  1221. class TestResultAccessor {
  1222. public:
  1223. static void RecordProperty(TestResult* test_result,
  1224. const std::string& xml_element,
  1225. const TestProperty& property) {
  1226. test_result->RecordProperty(xml_element, property);
  1227. }
  1228. static void ClearTestPartResults(TestResult* test_result) {
  1229. test_result->ClearTestPartResults();
  1230. }
  1231. static const std::vector<testing::TestPartResult>& test_part_results(
  1232. const TestResult& test_result) {
  1233. return test_result.test_part_results();
  1234. }
  1235. };
  1236. #if GTEST_CAN_STREAM_RESULTS_
  1237. // Streams test results to the given port on the given host machine.
  1238. class StreamingListener : public EmptyTestEventListener {
  1239. public:
  1240. // Abstract base class for writing strings to a socket.
  1241. class AbstractSocketWriter {
  1242. public:
  1243. virtual ~AbstractSocketWriter() {}
  1244. // Sends a string to the socket.
  1245. virtual void Send(const std::string& message) = 0;
  1246. // Closes the socket.
  1247. virtual void CloseConnection() {}
  1248. // Sends a string and a newline to the socket.
  1249. void SendLn(const std::string& message) { Send(message + "\n"); }
  1250. };
  1251. // Concrete class for actually writing strings to a socket.
  1252. class SocketWriter : public AbstractSocketWriter {
  1253. public:
  1254. SocketWriter(const std::string& host, const std::string& port)
  1255. : sockfd_(-1), host_name_(host), port_num_(port) {
  1256. MakeConnection();
  1257. }
  1258. virtual ~SocketWriter() {
  1259. if (sockfd_ != -1)
  1260. CloseConnection();
  1261. }
  1262. // Sends a string to the socket.
  1263. virtual void Send(const std::string& message) {
  1264. GTEST_CHECK_(sockfd_ != -1)
  1265. << "Send() can be called only when there is a connection.";
  1266. const int len = static_cast<int>(message.length());
  1267. if (write(sockfd_, message.c_str(), len) != len) {
  1268. GTEST_LOG_(WARNING)
  1269. << "stream_result_to: failed to stream to "
  1270. << host_name_ << ":" << port_num_;
  1271. }
  1272. }
  1273. private:
  1274. // Creates a client socket and connects to the server.
  1275. void MakeConnection();
  1276. // Closes the socket.
  1277. void CloseConnection() {
  1278. GTEST_CHECK_(sockfd_ != -1)
  1279. << "CloseConnection() can be called only when there is a connection.";
  1280. close(sockfd_);
  1281. sockfd_ = -1;
  1282. }
  1283. int sockfd_; // socket file descriptor
  1284. const std::string host_name_;
  1285. const std::string port_num_;
  1286. GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
  1287. }; // class SocketWriter
  1288. // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
  1289. static std::string UrlEncode(const char* str);
  1290. StreamingListener(const std::string& host, const std::string& port)
  1291. : socket_writer_(new SocketWriter(host, port)) {
  1292. Start();
  1293. }
  1294. explicit StreamingListener(AbstractSocketWriter* socket_writer)
  1295. : socket_writer_(socket_writer) { Start(); }
  1296. void OnTestProgramStart(const UnitTest& /* unit_test */) {
  1297. SendLn("event=TestProgramStart");
  1298. }
  1299. void OnTestProgramEnd(const UnitTest& unit_test) {
  1300. // Note that Google Test current only report elapsed time for each
  1301. // test iteration, not for the entire test program.
  1302. SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
  1303. // Notify the streaming server to stop.
  1304. socket_writer_->CloseConnection();
  1305. }
  1306. void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
  1307. SendLn("event=TestIterationStart&iteration=" +
  1308. StreamableToString(iteration));
  1309. }
  1310. void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
  1311. SendLn("event=TestIterationEnd&passed=" +
  1312. FormatBool(unit_test.Passed()) + "&elapsed_time=" +
  1313. StreamableToString(unit_test.elapsed_time()) + "ms");
  1314. }
  1315. void OnTestCaseStart(const TestCase& test_case) {
  1316. SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
  1317. }
  1318. void OnTestCaseEnd(const TestCase& test_case) {
  1319. SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
  1320. + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
  1321. + "ms");
  1322. }
  1323. void OnTestStart(const TestInfo& test_info) {
  1324. SendLn(std::string("event=TestStart&name=") + test_info.name());
  1325. }
  1326. void OnTestEnd(const TestInfo& test_info) {
  1327. SendLn("event=TestEnd&passed=" +
  1328. FormatBool((test_info.result())->Passed()) +
  1329. "&elapsed_time=" +
  1330. StreamableToString((test_info.result())->elapsed_time()) + "ms");
  1331. }
  1332. void OnTestPartResult(const TestPartResult& test_part_result) {
  1333. const char* file_name = test_part_result.file_name();
  1334. if (file_name == NULL)
  1335. file_name = "";
  1336. SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
  1337. "&line=" + StreamableToString(test_part_result.line_number()) +
  1338. "&message=" + UrlEncode(test_part_result.message()));
  1339. }
  1340. private:
  1341. // Sends the given message and a newline to the socket.
  1342. void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
  1343. // Called at the start of streaming to notify the receiver what
  1344. // protocol we are using.
  1345. void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
  1346. std::string FormatBool(bool value) { return value ? "1" : "0"; }
  1347. const scoped_ptr<AbstractSocketWriter> socket_writer_;
  1348. GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
  1349. }; // class StreamingListener
  1350. #endif // GTEST_CAN_STREAM_RESULTS_
  1351. } // namespace internal
  1352. } // namespace testing
  1353. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  1354. #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
  1355. #if GTEST_OS_WINDOWS
  1356. # define vsnprintf _vsnprintf
  1357. #endif // GTEST_OS_WINDOWS
  1358. #if GTEST_OS_MAC
  1359. #ifndef GTEST_OS_IOS
  1360. #include <crt_externs.h>
  1361. #endif
  1362. #endif
  1363. #if GTEST_HAS_ABSL
  1364. #include "absl/debugging/failure_signal_handler.h"
  1365. #include "absl/debugging/stacktrace.h"
  1366. #include "absl/debugging/symbolize.h"
  1367. #include "absl/strings/str_cat.h"
  1368. #endif // GTEST_HAS_ABSL
  1369. namespace testing {
  1370. using internal::CountIf;
  1371. using internal::ForEach;
  1372. using internal::GetElementOr;
  1373. using internal::Shuffle;
  1374. // Constants.
  1375. // A test whose test case name or test name matches this filter is
  1376. // disabled and not run.
  1377. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
  1378. // A test case whose name matches this filter is considered a death
  1379. // test case and will be run before test cases whose name doesn't
  1380. // match this filter.
  1381. static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
  1382. // A test filter that matches everything.
  1383. static const char kUniversalFilter[] = "*";
  1384. // The default output format.
  1385. static const char kDefaultOutputFormat[] = "xml";
  1386. // The default output file.
  1387. static const char kDefaultOutputFile[] = "test_detail";
  1388. // The environment variable name for the test shard index.
  1389. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
  1390. // The environment variable name for the total number of test shards.
  1391. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
  1392. // The environment variable name for the test shard status file.
  1393. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
  1394. namespace internal {
  1395. // The text used in failure messages to indicate the start of the
  1396. // stack trace.
  1397. const char kStackTraceMarker[] = "\nStack trace:\n";
  1398. // g_help_flag is true iff the --help flag or an equivalent form is
  1399. // specified on the command line.
  1400. bool g_help_flag = false;
  1401. // Utilty function to Open File for Writing
  1402. static FILE* OpenFileForWriting(const std::string& output_file) {
  1403. FILE* fileout = NULL;
  1404. FilePath output_file_path(output_file);
  1405. FilePath output_dir(output_file_path.RemoveFileName());
  1406. if (output_dir.CreateDirectoriesRecursively()) {
  1407. fileout = posix::FOpen(output_file.c_str(), "w");
  1408. }
  1409. if (fileout == NULL) {
  1410. GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
  1411. }
  1412. return fileout;
  1413. }
  1414. } // namespace internal
  1415. // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
  1416. // environment variable.
  1417. static const char* GetDefaultFilter() {
  1418. const char* const testbridge_test_only =
  1419. internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
  1420. if (testbridge_test_only != NULL) {
  1421. return testbridge_test_only;
  1422. }
  1423. return kUniversalFilter;
  1424. }
  1425. GTEST_DEFINE_bool_(
  1426. also_run_disabled_tests,
  1427. internal::BoolFromGTestEnv("also_run_disabled_tests", false),
  1428. "Run disabled tests too, in addition to the tests normally being run.");
  1429. GTEST_DEFINE_bool_(
  1430. break_on_failure,
  1431. internal::BoolFromGTestEnv("break_on_failure", false),
  1432. "True iff a failed assertion should be a debugger break-point.");
  1433. GTEST_DEFINE_bool_(
  1434. catch_exceptions,
  1435. internal::BoolFromGTestEnv("catch_exceptions", true),
  1436. "True iff " GTEST_NAME_
  1437. " should catch exceptions and treat them as test failures.");
  1438. GTEST_DEFINE_string_(
  1439. color,
  1440. internal::StringFromGTestEnv("color", "auto"),
  1441. "Whether to use colors in the output. Valid values: yes, no, "
  1442. "and auto. 'auto' means to use colors if the output is "
  1443. "being sent to a terminal and the TERM environment variable "
  1444. "is set to a terminal type that supports colors.");
  1445. GTEST_DEFINE_string_(
  1446. filter,
  1447. internal::StringFromGTestEnv("filter", GetDefaultFilter()),
  1448. "A colon-separated list of glob (not regex) patterns "
  1449. "for filtering the tests to run, optionally followed by a "
  1450. "'-' and a : separated list of negative patterns (tests to "
  1451. "exclude). A test is run if it matches one of the positive "
  1452. "patterns and does not match any of the negative patterns.");
  1453. GTEST_DEFINE_bool_(
  1454. install_failure_signal_handler,
  1455. internal::BoolFromGTestEnv("install_failure_signal_handler", false),
  1456. "If true and supported on the current platform, " GTEST_NAME_ " should "
  1457. "install a signal handler that dumps debugging information when fatal "
  1458. "signals are raised.");
  1459. GTEST_DEFINE_bool_(list_tests, false,
  1460. "List all tests without running them.");
  1461. // The net priority order after flag processing is thus:
  1462. // --gtest_output command line flag
  1463. // GTEST_OUTPUT environment variable
  1464. // XML_OUTPUT_FILE environment variable
  1465. // ''
  1466. GTEST_DEFINE_string_(
  1467. output,
  1468. internal::StringFromGTestEnv("output",
  1469. internal::OutputFlagAlsoCheckEnvVar().c_str()),
  1470. "A format (defaults to \"xml\" but can be specified to be \"json\"), "
  1471. "optionally followed by a colon and an output file name or directory. "
  1472. "A directory is indicated by a trailing pathname separator. "
  1473. "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
  1474. "If a directory is specified, output files will be created "
  1475. "within that directory, with file-names based on the test "
  1476. "executable's name and, if necessary, made unique by adding "
  1477. "digits.");
  1478. GTEST_DEFINE_bool_(
  1479. print_time,
  1480. internal::BoolFromGTestEnv("print_time", true),
  1481. "True iff " GTEST_NAME_
  1482. " should display elapsed time in text output.");
  1483. GTEST_DEFINE_bool_(
  1484. print_utf8,
  1485. internal::BoolFromGTestEnv("print_utf8", true),
  1486. "True iff " GTEST_NAME_
  1487. " prints UTF8 characters as text.");
  1488. GTEST_DEFINE_int32_(
  1489. random_seed,
  1490. internal::Int32FromGTestEnv("random_seed", 0),
  1491. "Random number seed to use when shuffling test orders. Must be in range "
  1492. "[1, 99999], or 0 to use a seed based on the current time.");
  1493. GTEST_DEFINE_int32_(
  1494. repeat,
  1495. internal::Int32FromGTestEnv("repeat", 1),
  1496. "How many times to repeat each test. Specify a negative number "
  1497. "for repeating forever. Useful for shaking out flaky tests.");
  1498. GTEST_DEFINE_bool_(
  1499. show_internal_stack_frames, false,
  1500. "True iff " GTEST_NAME_ " should include internal stack frames when "
  1501. "printing test failure stack traces.");
  1502. GTEST_DEFINE_bool_(
  1503. shuffle,
  1504. internal::BoolFromGTestEnv("shuffle", false),
  1505. "True iff " GTEST_NAME_
  1506. " should randomize tests' order on every run.");
  1507. GTEST_DEFINE_int32_(
  1508. stack_trace_depth,
  1509. internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
  1510. "The maximum number of stack frames to print when an "
  1511. "assertion fails. The valid range is 0 through 100, inclusive.");
  1512. GTEST_DEFINE_string_(
  1513. stream_result_to,
  1514. internal::StringFromGTestEnv("stream_result_to", ""),
  1515. "This flag specifies the host name and the port number on which to stream "
  1516. "test results. Example: \"localhost:555\". The flag is effective only on "
  1517. "Linux.");
  1518. GTEST_DEFINE_bool_(
  1519. throw_on_failure,
  1520. internal::BoolFromGTestEnv("throw_on_failure", false),
  1521. "When this flag is specified, a failed assertion will throw an exception "
  1522. "if exceptions are enabled or exit the program with a non-zero code "
  1523. "otherwise. For use with an external test framework.");
  1524. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  1525. GTEST_DEFINE_string_(
  1526. flagfile,
  1527. internal::StringFromGTestEnv("flagfile", ""),
  1528. "This flag specifies the flagfile to read command-line flags from.");
  1529. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  1530. namespace internal {
  1531. // Generates a random number from [0, range), using a Linear
  1532. // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
  1533. // than kMaxRange.
  1534. UInt32 Random::Generate(UInt32 range) {
  1535. // These constants are the same as are used in glibc's rand(3).
  1536. // Use wider types than necessary to prevent unsigned overflow diagnostics.
  1537. state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange;
  1538. GTEST_CHECK_(range > 0)
  1539. << "Cannot generate a number in the range [0, 0).";
  1540. GTEST_CHECK_(range <= kMaxRange)
  1541. << "Generation of a number in [0, " << range << ") was requested, "
  1542. << "but this can only generate numbers in [0, " << kMaxRange << ").";
  1543. // Converting via modulus introduces a bit of downward bias, but
  1544. // it's simple, and a linear congruential generator isn't too good
  1545. // to begin with.
  1546. return state_ % range;
  1547. }
  1548. // GTestIsInitialized() returns true iff the user has initialized
  1549. // Google Test. Useful for catching the user mistake of not initializing
  1550. // Google Test before calling RUN_ALL_TESTS().
  1551. static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
  1552. // Iterates over a vector of TestCases, keeping a running sum of the
  1553. // results of calling a given int-returning method on each.
  1554. // Returns the sum.
  1555. static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
  1556. int (TestCase::*method)() const) {
  1557. int sum = 0;
  1558. for (size_t i = 0; i < case_list.size(); i++) {
  1559. sum += (case_list[i]->*method)();
  1560. }
  1561. return sum;
  1562. }
  1563. // Returns true iff the test case passed.
  1564. static bool TestCasePassed(const TestCase* test_case) {
  1565. return test_case->should_run() && test_case->Passed();
  1566. }
  1567. // Returns true iff the test case failed.
  1568. static bool TestCaseFailed(const TestCase* test_case) {
  1569. return test_case->should_run() && test_case->Failed();
  1570. }
  1571. // Returns true iff test_case contains at least one test that should
  1572. // run.
  1573. static bool ShouldRunTestCase(const TestCase* test_case) {
  1574. return test_case->should_run();
  1575. }
  1576. // AssertHelper constructor.
  1577. AssertHelper::AssertHelper(TestPartResult::Type type,
  1578. const char* file,
  1579. int line,
  1580. const char* message)
  1581. : data_(new AssertHelperData(type, file, line, message)) {
  1582. }
  1583. AssertHelper::~AssertHelper() {
  1584. delete data_;
  1585. }
  1586. // Message assignment, for assertion streaming support.
  1587. void AssertHelper::operator=(const Message& message) const {
  1588. UnitTest::GetInstance()->
  1589. AddTestPartResult(data_->type, data_->file, data_->line,
  1590. AppendUserMessage(data_->message, message),
  1591. UnitTest::GetInstance()->impl()
  1592. ->CurrentOsStackTraceExceptTop(1)
  1593. // Skips the stack frame for this function itself.
  1594. ); // NOLINT
  1595. }
  1596. // Mutex for linked pointers.
  1597. GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
  1598. // A copy of all command line arguments. Set by InitGoogleTest().
  1599. static ::std::vector<std::string> g_argvs;
  1600. ::std::vector<std::string> GetArgvs() {
  1601. #if defined(GTEST_CUSTOM_GET_ARGVS_)
  1602. // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
  1603. // ::string. This code converts it to the appropriate type.
  1604. const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
  1605. return ::std::vector<std::string>(custom.begin(), custom.end());
  1606. #else // defined(GTEST_CUSTOM_GET_ARGVS_)
  1607. return g_argvs;
  1608. #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
  1609. }
  1610. // Returns the current application's name, removing directory path if that
  1611. // is present.
  1612. FilePath GetCurrentExecutableName() {
  1613. FilePath result;
  1614. #if GTEST_OS_WINDOWS
  1615. result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
  1616. #else
  1617. result.Set(FilePath(GetArgvs()[0]));
  1618. #endif // GTEST_OS_WINDOWS
  1619. return result.RemoveDirectoryName();
  1620. }
  1621. // Functions for processing the gtest_output flag.
  1622. // Returns the output format, or "" for normal printed output.
  1623. std::string UnitTestOptions::GetOutputFormat() {
  1624. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1625. const char* const colon = strchr(gtest_output_flag, ':');
  1626. return (colon == NULL) ?
  1627. std::string(gtest_output_flag) :
  1628. std::string(gtest_output_flag, colon - gtest_output_flag);
  1629. }
  1630. // Returns the name of the requested output file, or the default if none
  1631. // was explicitly specified.
  1632. std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
  1633. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1634. std::string format = GetOutputFormat();
  1635. if (format.empty())
  1636. format = std::string(kDefaultOutputFormat);
  1637. const char* const colon = strchr(gtest_output_flag, ':');
  1638. if (colon == NULL)
  1639. return internal::FilePath::MakeFileName(
  1640. internal::FilePath(
  1641. UnitTest::GetInstance()->original_working_dir()),
  1642. internal::FilePath(kDefaultOutputFile), 0,
  1643. format.c_str()).string();
  1644. internal::FilePath output_name(colon + 1);
  1645. if (!output_name.IsAbsolutePath())
  1646. // FIXME: on Windows \some\path is not an absolute
  1647. // path (as its meaning depends on the current drive), yet the
  1648. // following logic for turning it into an absolute path is wrong.
  1649. // Fix it.
  1650. output_name = internal::FilePath::ConcatPaths(
  1651. internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
  1652. internal::FilePath(colon + 1));
  1653. if (!output_name.IsDirectory())
  1654. return output_name.string();
  1655. internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
  1656. output_name, internal::GetCurrentExecutableName(),
  1657. GetOutputFormat().c_str()));
  1658. return result.string();
  1659. }
  1660. // Returns true iff the wildcard pattern matches the string. The
  1661. // first ':' or '\0' character in pattern marks the end of it.
  1662. //
  1663. // This recursive algorithm isn't very efficient, but is clear and
  1664. // works well enough for matching test names, which are short.
  1665. bool UnitTestOptions::PatternMatchesString(const char *pattern,
  1666. const char *str) {
  1667. switch (*pattern) {
  1668. case '\0':
  1669. case ':': // Either ':' or '\0' marks the end of the pattern.
  1670. return *str == '\0';
  1671. case '?': // Matches any single character.
  1672. return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
  1673. case '*': // Matches any string (possibly empty) of characters.
  1674. return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
  1675. PatternMatchesString(pattern + 1, str);
  1676. default: // Non-special character. Matches itself.
  1677. return *pattern == *str &&
  1678. PatternMatchesString(pattern + 1, str + 1);
  1679. }
  1680. }
  1681. bool UnitTestOptions::MatchesFilter(
  1682. const std::string& name, const char* filter) {
  1683. const char *cur_pattern = filter;
  1684. for (;;) {
  1685. if (PatternMatchesString(cur_pattern, name.c_str())) {
  1686. return true;
  1687. }
  1688. // Finds the next pattern in the filter.
  1689. cur_pattern = strchr(cur_pattern, ':');
  1690. // Returns if no more pattern can be found.
  1691. if (cur_pattern == NULL) {
  1692. return false;
  1693. }
  1694. // Skips the pattern separater (the ':' character).
  1695. cur_pattern++;
  1696. }
  1697. }
  1698. // Returns true iff the user-specified filter matches the test case
  1699. // name and the test name.
  1700. bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
  1701. const std::string &test_name) {
  1702. const std::string& full_name = test_case_name + "." + test_name.c_str();
  1703. // Split --gtest_filter at '-', if there is one, to separate into
  1704. // positive filter and negative filter portions
  1705. const char* const p = GTEST_FLAG(filter).c_str();
  1706. const char* const dash = strchr(p, '-');
  1707. std::string positive;
  1708. std::string negative;
  1709. if (dash == NULL) {
  1710. positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
  1711. negative = "";
  1712. } else {
  1713. positive = std::string(p, dash); // Everything up to the dash
  1714. negative = std::string(dash + 1); // Everything after the dash
  1715. if (positive.empty()) {
  1716. // Treat '-test1' as the same as '*-test1'
  1717. positive = kUniversalFilter;
  1718. }
  1719. }
  1720. // A filter is a colon-separated list of patterns. It matches a
  1721. // test if any pattern in it matches the test.
  1722. return (MatchesFilter(full_name, positive.c_str()) &&
  1723. !MatchesFilter(full_name, negative.c_str()));
  1724. }
  1725. #if GTEST_HAS_SEH
  1726. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  1727. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  1728. // This function is useful as an __except condition.
  1729. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
  1730. // Google Test should handle a SEH exception if:
  1731. // 1. the user wants it to, AND
  1732. // 2. this is not a breakpoint exception, AND
  1733. // 3. this is not a C++ exception (VC++ implements them via SEH,
  1734. // apparently).
  1735. //
  1736. // SEH exception code for C++ exceptions.
  1737. // (see http://support.microsoft.com/kb/185294 for more information).
  1738. const DWORD kCxxExceptionCode = 0xe06d7363;
  1739. bool should_handle = true;
  1740. if (!GTEST_FLAG(catch_exceptions))
  1741. should_handle = false;
  1742. else if (exception_code == EXCEPTION_BREAKPOINT)
  1743. should_handle = false;
  1744. else if (exception_code == kCxxExceptionCode)
  1745. should_handle = false;
  1746. return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
  1747. }
  1748. #endif // GTEST_HAS_SEH
  1749. } // namespace internal
  1750. // The c'tor sets this object as the test part result reporter used by
  1751. // Google Test. The 'result' parameter specifies where to report the
  1752. // results. Intercepts only failures from the current thread.
  1753. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1754. TestPartResultArray* result)
  1755. : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
  1756. result_(result) {
  1757. Init();
  1758. }
  1759. // The c'tor sets this object as the test part result reporter used by
  1760. // Google Test. The 'result' parameter specifies where to report the
  1761. // results.
  1762. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1763. InterceptMode intercept_mode, TestPartResultArray* result)
  1764. : intercept_mode_(intercept_mode),
  1765. result_(result) {
  1766. Init();
  1767. }
  1768. void ScopedFakeTestPartResultReporter::Init() {
  1769. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1770. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1771. old_reporter_ = impl->GetGlobalTestPartResultReporter();
  1772. impl->SetGlobalTestPartResultReporter(this);
  1773. } else {
  1774. old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
  1775. impl->SetTestPartResultReporterForCurrentThread(this);
  1776. }
  1777. }
  1778. // The d'tor restores the test part result reporter used by Google Test
  1779. // before.
  1780. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
  1781. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1782. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1783. impl->SetGlobalTestPartResultReporter(old_reporter_);
  1784. } else {
  1785. impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
  1786. }
  1787. }
  1788. // Increments the test part result count and remembers the result.
  1789. // This method is from the TestPartResultReporterInterface interface.
  1790. void ScopedFakeTestPartResultReporter::ReportTestPartResult(
  1791. const TestPartResult& result) {
  1792. result_->Append(result);
  1793. }
  1794. namespace internal {
  1795. // Returns the type ID of ::testing::Test. We should always call this
  1796. // instead of GetTypeId< ::testing::Test>() to get the type ID of
  1797. // testing::Test. This is to work around a suspected linker bug when
  1798. // using Google Test as a framework on Mac OS X. The bug causes
  1799. // GetTypeId< ::testing::Test>() to return different values depending
  1800. // on whether the call is from the Google Test framework itself or
  1801. // from user test code. GetTestTypeId() is guaranteed to always
  1802. // return the same value, as it always calls GetTypeId<>() from the
  1803. // gtest.cc, which is within the Google Test framework.
  1804. TypeId GetTestTypeId() {
  1805. return GetTypeId<Test>();
  1806. }
  1807. // The value of GetTestTypeId() as seen from within the Google Test
  1808. // library. This is solely for testing GetTestTypeId().
  1809. extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
  1810. // This predicate-formatter checks that 'results' contains a test part
  1811. // failure of the given type and that the failure message contains the
  1812. // given substring.
  1813. static AssertionResult HasOneFailure(const char* /* results_expr */,
  1814. const char* /* type_expr */,
  1815. const char* /* substr_expr */,
  1816. const TestPartResultArray& results,
  1817. TestPartResult::Type type,
  1818. const std::string& substr) {
  1819. const std::string expected(type == TestPartResult::kFatalFailure ?
  1820. "1 fatal failure" :
  1821. "1 non-fatal failure");
  1822. Message msg;
  1823. if (results.size() != 1) {
  1824. msg << "Expected: " << expected << "\n"
  1825. << " Actual: " << results.size() << " failures";
  1826. for (int i = 0; i < results.size(); i++) {
  1827. msg << "\n" << results.GetTestPartResult(i);
  1828. }
  1829. return AssertionFailure() << msg;
  1830. }
  1831. const TestPartResult& r = results.GetTestPartResult(0);
  1832. if (r.type() != type) {
  1833. return AssertionFailure() << "Expected: " << expected << "\n"
  1834. << " Actual:\n"
  1835. << r;
  1836. }
  1837. if (strstr(r.message(), substr.c_str()) == NULL) {
  1838. return AssertionFailure() << "Expected: " << expected << " containing \""
  1839. << substr << "\"\n"
  1840. << " Actual:\n"
  1841. << r;
  1842. }
  1843. return AssertionSuccess();
  1844. }
  1845. // The constructor of SingleFailureChecker remembers where to look up
  1846. // test part results, what type of failure we expect, and what
  1847. // substring the failure message should contain.
  1848. SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
  1849. TestPartResult::Type type,
  1850. const std::string& substr)
  1851. : results_(results), type_(type), substr_(substr) {}
  1852. // The destructor of SingleFailureChecker verifies that the given
  1853. // TestPartResultArray contains exactly one failure that has the given
  1854. // type and contains the given substring. If that's not the case, a
  1855. // non-fatal failure will be generated.
  1856. SingleFailureChecker::~SingleFailureChecker() {
  1857. EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
  1858. }
  1859. DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
  1860. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  1861. void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
  1862. const TestPartResult& result) {
  1863. unit_test_->current_test_result()->AddTestPartResult(result);
  1864. unit_test_->listeners()->repeater()->OnTestPartResult(result);
  1865. }
  1866. DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
  1867. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  1868. void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
  1869. const TestPartResult& result) {
  1870. unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
  1871. }
  1872. // Returns the global test part result reporter.
  1873. TestPartResultReporterInterface*
  1874. UnitTestImpl::GetGlobalTestPartResultReporter() {
  1875. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  1876. return global_test_part_result_repoter_;
  1877. }
  1878. // Sets the global test part result reporter.
  1879. void UnitTestImpl::SetGlobalTestPartResultReporter(
  1880. TestPartResultReporterInterface* reporter) {
  1881. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  1882. global_test_part_result_repoter_ = reporter;
  1883. }
  1884. // Returns the test part result reporter for the current thread.
  1885. TestPartResultReporterInterface*
  1886. UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
  1887. return per_thread_test_part_result_reporter_.get();
  1888. }
  1889. // Sets the test part result reporter for the current thread.
  1890. void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
  1891. TestPartResultReporterInterface* reporter) {
  1892. per_thread_test_part_result_reporter_.set(reporter);
  1893. }
  1894. // Gets the number of successful test cases.
  1895. int UnitTestImpl::successful_test_case_count() const {
  1896. return CountIf(test_cases_, TestCasePassed);
  1897. }
  1898. // Gets the number of failed test cases.
  1899. int UnitTestImpl::failed_test_case_count() const {
  1900. return CountIf(test_cases_, TestCaseFailed);
  1901. }
  1902. // Gets the number of all test cases.
  1903. int UnitTestImpl::total_test_case_count() const {
  1904. return static_cast<int>(test_cases_.size());
  1905. }
  1906. // Gets the number of all test cases that contain at least one test
  1907. // that should run.
  1908. int UnitTestImpl::test_case_to_run_count() const {
  1909. return CountIf(test_cases_, ShouldRunTestCase);
  1910. }
  1911. // Gets the number of successful tests.
  1912. int UnitTestImpl::successful_test_count() const {
  1913. return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
  1914. }
  1915. // Gets the number of failed tests.
  1916. int UnitTestImpl::failed_test_count() const {
  1917. return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
  1918. }
  1919. // Gets the number of disabled tests that will be reported in the XML report.
  1920. int UnitTestImpl::reportable_disabled_test_count() const {
  1921. return SumOverTestCaseList(test_cases_,
  1922. &TestCase::reportable_disabled_test_count);
  1923. }
  1924. // Gets the number of disabled tests.
  1925. int UnitTestImpl::disabled_test_count() const {
  1926. return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
  1927. }
  1928. // Gets the number of tests to be printed in the XML report.
  1929. int UnitTestImpl::reportable_test_count() const {
  1930. return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
  1931. }
  1932. // Gets the number of all tests.
  1933. int UnitTestImpl::total_test_count() const {
  1934. return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
  1935. }
  1936. // Gets the number of tests that should run.
  1937. int UnitTestImpl::test_to_run_count() const {
  1938. return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
  1939. }
  1940. // Returns the current OS stack trace as an std::string.
  1941. //
  1942. // The maximum number of stack frames to be included is specified by
  1943. // the gtest_stack_trace_depth flag. The skip_count parameter
  1944. // specifies the number of top frames to be skipped, which doesn't
  1945. // count against the number of frames to be included.
  1946. //
  1947. // For example, if Foo() calls Bar(), which in turn calls
  1948. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  1949. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  1950. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
  1951. return os_stack_trace_getter()->CurrentStackTrace(
  1952. static_cast<int>(GTEST_FLAG(stack_trace_depth)),
  1953. skip_count + 1
  1954. // Skips the user-specified number of frames plus this function
  1955. // itself.
  1956. ); // NOLINT
  1957. }
  1958. // Returns the current time in milliseconds.
  1959. TimeInMillis GetTimeInMillis() {
  1960. #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
  1961. // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
  1962. // http://analogous.blogspot.com/2005/04/epoch.html
  1963. const TimeInMillis kJavaEpochToWinFileTimeDelta =
  1964. static_cast<TimeInMillis>(116444736UL) * 100000UL;
  1965. const DWORD kTenthMicrosInMilliSecond = 10000;
  1966. SYSTEMTIME now_systime;
  1967. FILETIME now_filetime;
  1968. ULARGE_INTEGER now_int64;
  1969. // FIXME: Shouldn't this just use
  1970. // GetSystemTimeAsFileTime()?
  1971. GetSystemTime(&now_systime);
  1972. if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
  1973. now_int64.LowPart = now_filetime.dwLowDateTime;
  1974. now_int64.HighPart = now_filetime.dwHighDateTime;
  1975. now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
  1976. kJavaEpochToWinFileTimeDelta;
  1977. return now_int64.QuadPart;
  1978. }
  1979. return 0;
  1980. #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
  1981. __timeb64 now;
  1982. // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
  1983. // (deprecated function) there.
  1984. // FIXME: Use GetTickCount()? Or use
  1985. // SystemTimeToFileTime()
  1986. GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
  1987. _ftime64(&now);
  1988. GTEST_DISABLE_MSC_DEPRECATED_POP_()
  1989. return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
  1990. #elif GTEST_HAS_GETTIMEOFDAY_
  1991. struct timeval now;
  1992. gettimeofday(&now, NULL);
  1993. return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
  1994. #else
  1995. # error "Don't know how to get the current time on your system."
  1996. #endif
  1997. }
  1998. // Utilities
  1999. // class String.
  2000. #if GTEST_OS_WINDOWS_MOBILE
  2001. // Creates a UTF-16 wide string from the given ANSI string, allocating
  2002. // memory using new. The caller is responsible for deleting the return
  2003. // value using delete[]. Returns the wide string, or NULL if the
  2004. // input is NULL.
  2005. LPCWSTR String::AnsiToUtf16(const char* ansi) {
  2006. if (!ansi) return NULL;
  2007. const int length = strlen(ansi);
  2008. const int unicode_length =
  2009. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  2010. NULL, 0);
  2011. WCHAR* unicode = new WCHAR[unicode_length + 1];
  2012. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  2013. unicode, unicode_length);
  2014. unicode[unicode_length] = 0;
  2015. return unicode;
  2016. }
  2017. // Creates an ANSI string from the given wide string, allocating
  2018. // memory using new. The caller is responsible for deleting the return
  2019. // value using delete[]. Returns the ANSI string, or NULL if the
  2020. // input is NULL.
  2021. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
  2022. if (!utf16_str) return NULL;
  2023. const int ansi_length =
  2024. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  2025. NULL, 0, NULL, NULL);
  2026. char* ansi = new char[ansi_length + 1];
  2027. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  2028. ansi, ansi_length, NULL, NULL);
  2029. ansi[ansi_length] = 0;
  2030. return ansi;
  2031. }
  2032. #endif // GTEST_OS_WINDOWS_MOBILE
  2033. // Compares two C strings. Returns true iff they have the same content.
  2034. //
  2035. // Unlike strcmp(), this function can handle NULL argument(s). A NULL
  2036. // C string is considered different to any non-NULL C string,
  2037. // including the empty string.
  2038. bool String::CStringEquals(const char * lhs, const char * rhs) {
  2039. if ( lhs == NULL ) return rhs == NULL;
  2040. if ( rhs == NULL ) return false;
  2041. return strcmp(lhs, rhs) == 0;
  2042. }
  2043. #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  2044. // Converts an array of wide chars to a narrow string using the UTF-8
  2045. // encoding, and streams the result to the given Message object.
  2046. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
  2047. Message* msg) {
  2048. for (size_t i = 0; i != length; ) { // NOLINT
  2049. if (wstr[i] != L'\0') {
  2050. *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
  2051. while (i != length && wstr[i] != L'\0')
  2052. i++;
  2053. } else {
  2054. *msg << '\0';
  2055. i++;
  2056. }
  2057. }
  2058. }
  2059. #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  2060. void SplitString(const ::std::string& str, char delimiter,
  2061. ::std::vector< ::std::string>* dest) {
  2062. ::std::vector< ::std::string> parsed;
  2063. ::std::string::size_type pos = 0;
  2064. while (::testing::internal::AlwaysTrue()) {
  2065. const ::std::string::size_type colon = str.find(delimiter, pos);
  2066. if (colon == ::std::string::npos) {
  2067. parsed.push_back(str.substr(pos));
  2068. break;
  2069. } else {
  2070. parsed.push_back(str.substr(pos, colon - pos));
  2071. pos = colon + 1;
  2072. }
  2073. }
  2074. dest->swap(parsed);
  2075. }
  2076. } // namespace internal
  2077. // Constructs an empty Message.
  2078. // We allocate the stringstream separately because otherwise each use of
  2079. // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
  2080. // stack frame leading to huge stack frames in some cases; gcc does not reuse
  2081. // the stack space.
  2082. Message::Message() : ss_(new ::std::stringstream) {
  2083. // By default, we want there to be enough precision when printing
  2084. // a double to a Message.
  2085. *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
  2086. }
  2087. // These two overloads allow streaming a wide C string to a Message
  2088. // using the UTF-8 encoding.
  2089. Message& Message::operator <<(const wchar_t* wide_c_str) {
  2090. return *this << internal::String::ShowWideCString(wide_c_str);
  2091. }
  2092. Message& Message::operator <<(wchar_t* wide_c_str) {
  2093. return *this << internal::String::ShowWideCString(wide_c_str);
  2094. }
  2095. #if GTEST_HAS_STD_WSTRING
  2096. // Converts the given wide string to a narrow string using the UTF-8
  2097. // encoding, and streams the result to this Message object.
  2098. Message& Message::operator <<(const ::std::wstring& wstr) {
  2099. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  2100. return *this;
  2101. }
  2102. #endif // GTEST_HAS_STD_WSTRING
  2103. #if GTEST_HAS_GLOBAL_WSTRING
  2104. // Converts the given wide string to a narrow string using the UTF-8
  2105. // encoding, and streams the result to this Message object.
  2106. Message& Message::operator <<(const ::wstring& wstr) {
  2107. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  2108. return *this;
  2109. }
  2110. #endif // GTEST_HAS_GLOBAL_WSTRING
  2111. // Gets the text streamed to this object so far as an std::string.
  2112. // Each '\0' character in the buffer is replaced with "\\0".
  2113. std::string Message::GetString() const {
  2114. return internal::StringStreamToString(ss_.get());
  2115. }
  2116. // AssertionResult constructors.
  2117. // Used in EXPECT_TRUE/FALSE(assertion_result).
  2118. AssertionResult::AssertionResult(const AssertionResult& other)
  2119. : success_(other.success_),
  2120. message_(other.message_.get() != NULL ?
  2121. new ::std::string(*other.message_) :
  2122. static_cast< ::std::string*>(NULL)) {
  2123. }
  2124. // Swaps two AssertionResults.
  2125. void AssertionResult::swap(AssertionResult& other) {
  2126. using std::swap;
  2127. swap(success_, other.success_);
  2128. swap(message_, other.message_);
  2129. }
  2130. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  2131. AssertionResult AssertionResult::operator!() const {
  2132. AssertionResult negation(!success_);
  2133. if (message_.get() != NULL)
  2134. negation << *message_;
  2135. return negation;
  2136. }
  2137. // Makes a successful assertion result.
  2138. AssertionResult AssertionSuccess() {
  2139. return AssertionResult(true);
  2140. }
  2141. // Makes a failed assertion result.
  2142. AssertionResult AssertionFailure() {
  2143. return AssertionResult(false);
  2144. }
  2145. // Makes a failed assertion result with the given failure message.
  2146. // Deprecated; use AssertionFailure() << message.
  2147. AssertionResult AssertionFailure(const Message& message) {
  2148. return AssertionFailure() << message;
  2149. }
  2150. namespace internal {
  2151. namespace edit_distance {
  2152. std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
  2153. const std::vector<size_t>& right) {
  2154. std::vector<std::vector<double> > costs(
  2155. left.size() + 1, std::vector<double>(right.size() + 1));
  2156. std::vector<std::vector<EditType> > best_move(
  2157. left.size() + 1, std::vector<EditType>(right.size() + 1));
  2158. // Populate for empty right.
  2159. for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
  2160. costs[l_i][0] = static_cast<double>(l_i);
  2161. best_move[l_i][0] = kRemove;
  2162. }
  2163. // Populate for empty left.
  2164. for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
  2165. costs[0][r_i] = static_cast<double>(r_i);
  2166. best_move[0][r_i] = kAdd;
  2167. }
  2168. for (size_t l_i = 0; l_i < left.size(); ++l_i) {
  2169. for (size_t r_i = 0; r_i < right.size(); ++r_i) {
  2170. if (left[l_i] == right[r_i]) {
  2171. // Found a match. Consume it.
  2172. costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
  2173. best_move[l_i + 1][r_i + 1] = kMatch;
  2174. continue;
  2175. }
  2176. const double add = costs[l_i + 1][r_i];
  2177. const double remove = costs[l_i][r_i + 1];
  2178. const double replace = costs[l_i][r_i];
  2179. if (add < remove && add < replace) {
  2180. costs[l_i + 1][r_i + 1] = add + 1;
  2181. best_move[l_i + 1][r_i + 1] = kAdd;
  2182. } else if (remove < add && remove < replace) {
  2183. costs[l_i + 1][r_i + 1] = remove + 1;
  2184. best_move[l_i + 1][r_i + 1] = kRemove;
  2185. } else {
  2186. // We make replace a little more expensive than add/remove to lower
  2187. // their priority.
  2188. costs[l_i + 1][r_i + 1] = replace + 1.00001;
  2189. best_move[l_i + 1][r_i + 1] = kReplace;
  2190. }
  2191. }
  2192. }
  2193. // Reconstruct the best path. We do it in reverse order.
  2194. std::vector<EditType> best_path;
  2195. for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
  2196. EditType move = best_move[l_i][r_i];
  2197. best_path.push_back(move);
  2198. l_i -= move != kAdd;
  2199. r_i -= move != kRemove;
  2200. }
  2201. std::reverse(best_path.begin(), best_path.end());
  2202. return best_path;
  2203. }
  2204. namespace {
  2205. // Helper class to convert string into ids with deduplication.
  2206. class InternalStrings {
  2207. public:
  2208. size_t GetId(const std::string& str) {
  2209. IdMap::iterator it = ids_.find(str);
  2210. if (it != ids_.end()) return it->second;
  2211. size_t id = ids_.size();
  2212. return ids_[str] = id;
  2213. }
  2214. private:
  2215. typedef std::map<std::string, size_t> IdMap;
  2216. IdMap ids_;
  2217. };
  2218. } // namespace
  2219. std::vector<EditType> CalculateOptimalEdits(
  2220. const std::vector<std::string>& left,
  2221. const std::vector<std::string>& right) {
  2222. std::vector<size_t> left_ids, right_ids;
  2223. {
  2224. InternalStrings intern_table;
  2225. for (size_t i = 0; i < left.size(); ++i) {
  2226. left_ids.push_back(intern_table.GetId(left[i]));
  2227. }
  2228. for (size_t i = 0; i < right.size(); ++i) {
  2229. right_ids.push_back(intern_table.GetId(right[i]));
  2230. }
  2231. }
  2232. return CalculateOptimalEdits(left_ids, right_ids);
  2233. }
  2234. namespace {
  2235. // Helper class that holds the state for one hunk and prints it out to the
  2236. // stream.
  2237. // It reorders adds/removes when possible to group all removes before all
  2238. // adds. It also adds the hunk header before printint into the stream.
  2239. class Hunk {
  2240. public:
  2241. Hunk(size_t left_start, size_t right_start)
  2242. : left_start_(left_start),
  2243. right_start_(right_start),
  2244. adds_(),
  2245. removes_(),
  2246. common_() {}
  2247. void PushLine(char edit, const char* line) {
  2248. switch (edit) {
  2249. case ' ':
  2250. ++common_;
  2251. FlushEdits();
  2252. hunk_.push_back(std::make_pair(' ', line));
  2253. break;
  2254. case '-':
  2255. ++removes_;
  2256. hunk_removes_.push_back(std::make_pair('-', line));
  2257. break;
  2258. case '+':
  2259. ++adds_;
  2260. hunk_adds_.push_back(std::make_pair('+', line));
  2261. break;
  2262. }
  2263. }
  2264. void PrintTo(std::ostream* os) {
  2265. PrintHeader(os);
  2266. FlushEdits();
  2267. for (std::list<std::pair<char, const char*> >::const_iterator it =
  2268. hunk_.begin();
  2269. it != hunk_.end(); ++it) {
  2270. *os << it->first << it->second << "\n";
  2271. }
  2272. }
  2273. bool has_edits() const { return adds_ || removes_; }
  2274. private:
  2275. void FlushEdits() {
  2276. hunk_.splice(hunk_.end(), hunk_removes_);
  2277. hunk_.splice(hunk_.end(), hunk_adds_);
  2278. }
  2279. // Print a unified diff header for one hunk.
  2280. // The format is
  2281. // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
  2282. // where the left/right parts are omitted if unnecessary.
  2283. void PrintHeader(std::ostream* ss) const {
  2284. *ss << "@@ ";
  2285. if (removes_) {
  2286. *ss << "-" << left_start_ << "," << (removes_ + common_);
  2287. }
  2288. if (removes_ && adds_) {
  2289. *ss << " ";
  2290. }
  2291. if (adds_) {
  2292. *ss << "+" << right_start_ << "," << (adds_ + common_);
  2293. }
  2294. *ss << " @@\n";
  2295. }
  2296. size_t left_start_, right_start_;
  2297. size_t adds_, removes_, common_;
  2298. std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
  2299. };
  2300. } // namespace
  2301. // Create a list of diff hunks in Unified diff format.
  2302. // Each hunk has a header generated by PrintHeader above plus a body with
  2303. // lines prefixed with ' ' for no change, '-' for deletion and '+' for
  2304. // addition.
  2305. // 'context' represents the desired unchanged prefix/suffix around the diff.
  2306. // If two hunks are close enough that their contexts overlap, then they are
  2307. // joined into one hunk.
  2308. std::string CreateUnifiedDiff(const std::vector<std::string>& left,
  2309. const std::vector<std::string>& right,
  2310. size_t context) {
  2311. const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
  2312. size_t l_i = 0, r_i = 0, edit_i = 0;
  2313. std::stringstream ss;
  2314. while (edit_i < edits.size()) {
  2315. // Find first edit.
  2316. while (edit_i < edits.size() && edits[edit_i] == kMatch) {
  2317. ++l_i;
  2318. ++r_i;
  2319. ++edit_i;
  2320. }
  2321. // Find the first line to include in the hunk.
  2322. const size_t prefix_context = std::min(l_i, context);
  2323. Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
  2324. for (size_t i = prefix_context; i > 0; --i) {
  2325. hunk.PushLine(' ', left[l_i - i].c_str());
  2326. }
  2327. // Iterate the edits until we found enough suffix for the hunk or the input
  2328. // is over.
  2329. size_t n_suffix = 0;
  2330. for (; edit_i < edits.size(); ++edit_i) {
  2331. if (n_suffix >= context) {
  2332. // Continue only if the next hunk is very close.
  2333. std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
  2334. while (it != edits.end() && *it == kMatch) ++it;
  2335. if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
  2336. // There is no next edit or it is too far away.
  2337. break;
  2338. }
  2339. }
  2340. EditType edit = edits[edit_i];
  2341. // Reset count when a non match is found.
  2342. n_suffix = edit == kMatch ? n_suffix + 1 : 0;
  2343. if (edit == kMatch || edit == kRemove || edit == kReplace) {
  2344. hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
  2345. }
  2346. if (edit == kAdd || edit == kReplace) {
  2347. hunk.PushLine('+', right[r_i].c_str());
  2348. }
  2349. // Advance indices, depending on edit type.
  2350. l_i += edit != kAdd;
  2351. r_i += edit != kRemove;
  2352. }
  2353. if (!hunk.has_edits()) {
  2354. // We are done. We don't want this hunk.
  2355. break;
  2356. }
  2357. hunk.PrintTo(&ss);
  2358. }
  2359. return ss.str();
  2360. }
  2361. } // namespace edit_distance
  2362. namespace {
  2363. // The string representation of the values received in EqFailure() are already
  2364. // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
  2365. // characters the same.
  2366. std::vector<std::string> SplitEscapedString(const std::string& str) {
  2367. std::vector<std::string> lines;
  2368. size_t start = 0, end = str.size();
  2369. if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
  2370. ++start;
  2371. --end;
  2372. }
  2373. bool escaped = false;
  2374. for (size_t i = start; i + 1 < end; ++i) {
  2375. if (escaped) {
  2376. escaped = false;
  2377. if (str[i] == 'n') {
  2378. lines.push_back(str.substr(start, i - start - 1));
  2379. start = i + 1;
  2380. }
  2381. } else {
  2382. escaped = str[i] == '\\';
  2383. }
  2384. }
  2385. lines.push_back(str.substr(start, end - start));
  2386. return lines;
  2387. }
  2388. } // namespace
  2389. // Constructs and returns the message for an equality assertion
  2390. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  2391. //
  2392. // The first four parameters are the expressions used in the assertion
  2393. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  2394. // where foo is 5 and bar is 6, we have:
  2395. //
  2396. // lhs_expression: "foo"
  2397. // rhs_expression: "bar"
  2398. // lhs_value: "5"
  2399. // rhs_value: "6"
  2400. //
  2401. // The ignoring_case parameter is true iff the assertion is a
  2402. // *_STRCASEEQ*. When it's true, the string "Ignoring case" will
  2403. // be inserted into the message.
  2404. AssertionResult EqFailure(const char* lhs_expression,
  2405. const char* rhs_expression,
  2406. const std::string& lhs_value,
  2407. const std::string& rhs_value,
  2408. bool ignoring_case) {
  2409. Message msg;
  2410. msg << "Expected equality of these values:";
  2411. msg << "\n " << lhs_expression;
  2412. if (lhs_value != lhs_expression) {
  2413. msg << "\n Which is: " << lhs_value;
  2414. }
  2415. msg << "\n " << rhs_expression;
  2416. if (rhs_value != rhs_expression) {
  2417. msg << "\n Which is: " << rhs_value;
  2418. }
  2419. if (ignoring_case) {
  2420. msg << "\nIgnoring case";
  2421. }
  2422. if (!lhs_value.empty() && !rhs_value.empty()) {
  2423. const std::vector<std::string> lhs_lines =
  2424. SplitEscapedString(lhs_value);
  2425. const std::vector<std::string> rhs_lines =
  2426. SplitEscapedString(rhs_value);
  2427. if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
  2428. msg << "\nWith diff:\n"
  2429. << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
  2430. }
  2431. }
  2432. return AssertionFailure() << msg;
  2433. }
  2434. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  2435. std::string GetBoolAssertionFailureMessage(
  2436. const AssertionResult& assertion_result,
  2437. const char* expression_text,
  2438. const char* actual_predicate_value,
  2439. const char* expected_predicate_value) {
  2440. const char* actual_message = assertion_result.message();
  2441. Message msg;
  2442. msg << "Value of: " << expression_text
  2443. << "\n Actual: " << actual_predicate_value;
  2444. if (actual_message[0] != '\0')
  2445. msg << " (" << actual_message << ")";
  2446. msg << "\nExpected: " << expected_predicate_value;
  2447. return msg.GetString();
  2448. }
  2449. // Helper function for implementing ASSERT_NEAR.
  2450. AssertionResult DoubleNearPredFormat(const char* expr1,
  2451. const char* expr2,
  2452. const char* abs_error_expr,
  2453. double val1,
  2454. double val2,
  2455. double abs_error) {
  2456. const double diff = fabs(val1 - val2);
  2457. if (diff <= abs_error) return AssertionSuccess();
  2458. // FIXME: do not print the value of an expression if it's
  2459. // already a literal.
  2460. return AssertionFailure()
  2461. << "The difference between " << expr1 << " and " << expr2
  2462. << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
  2463. << expr1 << " evaluates to " << val1 << ",\n"
  2464. << expr2 << " evaluates to " << val2 << ", and\n"
  2465. << abs_error_expr << " evaluates to " << abs_error << ".";
  2466. }
  2467. // Helper template for implementing FloatLE() and DoubleLE().
  2468. template <typename RawType>
  2469. AssertionResult FloatingPointLE(const char* expr1,
  2470. const char* expr2,
  2471. RawType val1,
  2472. RawType val2) {
  2473. // Returns success if val1 is less than val2,
  2474. if (val1 < val2) {
  2475. return AssertionSuccess();
  2476. }
  2477. // or if val1 is almost equal to val2.
  2478. const FloatingPoint<RawType> lhs(val1), rhs(val2);
  2479. if (lhs.AlmostEquals(rhs)) {
  2480. return AssertionSuccess();
  2481. }
  2482. // Note that the above two checks will both fail if either val1 or
  2483. // val2 is NaN, as the IEEE floating-point standard requires that
  2484. // any predicate involving a NaN must return false.
  2485. ::std::stringstream val1_ss;
  2486. val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2487. << val1;
  2488. ::std::stringstream val2_ss;
  2489. val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2490. << val2;
  2491. return AssertionFailure()
  2492. << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
  2493. << " Actual: " << StringStreamToString(&val1_ss) << " vs "
  2494. << StringStreamToString(&val2_ss);
  2495. }
  2496. } // namespace internal
  2497. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2498. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2499. AssertionResult FloatLE(const char* expr1, const char* expr2,
  2500. float val1, float val2) {
  2501. return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
  2502. }
  2503. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2504. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2505. AssertionResult DoubleLE(const char* expr1, const char* expr2,
  2506. double val1, double val2) {
  2507. return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
  2508. }
  2509. namespace internal {
  2510. // The helper function for {ASSERT|EXPECT}_EQ with int or enum
  2511. // arguments.
  2512. AssertionResult CmpHelperEQ(const char* lhs_expression,
  2513. const char* rhs_expression,
  2514. BiggestInt lhs,
  2515. BiggestInt rhs) {
  2516. if (lhs == rhs) {
  2517. return AssertionSuccess();
  2518. }
  2519. return EqFailure(lhs_expression,
  2520. rhs_expression,
  2521. FormatForComparisonFailureMessage(lhs, rhs),
  2522. FormatForComparisonFailureMessage(rhs, lhs),
  2523. false);
  2524. }
  2525. // A macro for implementing the helper functions needed to implement
  2526. // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
  2527. // just to avoid copy-and-paste of similar code.
  2528. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
  2529. AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
  2530. BiggestInt val1, BiggestInt val2) {\
  2531. if (val1 op val2) {\
  2532. return AssertionSuccess();\
  2533. } else {\
  2534. return AssertionFailure() \
  2535. << "Expected: (" << expr1 << ") " #op " (" << expr2\
  2536. << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
  2537. << " vs " << FormatForComparisonFailureMessage(val2, val1);\
  2538. }\
  2539. }
  2540. // Implements the helper function for {ASSERT|EXPECT}_NE with int or
  2541. // enum arguments.
  2542. GTEST_IMPL_CMP_HELPER_(NE, !=)
  2543. // Implements the helper function for {ASSERT|EXPECT}_LE with int or
  2544. // enum arguments.
  2545. GTEST_IMPL_CMP_HELPER_(LE, <=)
  2546. // Implements the helper function for {ASSERT|EXPECT}_LT with int or
  2547. // enum arguments.
  2548. GTEST_IMPL_CMP_HELPER_(LT, < )
  2549. // Implements the helper function for {ASSERT|EXPECT}_GE with int or
  2550. // enum arguments.
  2551. GTEST_IMPL_CMP_HELPER_(GE, >=)
  2552. // Implements the helper function for {ASSERT|EXPECT}_GT with int or
  2553. // enum arguments.
  2554. GTEST_IMPL_CMP_HELPER_(GT, > )
  2555. #undef GTEST_IMPL_CMP_HELPER_
  2556. // The helper function for {ASSERT|EXPECT}_STREQ.
  2557. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  2558. const char* rhs_expression,
  2559. const char* lhs,
  2560. const char* rhs) {
  2561. if (String::CStringEquals(lhs, rhs)) {
  2562. return AssertionSuccess();
  2563. }
  2564. return EqFailure(lhs_expression,
  2565. rhs_expression,
  2566. PrintToString(lhs),
  2567. PrintToString(rhs),
  2568. false);
  2569. }
  2570. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  2571. AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
  2572. const char* rhs_expression,
  2573. const char* lhs,
  2574. const char* rhs) {
  2575. if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
  2576. return AssertionSuccess();
  2577. }
  2578. return EqFailure(lhs_expression,
  2579. rhs_expression,
  2580. PrintToString(lhs),
  2581. PrintToString(rhs),
  2582. true);
  2583. }
  2584. // The helper function for {ASSERT|EXPECT}_STRNE.
  2585. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  2586. const char* s2_expression,
  2587. const char* s1,
  2588. const char* s2) {
  2589. if (!String::CStringEquals(s1, s2)) {
  2590. return AssertionSuccess();
  2591. } else {
  2592. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  2593. << s2_expression << "), actual: \""
  2594. << s1 << "\" vs \"" << s2 << "\"";
  2595. }
  2596. }
  2597. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  2598. AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  2599. const char* s2_expression,
  2600. const char* s1,
  2601. const char* s2) {
  2602. if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
  2603. return AssertionSuccess();
  2604. } else {
  2605. return AssertionFailure()
  2606. << "Expected: (" << s1_expression << ") != ("
  2607. << s2_expression << ") (ignoring case), actual: \""
  2608. << s1 << "\" vs \"" << s2 << "\"";
  2609. }
  2610. }
  2611. } // namespace internal
  2612. namespace {
  2613. // Helper functions for implementing IsSubString() and IsNotSubstring().
  2614. // This group of overloaded functions return true iff needle is a
  2615. // substring of haystack. NULL is considered a substring of itself
  2616. // only.
  2617. bool IsSubstringPred(const char* needle, const char* haystack) {
  2618. if (needle == NULL || haystack == NULL)
  2619. return needle == haystack;
  2620. return strstr(haystack, needle) != NULL;
  2621. }
  2622. bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
  2623. if (needle == NULL || haystack == NULL)
  2624. return needle == haystack;
  2625. return wcsstr(haystack, needle) != NULL;
  2626. }
  2627. // StringType here can be either ::std::string or ::std::wstring.
  2628. template <typename StringType>
  2629. bool IsSubstringPred(const StringType& needle,
  2630. const StringType& haystack) {
  2631. return haystack.find(needle) != StringType::npos;
  2632. }
  2633. // This function implements either IsSubstring() or IsNotSubstring(),
  2634. // depending on the value of the expected_to_be_substring parameter.
  2635. // StringType here can be const char*, const wchar_t*, ::std::string,
  2636. // or ::std::wstring.
  2637. template <typename StringType>
  2638. AssertionResult IsSubstringImpl(
  2639. bool expected_to_be_substring,
  2640. const char* needle_expr, const char* haystack_expr,
  2641. const StringType& needle, const StringType& haystack) {
  2642. if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
  2643. return AssertionSuccess();
  2644. const bool is_wide_string = sizeof(needle[0]) > 1;
  2645. const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
  2646. return AssertionFailure()
  2647. << "Value of: " << needle_expr << "\n"
  2648. << " Actual: " << begin_string_quote << needle << "\"\n"
  2649. << "Expected: " << (expected_to_be_substring ? "" : "not ")
  2650. << "a substring of " << haystack_expr << "\n"
  2651. << "Which is: " << begin_string_quote << haystack << "\"";
  2652. }
  2653. } // namespace
  2654. // IsSubstring() and IsNotSubstring() check whether needle is a
  2655. // substring of haystack (NULL is considered a substring of itself
  2656. // only), and return an appropriate error message when they fail.
  2657. AssertionResult IsSubstring(
  2658. const char* needle_expr, const char* haystack_expr,
  2659. const char* needle, const char* haystack) {
  2660. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2661. }
  2662. AssertionResult IsSubstring(
  2663. const char* needle_expr, const char* haystack_expr,
  2664. const wchar_t* needle, const wchar_t* haystack) {
  2665. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2666. }
  2667. AssertionResult IsNotSubstring(
  2668. const char* needle_expr, const char* haystack_expr,
  2669. const char* needle, const char* haystack) {
  2670. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2671. }
  2672. AssertionResult IsNotSubstring(
  2673. const char* needle_expr, const char* haystack_expr,
  2674. const wchar_t* needle, const wchar_t* haystack) {
  2675. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2676. }
  2677. AssertionResult IsSubstring(
  2678. const char* needle_expr, const char* haystack_expr,
  2679. const ::std::string& needle, const ::std::string& haystack) {
  2680. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2681. }
  2682. AssertionResult IsNotSubstring(
  2683. const char* needle_expr, const char* haystack_expr,
  2684. const ::std::string& needle, const ::std::string& haystack) {
  2685. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2686. }
  2687. #if GTEST_HAS_STD_WSTRING
  2688. AssertionResult IsSubstring(
  2689. const char* needle_expr, const char* haystack_expr,
  2690. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2691. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2692. }
  2693. AssertionResult IsNotSubstring(
  2694. const char* needle_expr, const char* haystack_expr,
  2695. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2696. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2697. }
  2698. #endif // GTEST_HAS_STD_WSTRING
  2699. namespace internal {
  2700. #if GTEST_OS_WINDOWS
  2701. namespace {
  2702. // Helper function for IsHRESULT{SuccessFailure} predicates
  2703. AssertionResult HRESULTFailureHelper(const char* expr,
  2704. const char* expected,
  2705. long hr) { // NOLINT
  2706. # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
  2707. // Windows CE doesn't support FormatMessage.
  2708. const char error_text[] = "";
  2709. # else
  2710. // Looks up the human-readable system message for the HRESULT code
  2711. // and since we're not passing any params to FormatMessage, we don't
  2712. // want inserts expanded.
  2713. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
  2714. FORMAT_MESSAGE_IGNORE_INSERTS;
  2715. const DWORD kBufSize = 4096;
  2716. // Gets the system's human readable message string for this HRESULT.
  2717. char error_text[kBufSize] = { '\0' };
  2718. DWORD message_length = ::FormatMessageA(kFlags,
  2719. 0, // no source, we're asking system
  2720. hr, // the error
  2721. 0, // no line width restrictions
  2722. error_text, // output buffer
  2723. kBufSize, // buf size
  2724. NULL); // no arguments for inserts
  2725. // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
  2726. for (; message_length && IsSpace(error_text[message_length - 1]);
  2727. --message_length) {
  2728. error_text[message_length - 1] = '\0';
  2729. }
  2730. # endif // GTEST_OS_WINDOWS_MOBILE
  2731. const std::string error_hex("0x" + String::FormatHexInt(hr));
  2732. return ::testing::AssertionFailure()
  2733. << "Expected: " << expr << " " << expected << ".\n"
  2734. << " Actual: " << error_hex << " " << error_text << "\n";
  2735. }
  2736. } // namespace
  2737. AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
  2738. if (SUCCEEDED(hr)) {
  2739. return AssertionSuccess();
  2740. }
  2741. return HRESULTFailureHelper(expr, "succeeds", hr);
  2742. }
  2743. AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
  2744. if (FAILED(hr)) {
  2745. return AssertionSuccess();
  2746. }
  2747. return HRESULTFailureHelper(expr, "fails", hr);
  2748. }
  2749. #endif // GTEST_OS_WINDOWS
  2750. // Utility functions for encoding Unicode text (wide strings) in
  2751. // UTF-8.
  2752. // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
  2753. // like this:
  2754. //
  2755. // Code-point length Encoding
  2756. // 0 - 7 bits 0xxxxxxx
  2757. // 8 - 11 bits 110xxxxx 10xxxxxx
  2758. // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
  2759. // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  2760. // The maximum code-point a one-byte UTF-8 sequence can represent.
  2761. const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
  2762. // The maximum code-point a two-byte UTF-8 sequence can represent.
  2763. const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
  2764. // The maximum code-point a three-byte UTF-8 sequence can represent.
  2765. const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
  2766. // The maximum code-point a four-byte UTF-8 sequence can represent.
  2767. const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
  2768. // Chops off the n lowest bits from a bit pattern. Returns the n
  2769. // lowest bits. As a side effect, the original bit pattern will be
  2770. // shifted to the right by n bits.
  2771. inline UInt32 ChopLowBits(UInt32* bits, int n) {
  2772. const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
  2773. *bits >>= n;
  2774. return low_bits;
  2775. }
  2776. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  2777. // code_point parameter is of type UInt32 because wchar_t may not be
  2778. // wide enough to contain a code point.
  2779. // If the code_point is not a valid Unicode code point
  2780. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  2781. // to "(Invalid Unicode 0xXXXXXXXX)".
  2782. std::string CodePointToUtf8(UInt32 code_point) {
  2783. if (code_point > kMaxCodePoint4) {
  2784. return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
  2785. }
  2786. char str[5]; // Big enough for the largest valid code point.
  2787. if (code_point <= kMaxCodePoint1) {
  2788. str[1] = '\0';
  2789. str[0] = static_cast<char>(code_point); // 0xxxxxxx
  2790. } else if (code_point <= kMaxCodePoint2) {
  2791. str[2] = '\0';
  2792. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2793. str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
  2794. } else if (code_point <= kMaxCodePoint3) {
  2795. str[3] = '\0';
  2796. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2797. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2798. str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
  2799. } else { // code_point <= kMaxCodePoint4
  2800. str[4] = '\0';
  2801. str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2802. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2803. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2804. str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
  2805. }
  2806. return str;
  2807. }
  2808. // The following two functions only make sense if the system
  2809. // uses UTF-16 for wide string encoding. All supported systems
  2810. // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
  2811. // Determines if the arguments constitute UTF-16 surrogate pair
  2812. // and thus should be combined into a single Unicode code point
  2813. // using CreateCodePointFromUtf16SurrogatePair.
  2814. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
  2815. return sizeof(wchar_t) == 2 &&
  2816. (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
  2817. }
  2818. // Creates a Unicode code point from UTF16 surrogate pair.
  2819. inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
  2820. wchar_t second) {
  2821. const UInt32 mask = (1 << 10) - 1;
  2822. return (sizeof(wchar_t) == 2) ?
  2823. (((first & mask) << 10) | (second & mask)) + 0x10000 :
  2824. // This function should not be called when the condition is
  2825. // false, but we provide a sensible default in case it is.
  2826. static_cast<UInt32>(first);
  2827. }
  2828. // Converts a wide string to a narrow string in UTF-8 encoding.
  2829. // The wide string is assumed to have the following encoding:
  2830. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
  2831. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  2832. // Parameter str points to a null-terminated wide string.
  2833. // Parameter num_chars may additionally limit the number
  2834. // of wchar_t characters processed. -1 is used when the entire string
  2835. // should be processed.
  2836. // If the string contains code points that are not valid Unicode code points
  2837. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  2838. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  2839. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  2840. // will be encoded as individual Unicode characters from Basic Normal Plane.
  2841. std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
  2842. if (num_chars == -1)
  2843. num_chars = static_cast<int>(wcslen(str));
  2844. ::std::stringstream stream;
  2845. for (int i = 0; i < num_chars; ++i) {
  2846. UInt32 unicode_code_point;
  2847. if (str[i] == L'\0') {
  2848. break;
  2849. } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
  2850. unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
  2851. str[i + 1]);
  2852. i++;
  2853. } else {
  2854. unicode_code_point = static_cast<UInt32>(str[i]);
  2855. }
  2856. stream << CodePointToUtf8(unicode_code_point);
  2857. }
  2858. return StringStreamToString(&stream);
  2859. }
  2860. // Converts a wide C string to an std::string using the UTF-8 encoding.
  2861. // NULL will be converted to "(null)".
  2862. std::string String::ShowWideCString(const wchar_t * wide_c_str) {
  2863. if (wide_c_str == NULL) return "(null)";
  2864. return internal::WideStringToUtf8(wide_c_str, -1);
  2865. }
  2866. // Compares two wide C strings. Returns true iff they have the same
  2867. // content.
  2868. //
  2869. // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
  2870. // C string is considered different to any non-NULL C string,
  2871. // including the empty string.
  2872. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
  2873. if (lhs == NULL) return rhs == NULL;
  2874. if (rhs == NULL) return false;
  2875. return wcscmp(lhs, rhs) == 0;
  2876. }
  2877. // Helper function for *_STREQ on wide strings.
  2878. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  2879. const char* rhs_expression,
  2880. const wchar_t* lhs,
  2881. const wchar_t* rhs) {
  2882. if (String::WideCStringEquals(lhs, rhs)) {
  2883. return AssertionSuccess();
  2884. }
  2885. return EqFailure(lhs_expression,
  2886. rhs_expression,
  2887. PrintToString(lhs),
  2888. PrintToString(rhs),
  2889. false);
  2890. }
  2891. // Helper function for *_STRNE on wide strings.
  2892. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  2893. const char* s2_expression,
  2894. const wchar_t* s1,
  2895. const wchar_t* s2) {
  2896. if (!String::WideCStringEquals(s1, s2)) {
  2897. return AssertionSuccess();
  2898. }
  2899. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  2900. << s2_expression << "), actual: "
  2901. << PrintToString(s1)
  2902. << " vs " << PrintToString(s2);
  2903. }
  2904. // Compares two C strings, ignoring case. Returns true iff they have
  2905. // the same content.
  2906. //
  2907. // Unlike strcasecmp(), this function can handle NULL argument(s). A
  2908. // NULL C string is considered different to any non-NULL C string,
  2909. // including the empty string.
  2910. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
  2911. if (lhs == NULL)
  2912. return rhs == NULL;
  2913. if (rhs == NULL)
  2914. return false;
  2915. return posix::StrCaseCmp(lhs, rhs) == 0;
  2916. }
  2917. // Compares two wide C strings, ignoring case. Returns true iff they
  2918. // have the same content.
  2919. //
  2920. // Unlike wcscasecmp(), this function can handle NULL argument(s).
  2921. // A NULL C string is considered different to any non-NULL wide C string,
  2922. // including the empty string.
  2923. // NB: The implementations on different platforms slightly differ.
  2924. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  2925. // environment variable. On GNU platform this method uses wcscasecmp
  2926. // which compares according to LC_CTYPE category of the current locale.
  2927. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  2928. // current locale.
  2929. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  2930. const wchar_t* rhs) {
  2931. if (lhs == NULL) return rhs == NULL;
  2932. if (rhs == NULL) return false;
  2933. #if GTEST_OS_WINDOWS
  2934. return _wcsicmp(lhs, rhs) == 0;
  2935. #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
  2936. return wcscasecmp(lhs, rhs) == 0;
  2937. #else
  2938. // Android, Mac OS X and Cygwin don't define wcscasecmp.
  2939. // Other unknown OSes may not define it either.
  2940. wint_t left, right;
  2941. do {
  2942. left = towlower(*lhs++);
  2943. right = towlower(*rhs++);
  2944. } while (left && left == right);
  2945. return left == right;
  2946. #endif // OS selector
  2947. }
  2948. // Returns true iff str ends with the given suffix, ignoring case.
  2949. // Any string is considered to end with an empty suffix.
  2950. bool String::EndsWithCaseInsensitive(
  2951. const std::string& str, const std::string& suffix) {
  2952. const size_t str_len = str.length();
  2953. const size_t suffix_len = suffix.length();
  2954. return (str_len >= suffix_len) &&
  2955. CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
  2956. suffix.c_str());
  2957. }
  2958. // Formats an int value as "%02d".
  2959. std::string String::FormatIntWidth2(int value) {
  2960. std::stringstream ss;
  2961. ss << std::setfill('0') << std::setw(2) << value;
  2962. return ss.str();
  2963. }
  2964. // Formats an int value as "%X".
  2965. std::string String::FormatHexInt(int value) {
  2966. std::stringstream ss;
  2967. ss << std::hex << std::uppercase << value;
  2968. return ss.str();
  2969. }
  2970. // Formats a byte as "%02X".
  2971. std::string String::FormatByte(unsigned char value) {
  2972. std::stringstream ss;
  2973. ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
  2974. << static_cast<unsigned int>(value);
  2975. return ss.str();
  2976. }
  2977. // Converts the buffer in a stringstream to an std::string, converting NUL
  2978. // bytes to "\\0" along the way.
  2979. std::string StringStreamToString(::std::stringstream* ss) {
  2980. const ::std::string& str = ss->str();
  2981. const char* const start = str.c_str();
  2982. const char* const end = start + str.length();
  2983. std::string result;
  2984. result.reserve(2 * (end - start));
  2985. for (const char* ch = start; ch != end; ++ch) {
  2986. if (*ch == '\0') {
  2987. result += "\\0"; // Replaces NUL with "\\0";
  2988. } else {
  2989. result += *ch;
  2990. }
  2991. }
  2992. return result;
  2993. }
  2994. // Appends the user-supplied message to the Google-Test-generated message.
  2995. std::string AppendUserMessage(const std::string& gtest_msg,
  2996. const Message& user_msg) {
  2997. // Appends the user message if it's non-empty.
  2998. const std::string user_msg_string = user_msg.GetString();
  2999. if (user_msg_string.empty()) {
  3000. return gtest_msg;
  3001. }
  3002. return gtest_msg + "\n" + user_msg_string;
  3003. }
  3004. } // namespace internal
  3005. // class TestResult
  3006. // Creates an empty TestResult.
  3007. TestResult::TestResult()
  3008. : death_test_count_(0),
  3009. elapsed_time_(0) {
  3010. }
  3011. // D'tor.
  3012. TestResult::~TestResult() {
  3013. }
  3014. // Returns the i-th test part result among all the results. i can
  3015. // range from 0 to total_part_count() - 1. If i is not in that range,
  3016. // aborts the program.
  3017. const TestPartResult& TestResult::GetTestPartResult(int i) const {
  3018. if (i < 0 || i >= total_part_count())
  3019. internal::posix::Abort();
  3020. return test_part_results_.at(i);
  3021. }
  3022. // Returns the i-th test property. i can range from 0 to
  3023. // test_property_count() - 1. If i is not in that range, aborts the
  3024. // program.
  3025. const TestProperty& TestResult::GetTestProperty(int i) const {
  3026. if (i < 0 || i >= test_property_count())
  3027. internal::posix::Abort();
  3028. return test_properties_.at(i);
  3029. }
  3030. // Clears the test part results.
  3031. void TestResult::ClearTestPartResults() {
  3032. test_part_results_.clear();
  3033. }
  3034. // Adds a test part result to the list.
  3035. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
  3036. test_part_results_.push_back(test_part_result);
  3037. }
  3038. // Adds a test property to the list. If a property with the same key as the
  3039. // supplied property is already represented, the value of this test_property
  3040. // replaces the old value for that key.
  3041. void TestResult::RecordProperty(const std::string& xml_element,
  3042. const TestProperty& test_property) {
  3043. if (!ValidateTestProperty(xml_element, test_property)) {
  3044. return;
  3045. }
  3046. internal::MutexLock lock(&test_properites_mutex_);
  3047. const std::vector<TestProperty>::iterator property_with_matching_key =
  3048. std::find_if(test_properties_.begin(), test_properties_.end(),
  3049. internal::TestPropertyKeyIs(test_property.key()));
  3050. if (property_with_matching_key == test_properties_.end()) {
  3051. test_properties_.push_back(test_property);
  3052. return;
  3053. }
  3054. property_with_matching_key->SetValue(test_property.value());
  3055. }
  3056. // The list of reserved attributes used in the <testsuites> element of XML
  3057. // output.
  3058. static const char* const kReservedTestSuitesAttributes[] = {
  3059. "disabled",
  3060. "errors",
  3061. "failures",
  3062. "name",
  3063. "random_seed",
  3064. "tests",
  3065. "time",
  3066. "timestamp"
  3067. };
  3068. // The list of reserved attributes used in the <testsuite> element of XML
  3069. // output.
  3070. static const char* const kReservedTestSuiteAttributes[] = {
  3071. "disabled",
  3072. "errors",
  3073. "failures",
  3074. "name",
  3075. "tests",
  3076. "time"
  3077. };
  3078. // The list of reserved attributes used in the <testcase> element of XML output.
  3079. static const char* const kReservedTestCaseAttributes[] = {
  3080. "classname", "name", "status", "time",
  3081. "type_param", "value_param", "file", "line"};
  3082. template <int kSize>
  3083. std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
  3084. return std::vector<std::string>(array, array + kSize);
  3085. }
  3086. static std::vector<std::string> GetReservedAttributesForElement(
  3087. const std::string& xml_element) {
  3088. if (xml_element == "testsuites") {
  3089. return ArrayAsVector(kReservedTestSuitesAttributes);
  3090. } else if (xml_element == "testsuite") {
  3091. return ArrayAsVector(kReservedTestSuiteAttributes);
  3092. } else if (xml_element == "testcase") {
  3093. return ArrayAsVector(kReservedTestCaseAttributes);
  3094. } else {
  3095. GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
  3096. }
  3097. // This code is unreachable but some compilers may not realizes that.
  3098. return std::vector<std::string>();
  3099. }
  3100. static std::string FormatWordList(const std::vector<std::string>& words) {
  3101. Message word_list;
  3102. for (size_t i = 0; i < words.size(); ++i) {
  3103. if (i > 0 && words.size() > 2) {
  3104. word_list << ", ";
  3105. }
  3106. if (i == words.size() - 1) {
  3107. word_list << "and ";
  3108. }
  3109. word_list << "'" << words[i] << "'";
  3110. }
  3111. return word_list.GetString();
  3112. }
  3113. static bool ValidateTestPropertyName(
  3114. const std::string& property_name,
  3115. const std::vector<std::string>& reserved_names) {
  3116. if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
  3117. reserved_names.end()) {
  3118. ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
  3119. << " (" << FormatWordList(reserved_names)
  3120. << " are reserved by " << GTEST_NAME_ << ")";
  3121. return false;
  3122. }
  3123. return true;
  3124. }
  3125. // Adds a failure if the key is a reserved attribute of the element named
  3126. // xml_element. Returns true if the property is valid.
  3127. bool TestResult::ValidateTestProperty(const std::string& xml_element,
  3128. const TestProperty& test_property) {
  3129. return ValidateTestPropertyName(test_property.key(),
  3130. GetReservedAttributesForElement(xml_element));
  3131. }
  3132. // Clears the object.
  3133. void TestResult::Clear() {
  3134. test_part_results_.clear();
  3135. test_properties_.clear();
  3136. death_test_count_ = 0;
  3137. elapsed_time_ = 0;
  3138. }
  3139. // Returns true iff the test failed.
  3140. bool TestResult::Failed() const {
  3141. for (int i = 0; i < total_part_count(); ++i) {
  3142. if (GetTestPartResult(i).failed())
  3143. return true;
  3144. }
  3145. return false;
  3146. }
  3147. // Returns true iff the test part fatally failed.
  3148. static bool TestPartFatallyFailed(const TestPartResult& result) {
  3149. return result.fatally_failed();
  3150. }
  3151. // Returns true iff the test fatally failed.
  3152. bool TestResult::HasFatalFailure() const {
  3153. return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
  3154. }
  3155. // Returns true iff the test part non-fatally failed.
  3156. static bool TestPartNonfatallyFailed(const TestPartResult& result) {
  3157. return result.nonfatally_failed();
  3158. }
  3159. // Returns true iff the test has a non-fatal failure.
  3160. bool TestResult::HasNonfatalFailure() const {
  3161. return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
  3162. }
  3163. // Gets the number of all test parts. This is the sum of the number
  3164. // of successful test parts and the number of failed test parts.
  3165. int TestResult::total_part_count() const {
  3166. return static_cast<int>(test_part_results_.size());
  3167. }
  3168. // Returns the number of the test properties.
  3169. int TestResult::test_property_count() const {
  3170. return static_cast<int>(test_properties_.size());
  3171. }
  3172. // class Test
  3173. // Creates a Test object.
  3174. // The c'tor saves the states of all flags.
  3175. Test::Test()
  3176. : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
  3177. }
  3178. // The d'tor restores the states of all flags. The actual work is
  3179. // done by the d'tor of the gtest_flag_saver_ field, and thus not
  3180. // visible here.
  3181. Test::~Test() {
  3182. }
  3183. // Sets up the test fixture.
  3184. //
  3185. // A sub-class may override this.
  3186. void Test::SetUp() {
  3187. }
  3188. // Tears down the test fixture.
  3189. //
  3190. // A sub-class may override this.
  3191. void Test::TearDown() {
  3192. }
  3193. // Allows user supplied key value pairs to be recorded for later output.
  3194. void Test::RecordProperty(const std::string& key, const std::string& value) {
  3195. UnitTest::GetInstance()->RecordProperty(key, value);
  3196. }
  3197. // Allows user supplied key value pairs to be recorded for later output.
  3198. void Test::RecordProperty(const std::string& key, int value) {
  3199. Message value_message;
  3200. value_message << value;
  3201. RecordProperty(key, value_message.GetString().c_str());
  3202. }
  3203. namespace internal {
  3204. void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  3205. const std::string& message) {
  3206. // This function is a friend of UnitTest and as such has access to
  3207. // AddTestPartResult.
  3208. UnitTest::GetInstance()->AddTestPartResult(
  3209. result_type,
  3210. NULL, // No info about the source file where the exception occurred.
  3211. -1, // We have no info on which line caused the exception.
  3212. message,
  3213. ""); // No stack trace, either.
  3214. }
  3215. } // namespace internal
  3216. // Google Test requires all tests in the same test case to use the same test
  3217. // fixture class. This function checks if the current test has the
  3218. // same fixture class as the first test in the current test case. If
  3219. // yes, it returns true; otherwise it generates a Google Test failure and
  3220. // returns false.
  3221. bool Test::HasSameFixtureClass() {
  3222. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3223. const TestCase* const test_case = impl->current_test_case();
  3224. // Info about the first test in the current test case.
  3225. const TestInfo* const first_test_info = test_case->test_info_list()[0];
  3226. const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
  3227. const char* const first_test_name = first_test_info->name();
  3228. // Info about the current test.
  3229. const TestInfo* const this_test_info = impl->current_test_info();
  3230. const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
  3231. const char* const this_test_name = this_test_info->name();
  3232. if (this_fixture_id != first_fixture_id) {
  3233. // Is the first test defined using TEST?
  3234. const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
  3235. // Is this test defined using TEST?
  3236. const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
  3237. if (first_is_TEST || this_is_TEST) {
  3238. // Both TEST and TEST_F appear in same test case, which is incorrect.
  3239. // Tell the user how to fix this.
  3240. // Gets the name of the TEST and the name of the TEST_F. Note
  3241. // that first_is_TEST and this_is_TEST cannot both be true, as
  3242. // the fixture IDs are different for the two tests.
  3243. const char* const TEST_name =
  3244. first_is_TEST ? first_test_name : this_test_name;
  3245. const char* const TEST_F_name =
  3246. first_is_TEST ? this_test_name : first_test_name;
  3247. ADD_FAILURE()
  3248. << "All tests in the same test case must use the same test fixture\n"
  3249. << "class, so mixing TEST_F and TEST in the same test case is\n"
  3250. << "illegal. In test case " << this_test_info->test_case_name()
  3251. << ",\n"
  3252. << "test " << TEST_F_name << " is defined using TEST_F but\n"
  3253. << "test " << TEST_name << " is defined using TEST. You probably\n"
  3254. << "want to change the TEST to TEST_F or move it to another test\n"
  3255. << "case.";
  3256. } else {
  3257. // Two fixture classes with the same name appear in two different
  3258. // namespaces, which is not allowed. Tell the user how to fix this.
  3259. ADD_FAILURE()
  3260. << "All tests in the same test case must use the same test fixture\n"
  3261. << "class. However, in test case "
  3262. << this_test_info->test_case_name() << ",\n"
  3263. << "you defined test " << first_test_name
  3264. << " and test " << this_test_name << "\n"
  3265. << "using two different test fixture classes. This can happen if\n"
  3266. << "the two classes are from different namespaces or translation\n"
  3267. << "units and have the same name. You should probably rename one\n"
  3268. << "of the classes to put the tests into different test cases.";
  3269. }
  3270. return false;
  3271. }
  3272. return true;
  3273. }
  3274. #if GTEST_HAS_SEH
  3275. // Adds an "exception thrown" fatal failure to the current test. This
  3276. // function returns its result via an output parameter pointer because VC++
  3277. // prohibits creation of objects with destructors on stack in functions
  3278. // using __try (see error C2712).
  3279. static std::string* FormatSehExceptionMessage(DWORD exception_code,
  3280. const char* location) {
  3281. Message message;
  3282. message << "SEH exception with code 0x" << std::setbase(16) <<
  3283. exception_code << std::setbase(10) << " thrown in " << location << ".";
  3284. return new std::string(message.GetString());
  3285. }
  3286. #endif // GTEST_HAS_SEH
  3287. namespace internal {
  3288. #if GTEST_HAS_EXCEPTIONS
  3289. // Adds an "exception thrown" fatal failure to the current test.
  3290. static std::string FormatCxxExceptionMessage(const char* description,
  3291. const char* location) {
  3292. Message message;
  3293. if (description != NULL) {
  3294. message << "C++ exception with description \"" << description << "\"";
  3295. } else {
  3296. message << "Unknown C++ exception";
  3297. }
  3298. message << " thrown in " << location << ".";
  3299. return message.GetString();
  3300. }
  3301. static std::string PrintTestPartResultToString(
  3302. const TestPartResult& test_part_result);
  3303. GoogleTestFailureException::GoogleTestFailureException(
  3304. const TestPartResult& failure)
  3305. : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
  3306. #endif // GTEST_HAS_EXCEPTIONS
  3307. // We put these helper functions in the internal namespace as IBM's xlC
  3308. // compiler rejects the code if they were declared static.
  3309. // Runs the given method and handles SEH exceptions it throws, when
  3310. // SEH is supported; returns the 0-value for type Result in case of an
  3311. // SEH exception. (Microsoft compilers cannot handle SEH and C++
  3312. // exceptions in the same function. Therefore, we provide a separate
  3313. // wrapper function for handling SEH exceptions.)
  3314. template <class T, typename Result>
  3315. Result HandleSehExceptionsInMethodIfSupported(
  3316. T* object, Result (T::*method)(), const char* location) {
  3317. #if GTEST_HAS_SEH
  3318. __try {
  3319. return (object->*method)();
  3320. } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
  3321. GetExceptionCode())) {
  3322. // We create the exception message on the heap because VC++ prohibits
  3323. // creation of objects with destructors on stack in functions using __try
  3324. // (see error C2712).
  3325. std::string* exception_message = FormatSehExceptionMessage(
  3326. GetExceptionCode(), location);
  3327. internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
  3328. *exception_message);
  3329. delete exception_message;
  3330. return static_cast<Result>(0);
  3331. }
  3332. #else
  3333. (void)location;
  3334. return (object->*method)();
  3335. #endif // GTEST_HAS_SEH
  3336. }
  3337. // Runs the given method and catches and reports C++ and/or SEH-style
  3338. // exceptions, if they are supported; returns the 0-value for type
  3339. // Result in case of an SEH exception.
  3340. template <class T, typename Result>
  3341. Result HandleExceptionsInMethodIfSupported(
  3342. T* object, Result (T::*method)(), const char* location) {
  3343. // NOTE: The user code can affect the way in which Google Test handles
  3344. // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
  3345. // RUN_ALL_TESTS() starts. It is technically possible to check the flag
  3346. // after the exception is caught and either report or re-throw the
  3347. // exception based on the flag's value:
  3348. //
  3349. // try {
  3350. // // Perform the test method.
  3351. // } catch (...) {
  3352. // if (GTEST_FLAG(catch_exceptions))
  3353. // // Report the exception as failure.
  3354. // else
  3355. // throw; // Re-throws the original exception.
  3356. // }
  3357. //
  3358. // However, the purpose of this flag is to allow the program to drop into
  3359. // the debugger when the exception is thrown. On most platforms, once the
  3360. // control enters the catch block, the exception origin information is
  3361. // lost and the debugger will stop the program at the point of the
  3362. // re-throw in this function -- instead of at the point of the original
  3363. // throw statement in the code under test. For this reason, we perform
  3364. // the check early, sacrificing the ability to affect Google Test's
  3365. // exception handling in the method where the exception is thrown.
  3366. if (internal::GetUnitTestImpl()->catch_exceptions()) {
  3367. #if GTEST_HAS_EXCEPTIONS
  3368. try {
  3369. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  3370. } catch (const AssertionException&) { // NOLINT
  3371. // This failure was reported already.
  3372. } catch (const internal::GoogleTestFailureException&) { // NOLINT
  3373. // This exception type can only be thrown by a failed Google
  3374. // Test assertion with the intention of letting another testing
  3375. // framework catch it. Therefore we just re-throw it.
  3376. throw;
  3377. } catch (const std::exception& e) { // NOLINT
  3378. internal::ReportFailureInUnknownLocation(
  3379. TestPartResult::kFatalFailure,
  3380. FormatCxxExceptionMessage(e.what(), location));
  3381. } catch (...) { // NOLINT
  3382. internal::ReportFailureInUnknownLocation(
  3383. TestPartResult::kFatalFailure,
  3384. FormatCxxExceptionMessage(NULL, location));
  3385. }
  3386. return static_cast<Result>(0);
  3387. #else
  3388. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  3389. #endif // GTEST_HAS_EXCEPTIONS
  3390. } else {
  3391. return (object->*method)();
  3392. }
  3393. }
  3394. } // namespace internal
  3395. // Runs the test and updates the test result.
  3396. void Test::Run() {
  3397. if (!HasSameFixtureClass()) return;
  3398. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3399. impl->os_stack_trace_getter()->UponLeavingGTest();
  3400. internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
  3401. // We will run the test only if SetUp() was successful.
  3402. if (!HasFatalFailure()) {
  3403. impl->os_stack_trace_getter()->UponLeavingGTest();
  3404. internal::HandleExceptionsInMethodIfSupported(
  3405. this, &Test::TestBody, "the test body");
  3406. }
  3407. // However, we want to clean up as much as possible. Hence we will
  3408. // always call TearDown(), even if SetUp() or the test body has
  3409. // failed.
  3410. impl->os_stack_trace_getter()->UponLeavingGTest();
  3411. internal::HandleExceptionsInMethodIfSupported(
  3412. this, &Test::TearDown, "TearDown()");
  3413. }
  3414. // Returns true iff the current test has a fatal failure.
  3415. bool Test::HasFatalFailure() {
  3416. return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
  3417. }
  3418. // Returns true iff the current test has a non-fatal failure.
  3419. bool Test::HasNonfatalFailure() {
  3420. return internal::GetUnitTestImpl()->current_test_result()->
  3421. HasNonfatalFailure();
  3422. }
  3423. // class TestInfo
  3424. // Constructs a TestInfo object. It assumes ownership of the test factory
  3425. // object.
  3426. TestInfo::TestInfo(const std::string& a_test_case_name,
  3427. const std::string& a_name,
  3428. const char* a_type_param,
  3429. const char* a_value_param,
  3430. internal::CodeLocation a_code_location,
  3431. internal::TypeId fixture_class_id,
  3432. internal::TestFactoryBase* factory)
  3433. : test_case_name_(a_test_case_name),
  3434. name_(a_name),
  3435. type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  3436. value_param_(a_value_param ? new std::string(a_value_param) : NULL),
  3437. location_(a_code_location),
  3438. fixture_class_id_(fixture_class_id),
  3439. should_run_(false),
  3440. is_disabled_(false),
  3441. matches_filter_(false),
  3442. factory_(factory),
  3443. result_() {}
  3444. // Destructs a TestInfo object.
  3445. TestInfo::~TestInfo() { delete factory_; }
  3446. namespace internal {
  3447. // Creates a new TestInfo object and registers it with Google Test;
  3448. // returns the created object.
  3449. //
  3450. // Arguments:
  3451. //
  3452. // test_case_name: name of the test case
  3453. // name: name of the test
  3454. // type_param: the name of the test's type parameter, or NULL if
  3455. // this is not a typed or a type-parameterized test.
  3456. // value_param: text representation of the test's value parameter,
  3457. // or NULL if this is not a value-parameterized test.
  3458. // code_location: code location where the test is defined
  3459. // fixture_class_id: ID of the test fixture class
  3460. // set_up_tc: pointer to the function that sets up the test case
  3461. // tear_down_tc: pointer to the function that tears down the test case
  3462. // factory: pointer to the factory that creates a test object.
  3463. // The newly created TestInfo instance will assume
  3464. // ownership of the factory object.
  3465. TestInfo* MakeAndRegisterTestInfo(
  3466. const char* test_case_name,
  3467. const char* name,
  3468. const char* type_param,
  3469. const char* value_param,
  3470. CodeLocation code_location,
  3471. TypeId fixture_class_id,
  3472. SetUpTestCaseFunc set_up_tc,
  3473. TearDownTestCaseFunc tear_down_tc,
  3474. TestFactoryBase* factory) {
  3475. TestInfo* const test_info =
  3476. new TestInfo(test_case_name, name, type_param, value_param,
  3477. code_location, fixture_class_id, factory);
  3478. GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
  3479. return test_info;
  3480. }
  3481. void ReportInvalidTestCaseType(const char* test_case_name,
  3482. CodeLocation code_location) {
  3483. Message errors;
  3484. errors
  3485. << "Attempted redefinition of test case " << test_case_name << ".\n"
  3486. << "All tests in the same test case must use the same test fixture\n"
  3487. << "class. However, in test case " << test_case_name << ", you tried\n"
  3488. << "to define a test using a fixture class different from the one\n"
  3489. << "used earlier. This can happen if the two fixture classes are\n"
  3490. << "from different namespaces and have the same name. You should\n"
  3491. << "probably rename one of the classes to put the tests into different\n"
  3492. << "test cases.";
  3493. GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
  3494. code_location.line)
  3495. << " " << errors.GetString();
  3496. }
  3497. } // namespace internal
  3498. namespace {
  3499. // A predicate that checks the test name of a TestInfo against a known
  3500. // value.
  3501. //
  3502. // This is used for implementation of the TestCase class only. We put
  3503. // it in the anonymous namespace to prevent polluting the outer
  3504. // namespace.
  3505. //
  3506. // TestNameIs is copyable.
  3507. class TestNameIs {
  3508. public:
  3509. // Constructor.
  3510. //
  3511. // TestNameIs has NO default constructor.
  3512. explicit TestNameIs(const char* name)
  3513. : name_(name) {}
  3514. // Returns true iff the test name of test_info matches name_.
  3515. bool operator()(const TestInfo * test_info) const {
  3516. return test_info && test_info->name() == name_;
  3517. }
  3518. private:
  3519. std::string name_;
  3520. };
  3521. } // namespace
  3522. namespace internal {
  3523. // This method expands all parameterized tests registered with macros TEST_P
  3524. // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
  3525. // This will be done just once during the program runtime.
  3526. void UnitTestImpl::RegisterParameterizedTests() {
  3527. if (!parameterized_tests_registered_) {
  3528. parameterized_test_registry_.RegisterTests();
  3529. parameterized_tests_registered_ = true;
  3530. }
  3531. }
  3532. } // namespace internal
  3533. // Creates the test object, runs it, records its result, and then
  3534. // deletes it.
  3535. void TestInfo::Run() {
  3536. if (!should_run_) return;
  3537. // Tells UnitTest where to store test result.
  3538. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3539. impl->set_current_test_info(this);
  3540. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3541. // Notifies the unit test event listeners that a test is about to start.
  3542. repeater->OnTestStart(*this);
  3543. const TimeInMillis start = internal::GetTimeInMillis();
  3544. impl->os_stack_trace_getter()->UponLeavingGTest();
  3545. // Creates the test object.
  3546. Test* const test = internal::HandleExceptionsInMethodIfSupported(
  3547. factory_, &internal::TestFactoryBase::CreateTest,
  3548. "the test fixture's constructor");
  3549. // Runs the test if the constructor didn't generate a fatal failure.
  3550. // Note that the object will not be null
  3551. if (!Test::HasFatalFailure()) {
  3552. // This doesn't throw as all user code that can throw are wrapped into
  3553. // exception handling code.
  3554. test->Run();
  3555. }
  3556. // Deletes the test object.
  3557. impl->os_stack_trace_getter()->UponLeavingGTest();
  3558. internal::HandleExceptionsInMethodIfSupported(
  3559. test, &Test::DeleteSelf_, "the test fixture's destructor");
  3560. result_.set_elapsed_time(internal::GetTimeInMillis() - start);
  3561. // Notifies the unit test event listener that a test has just finished.
  3562. repeater->OnTestEnd(*this);
  3563. // Tells UnitTest to stop associating assertion results to this
  3564. // test.
  3565. impl->set_current_test_info(NULL);
  3566. }
  3567. // class TestCase
  3568. // Gets the number of successful tests in this test case.
  3569. int TestCase::successful_test_count() const {
  3570. return CountIf(test_info_list_, TestPassed);
  3571. }
  3572. // Gets the number of failed tests in this test case.
  3573. int TestCase::failed_test_count() const {
  3574. return CountIf(test_info_list_, TestFailed);
  3575. }
  3576. // Gets the number of disabled tests that will be reported in the XML report.
  3577. int TestCase::reportable_disabled_test_count() const {
  3578. return CountIf(test_info_list_, TestReportableDisabled);
  3579. }
  3580. // Gets the number of disabled tests in this test case.
  3581. int TestCase::disabled_test_count() const {
  3582. return CountIf(test_info_list_, TestDisabled);
  3583. }
  3584. // Gets the number of tests to be printed in the XML report.
  3585. int TestCase::reportable_test_count() const {
  3586. return CountIf(test_info_list_, TestReportable);
  3587. }
  3588. // Get the number of tests in this test case that should run.
  3589. int TestCase::test_to_run_count() const {
  3590. return CountIf(test_info_list_, ShouldRunTest);
  3591. }
  3592. // Gets the number of all tests.
  3593. int TestCase::total_test_count() const {
  3594. return static_cast<int>(test_info_list_.size());
  3595. }
  3596. // Creates a TestCase with the given name.
  3597. //
  3598. // Arguments:
  3599. //
  3600. // name: name of the test case
  3601. // a_type_param: the name of the test case's type parameter, or NULL if
  3602. // this is not a typed or a type-parameterized test case.
  3603. // set_up_tc: pointer to the function that sets up the test case
  3604. // tear_down_tc: pointer to the function that tears down the test case
  3605. TestCase::TestCase(const char* a_name, const char* a_type_param,
  3606. Test::SetUpTestCaseFunc set_up_tc,
  3607. Test::TearDownTestCaseFunc tear_down_tc)
  3608. : name_(a_name),
  3609. type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  3610. set_up_tc_(set_up_tc),
  3611. tear_down_tc_(tear_down_tc),
  3612. should_run_(false),
  3613. elapsed_time_(0) {
  3614. }
  3615. // Destructor of TestCase.
  3616. TestCase::~TestCase() {
  3617. // Deletes every Test in the collection.
  3618. ForEach(test_info_list_, internal::Delete<TestInfo>);
  3619. }
  3620. // Returns the i-th test among all the tests. i can range from 0 to
  3621. // total_test_count() - 1. If i is not in that range, returns NULL.
  3622. const TestInfo* TestCase::GetTestInfo(int i) const {
  3623. const int index = GetElementOr(test_indices_, i, -1);
  3624. return index < 0 ? NULL : test_info_list_[index];
  3625. }
  3626. // Returns the i-th test among all the tests. i can range from 0 to
  3627. // total_test_count() - 1. If i is not in that range, returns NULL.
  3628. TestInfo* TestCase::GetMutableTestInfo(int i) {
  3629. const int index = GetElementOr(test_indices_, i, -1);
  3630. return index < 0 ? NULL : test_info_list_[index];
  3631. }
  3632. // Adds a test to this test case. Will delete the test upon
  3633. // destruction of the TestCase object.
  3634. void TestCase::AddTestInfo(TestInfo * test_info) {
  3635. test_info_list_.push_back(test_info);
  3636. test_indices_.push_back(static_cast<int>(test_indices_.size()));
  3637. }
  3638. // Runs every test in this TestCase.
  3639. void TestCase::Run() {
  3640. if (!should_run_) return;
  3641. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3642. impl->set_current_test_case(this);
  3643. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3644. repeater->OnTestCaseStart(*this);
  3645. impl->os_stack_trace_getter()->UponLeavingGTest();
  3646. internal::HandleExceptionsInMethodIfSupported(
  3647. this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
  3648. const internal::TimeInMillis start = internal::GetTimeInMillis();
  3649. for (int i = 0; i < total_test_count(); i++) {
  3650. GetMutableTestInfo(i)->Run();
  3651. }
  3652. elapsed_time_ = internal::GetTimeInMillis() - start;
  3653. impl->os_stack_trace_getter()->UponLeavingGTest();
  3654. internal::HandleExceptionsInMethodIfSupported(
  3655. this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
  3656. repeater->OnTestCaseEnd(*this);
  3657. impl->set_current_test_case(NULL);
  3658. }
  3659. // Clears the results of all tests in this test case.
  3660. void TestCase::ClearResult() {
  3661. ad_hoc_test_result_.Clear();
  3662. ForEach(test_info_list_, TestInfo::ClearTestResult);
  3663. }
  3664. // Shuffles the tests in this test case.
  3665. void TestCase::ShuffleTests(internal::Random* random) {
  3666. Shuffle(random, &test_indices_);
  3667. }
  3668. // Restores the test order to before the first shuffle.
  3669. void TestCase::UnshuffleTests() {
  3670. for (size_t i = 0; i < test_indices_.size(); i++) {
  3671. test_indices_[i] = static_cast<int>(i);
  3672. }
  3673. }
  3674. // Formats a countable noun. Depending on its quantity, either the
  3675. // singular form or the plural form is used. e.g.
  3676. //
  3677. // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
  3678. // FormatCountableNoun(5, "book", "books") returns "5 books".
  3679. static std::string FormatCountableNoun(int count,
  3680. const char * singular_form,
  3681. const char * plural_form) {
  3682. return internal::StreamableToString(count) + " " +
  3683. (count == 1 ? singular_form : plural_form);
  3684. }
  3685. // Formats the count of tests.
  3686. static std::string FormatTestCount(int test_count) {
  3687. return FormatCountableNoun(test_count, "test", "tests");
  3688. }
  3689. // Formats the count of test cases.
  3690. static std::string FormatTestCaseCount(int test_case_count) {
  3691. return FormatCountableNoun(test_case_count, "test case", "test cases");
  3692. }
  3693. // Converts a TestPartResult::Type enum to human-friendly string
  3694. // representation. Both kNonFatalFailure and kFatalFailure are translated
  3695. // to "Failure", as the user usually doesn't care about the difference
  3696. // between the two when viewing the test result.
  3697. static const char * TestPartResultTypeToString(TestPartResult::Type type) {
  3698. switch (type) {
  3699. case TestPartResult::kSuccess:
  3700. return "Success";
  3701. case TestPartResult::kNonFatalFailure:
  3702. case TestPartResult::kFatalFailure:
  3703. #ifdef _MSC_VER
  3704. return "error: ";
  3705. #else
  3706. return "Failure\n";
  3707. #endif
  3708. default:
  3709. return "Unknown result type";
  3710. }
  3711. }
  3712. namespace internal {
  3713. // Prints a TestPartResult to an std::string.
  3714. static std::string PrintTestPartResultToString(
  3715. const TestPartResult& test_part_result) {
  3716. return (Message()
  3717. << internal::FormatFileLocation(test_part_result.file_name(),
  3718. test_part_result.line_number())
  3719. << " " << TestPartResultTypeToString(test_part_result.type())
  3720. << test_part_result.message()).GetString();
  3721. }
  3722. // Prints a TestPartResult.
  3723. static void PrintTestPartResult(const TestPartResult& test_part_result) {
  3724. const std::string& result =
  3725. PrintTestPartResultToString(test_part_result);
  3726. printf("%s\n", result.c_str());
  3727. fflush(stdout);
  3728. // If the test program runs in Visual Studio or a debugger, the
  3729. // following statements add the test part result message to the Output
  3730. // window such that the user can double-click on it to jump to the
  3731. // corresponding source code location; otherwise they do nothing.
  3732. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3733. // We don't call OutputDebugString*() on Windows Mobile, as printing
  3734. // to stdout is done by OutputDebugString() there already - we don't
  3735. // want the same message printed twice.
  3736. ::OutputDebugStringA(result.c_str());
  3737. ::OutputDebugStringA("\n");
  3738. #endif
  3739. }
  3740. // class PrettyUnitTestResultPrinter
  3741. enum GTestColor {
  3742. COLOR_DEFAULT,
  3743. COLOR_RED,
  3744. COLOR_GREEN,
  3745. COLOR_YELLOW
  3746. };
  3747. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
  3748. !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  3749. // Returns the character attribute for the given color.
  3750. static WORD GetColorAttribute(GTestColor color) {
  3751. switch (color) {
  3752. case COLOR_RED: return FOREGROUND_RED;
  3753. case COLOR_GREEN: return FOREGROUND_GREEN;
  3754. case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
  3755. default: return 0;
  3756. }
  3757. }
  3758. static int GetBitOffset(WORD color_mask) {
  3759. if (color_mask == 0) return 0;
  3760. int bitOffset = 0;
  3761. while ((color_mask & 1) == 0) {
  3762. color_mask >>= 1;
  3763. ++bitOffset;
  3764. }
  3765. return bitOffset;
  3766. }
  3767. static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
  3768. // Let's reuse the BG
  3769. static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
  3770. BACKGROUND_RED | BACKGROUND_INTENSITY;
  3771. static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
  3772. FOREGROUND_RED | FOREGROUND_INTENSITY;
  3773. const WORD existing_bg = old_color_attrs & background_mask;
  3774. WORD new_color =
  3775. GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
  3776. static const int bg_bitOffset = GetBitOffset(background_mask);
  3777. static const int fg_bitOffset = GetBitOffset(foreground_mask);
  3778. if (((new_color & background_mask) >> bg_bitOffset) ==
  3779. ((new_color & foreground_mask) >> fg_bitOffset)) {
  3780. new_color ^= FOREGROUND_INTENSITY; // invert intensity
  3781. }
  3782. return new_color;
  3783. }
  3784. #else
  3785. // Returns the ANSI color code for the given color. COLOR_DEFAULT is
  3786. // an invalid input.
  3787. static const char* GetAnsiColorCode(GTestColor color) {
  3788. switch (color) {
  3789. case COLOR_RED: return "1";
  3790. case COLOR_GREEN: return "2";
  3791. case COLOR_YELLOW: return "3";
  3792. default: return NULL;
  3793. };
  3794. }
  3795. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3796. // Returns true iff Google Test should use colors in the output.
  3797. bool ShouldUseColor(bool stdout_is_tty) {
  3798. const char* const gtest_color = GTEST_FLAG(color).c_str();
  3799. if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
  3800. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
  3801. // On Windows the TERM variable is usually not set, but the
  3802. // console there does support colors.
  3803. return stdout_is_tty;
  3804. #else
  3805. // On non-Windows platforms, we rely on the TERM variable.
  3806. const char* const term = posix::GetEnv("TERM");
  3807. const bool term_supports_color =
  3808. String::CStringEquals(term, "xterm") ||
  3809. String::CStringEquals(term, "xterm-color") ||
  3810. String::CStringEquals(term, "xterm-256color") ||
  3811. String::CStringEquals(term, "screen") ||
  3812. String::CStringEquals(term, "screen-256color") ||
  3813. String::CStringEquals(term, "tmux") ||
  3814. String::CStringEquals(term, "tmux-256color") ||
  3815. String::CStringEquals(term, "rxvt-unicode") ||
  3816. String::CStringEquals(term, "rxvt-unicode-256color") ||
  3817. String::CStringEquals(term, "linux") ||
  3818. String::CStringEquals(term, "cygwin");
  3819. return stdout_is_tty && term_supports_color;
  3820. #endif // GTEST_OS_WINDOWS
  3821. }
  3822. return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
  3823. String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
  3824. String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
  3825. String::CStringEquals(gtest_color, "1");
  3826. // We take "yes", "true", "t", and "1" as meaning "yes". If the
  3827. // value is neither one of these nor "auto", we treat it as "no" to
  3828. // be conservative.
  3829. }
  3830. // Helpers for printing colored strings to stdout. Note that on Windows, we
  3831. // cannot simply emit special characters and have the terminal change colors.
  3832. // This routine must actually emit the characters rather than return a string
  3833. // that would be colored when printed, as can be done on Linux.
  3834. static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
  3835. va_list args;
  3836. va_start(args, fmt);
  3837. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \
  3838. GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
  3839. const bool use_color = AlwaysFalse();
  3840. #else
  3841. static const bool in_color_mode =
  3842. ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
  3843. const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
  3844. #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
  3845. // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
  3846. if (!use_color) {
  3847. vprintf(fmt, args);
  3848. va_end(args);
  3849. return;
  3850. }
  3851. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
  3852. !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  3853. const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  3854. // Gets the current text color.
  3855. CONSOLE_SCREEN_BUFFER_INFO buffer_info;
  3856. GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
  3857. const WORD old_color_attrs = buffer_info.wAttributes;
  3858. const WORD new_color = GetNewColor(color, old_color_attrs);
  3859. // We need to flush the stream buffers into the console before each
  3860. // SetConsoleTextAttribute call lest it affect the text that is already
  3861. // printed but has not yet reached the console.
  3862. fflush(stdout);
  3863. SetConsoleTextAttribute(stdout_handle, new_color);
  3864. vprintf(fmt, args);
  3865. fflush(stdout);
  3866. // Restores the text color.
  3867. SetConsoleTextAttribute(stdout_handle, old_color_attrs);
  3868. #else
  3869. printf("\033[0;3%sm", GetAnsiColorCode(color));
  3870. vprintf(fmt, args);
  3871. printf("\033[m"); // Resets the terminal to default.
  3872. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3873. va_end(args);
  3874. }
  3875. // Text printed in Google Test's text output and --gtest_list_tests
  3876. // output to label the type parameter and value parameter for a test.
  3877. static const char kTypeParamLabel[] = "TypeParam";
  3878. static const char kValueParamLabel[] = "GetParam()";
  3879. static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
  3880. const char* const type_param = test_info.type_param();
  3881. const char* const value_param = test_info.value_param();
  3882. if (type_param != NULL || value_param != NULL) {
  3883. printf(", where ");
  3884. if (type_param != NULL) {
  3885. printf("%s = %s", kTypeParamLabel, type_param);
  3886. if (value_param != NULL)
  3887. printf(" and ");
  3888. }
  3889. if (value_param != NULL) {
  3890. printf("%s = %s", kValueParamLabel, value_param);
  3891. }
  3892. }
  3893. }
  3894. // This class implements the TestEventListener interface.
  3895. //
  3896. // Class PrettyUnitTestResultPrinter is copyable.
  3897. class PrettyUnitTestResultPrinter : public TestEventListener {
  3898. public:
  3899. PrettyUnitTestResultPrinter() {}
  3900. static void PrintTestName(const char * test_case, const char * test) {
  3901. printf("%s.%s", test_case, test);
  3902. }
  3903. // The following methods override what's in the TestEventListener class.
  3904. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
  3905. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  3906. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  3907. virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
  3908. virtual void OnTestCaseStart(const TestCase& test_case);
  3909. virtual void OnTestStart(const TestInfo& test_info);
  3910. virtual void OnTestPartResult(const TestPartResult& result);
  3911. virtual void OnTestEnd(const TestInfo& test_info);
  3912. virtual void OnTestCaseEnd(const TestCase& test_case);
  3913. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  3914. virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
  3915. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3916. virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
  3917. private:
  3918. static void PrintFailedTests(const UnitTest& unit_test);
  3919. };
  3920. // Fired before each iteration of tests starts.
  3921. void PrettyUnitTestResultPrinter::OnTestIterationStart(
  3922. const UnitTest& unit_test, int iteration) {
  3923. if (GTEST_FLAG(repeat) != 1)
  3924. printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
  3925. const char* const filter = GTEST_FLAG(filter).c_str();
  3926. // Prints the filter if it's not *. This reminds the user that some
  3927. // tests may be skipped.
  3928. if (!String::CStringEquals(filter, kUniversalFilter)) {
  3929. ColoredPrintf(COLOR_YELLOW,
  3930. "Note: %s filter = %s\n", GTEST_NAME_, filter);
  3931. }
  3932. if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
  3933. const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
  3934. ColoredPrintf(COLOR_YELLOW,
  3935. "Note: This is test shard %d of %s.\n",
  3936. static_cast<int>(shard_index) + 1,
  3937. internal::posix::GetEnv(kTestTotalShards));
  3938. }
  3939. if (GTEST_FLAG(shuffle)) {
  3940. ColoredPrintf(COLOR_YELLOW,
  3941. "Note: Randomizing tests' orders with a seed of %d .\n",
  3942. unit_test.random_seed());
  3943. }
  3944. ColoredPrintf(COLOR_GREEN, "[==========] ");
  3945. printf("Running %s from %s.\n",
  3946. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  3947. FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  3948. fflush(stdout);
  3949. }
  3950. void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
  3951. const UnitTest& /*unit_test*/) {
  3952. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3953. printf("Global test environment set-up.\n");
  3954. fflush(stdout);
  3955. }
  3956. void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
  3957. const std::string counts =
  3958. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  3959. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3960. printf("%s from %s", counts.c_str(), test_case.name());
  3961. if (test_case.type_param() == NULL) {
  3962. printf("\n");
  3963. } else {
  3964. printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
  3965. }
  3966. fflush(stdout);
  3967. }
  3968. void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
  3969. ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
  3970. PrintTestName(test_info.test_case_name(), test_info.name());
  3971. printf("\n");
  3972. fflush(stdout);
  3973. }
  3974. // Called after an assertion failure.
  3975. void PrettyUnitTestResultPrinter::OnTestPartResult(
  3976. const TestPartResult& result) {
  3977. // If the test part succeeded, we don't need to do anything.
  3978. if (result.type() == TestPartResult::kSuccess)
  3979. return;
  3980. // Print failure message from the assertion (e.g. expected this and got that).
  3981. PrintTestPartResult(result);
  3982. fflush(stdout);
  3983. }
  3984. void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  3985. if (test_info.result()->Passed()) {
  3986. ColoredPrintf(COLOR_GREEN, "[ OK ] ");
  3987. } else {
  3988. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  3989. }
  3990. PrintTestName(test_info.test_case_name(), test_info.name());
  3991. if (test_info.result()->Failed())
  3992. PrintFullTestCommentIfPresent(test_info);
  3993. if (GTEST_FLAG(print_time)) {
  3994. printf(" (%s ms)\n", internal::StreamableToString(
  3995. test_info.result()->elapsed_time()).c_str());
  3996. } else {
  3997. printf("\n");
  3998. }
  3999. fflush(stdout);
  4000. }
  4001. void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
  4002. if (!GTEST_FLAG(print_time)) return;
  4003. const std::string counts =
  4004. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  4005. ColoredPrintf(COLOR_GREEN, "[----------] ");
  4006. printf("%s from %s (%s ms total)\n\n",
  4007. counts.c_str(), test_case.name(),
  4008. internal::StreamableToString(test_case.elapsed_time()).c_str());
  4009. fflush(stdout);
  4010. }
  4011. void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
  4012. const UnitTest& /*unit_test*/) {
  4013. ColoredPrintf(COLOR_GREEN, "[----------] ");
  4014. printf("Global test environment tear-down\n");
  4015. fflush(stdout);
  4016. }
  4017. // Internal helper for printing the list of failed tests.
  4018. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
  4019. const int failed_test_count = unit_test.failed_test_count();
  4020. if (failed_test_count == 0) {
  4021. return;
  4022. }
  4023. for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  4024. const TestCase& test_case = *unit_test.GetTestCase(i);
  4025. if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
  4026. continue;
  4027. }
  4028. for (int j = 0; j < test_case.total_test_count(); ++j) {
  4029. const TestInfo& test_info = *test_case.GetTestInfo(j);
  4030. if (!test_info.should_run() || test_info.result()->Passed()) {
  4031. continue;
  4032. }
  4033. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  4034. printf("%s.%s", test_case.name(), test_info.name());
  4035. PrintFullTestCommentIfPresent(test_info);
  4036. printf("\n");
  4037. }
  4038. }
  4039. }
  4040. void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4041. int /*iteration*/) {
  4042. ColoredPrintf(COLOR_GREEN, "[==========] ");
  4043. printf("%s from %s ran.",
  4044. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  4045. FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  4046. if (GTEST_FLAG(print_time)) {
  4047. printf(" (%s ms total)",
  4048. internal::StreamableToString(unit_test.elapsed_time()).c_str());
  4049. }
  4050. printf("\n");
  4051. ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
  4052. printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  4053. int num_failures = unit_test.failed_test_count();
  4054. if (!unit_test.Passed()) {
  4055. const int failed_test_count = unit_test.failed_test_count();
  4056. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  4057. printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
  4058. PrintFailedTests(unit_test);
  4059. printf("\n%2d FAILED %s\n", num_failures,
  4060. num_failures == 1 ? "TEST" : "TESTS");
  4061. }
  4062. int num_disabled = unit_test.reportable_disabled_test_count();
  4063. if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
  4064. if (!num_failures) {
  4065. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
  4066. }
  4067. ColoredPrintf(COLOR_YELLOW,
  4068. " YOU HAVE %d DISABLED %s\n\n",
  4069. num_disabled,
  4070. num_disabled == 1 ? "TEST" : "TESTS");
  4071. }
  4072. // Ensure that Google Test output is printed before, e.g., heapchecker output.
  4073. fflush(stdout);
  4074. }
  4075. // End PrettyUnitTestResultPrinter
  4076. // class TestEventRepeater
  4077. //
  4078. // This class forwards events to other event listeners.
  4079. class TestEventRepeater : public TestEventListener {
  4080. public:
  4081. TestEventRepeater() : forwarding_enabled_(true) {}
  4082. virtual ~TestEventRepeater();
  4083. void Append(TestEventListener *listener);
  4084. TestEventListener* Release(TestEventListener* listener);
  4085. // Controls whether events will be forwarded to listeners_. Set to false
  4086. // in death test child processes.
  4087. bool forwarding_enabled() const { return forwarding_enabled_; }
  4088. void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
  4089. virtual void OnTestProgramStart(const UnitTest& unit_test);
  4090. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  4091. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  4092. virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
  4093. virtual void OnTestCaseStart(const TestCase& test_case);
  4094. virtual void OnTestStart(const TestInfo& test_info);
  4095. virtual void OnTestPartResult(const TestPartResult& result);
  4096. virtual void OnTestEnd(const TestInfo& test_info);
  4097. virtual void OnTestCaseEnd(const TestCase& test_case);
  4098. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  4099. virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
  4100. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  4101. virtual void OnTestProgramEnd(const UnitTest& unit_test);
  4102. private:
  4103. // Controls whether events will be forwarded to listeners_. Set to false
  4104. // in death test child processes.
  4105. bool forwarding_enabled_;
  4106. // The list of listeners that receive events.
  4107. std::vector<TestEventListener*> listeners_;
  4108. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
  4109. };
  4110. TestEventRepeater::~TestEventRepeater() {
  4111. ForEach(listeners_, Delete<TestEventListener>);
  4112. }
  4113. void TestEventRepeater::Append(TestEventListener *listener) {
  4114. listeners_.push_back(listener);
  4115. }
  4116. // FIXME: Factor the search functionality into Vector::Find.
  4117. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
  4118. for (size_t i = 0; i < listeners_.size(); ++i) {
  4119. if (listeners_[i] == listener) {
  4120. listeners_.erase(listeners_.begin() + i);
  4121. return listener;
  4122. }
  4123. }
  4124. return NULL;
  4125. }
  4126. // Since most methods are very similar, use macros to reduce boilerplate.
  4127. // This defines a member that forwards the call to all listeners.
  4128. #define GTEST_REPEATER_METHOD_(Name, Type) \
  4129. void TestEventRepeater::Name(const Type& parameter) { \
  4130. if (forwarding_enabled_) { \
  4131. for (size_t i = 0; i < listeners_.size(); i++) { \
  4132. listeners_[i]->Name(parameter); \
  4133. } \
  4134. } \
  4135. }
  4136. // This defines a member that forwards the call to all listeners in reverse
  4137. // order.
  4138. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
  4139. void TestEventRepeater::Name(const Type& parameter) { \
  4140. if (forwarding_enabled_) { \
  4141. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
  4142. listeners_[i]->Name(parameter); \
  4143. } \
  4144. } \
  4145. }
  4146. GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
  4147. GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
  4148. GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
  4149. GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
  4150. GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
  4151. GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
  4152. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
  4153. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
  4154. GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
  4155. GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
  4156. GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
  4157. #undef GTEST_REPEATER_METHOD_
  4158. #undef GTEST_REVERSE_REPEATER_METHOD_
  4159. void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
  4160. int iteration) {
  4161. if (forwarding_enabled_) {
  4162. for (size_t i = 0; i < listeners_.size(); i++) {
  4163. listeners_[i]->OnTestIterationStart(unit_test, iteration);
  4164. }
  4165. }
  4166. }
  4167. void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
  4168. int iteration) {
  4169. if (forwarding_enabled_) {
  4170. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
  4171. listeners_[i]->OnTestIterationEnd(unit_test, iteration);
  4172. }
  4173. }
  4174. }
  4175. // End TestEventRepeater
  4176. // This class generates an XML output file.
  4177. class XmlUnitTestResultPrinter : public EmptyTestEventListener {
  4178. public:
  4179. explicit XmlUnitTestResultPrinter(const char* output_file);
  4180. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  4181. void ListTestsMatchingFilter(const std::vector<TestCase*>& test_cases);
  4182. // Prints an XML summary of all unit tests.
  4183. static void PrintXmlTestsList(std::ostream* stream,
  4184. const std::vector<TestCase*>& test_cases);
  4185. private:
  4186. // Is c a whitespace character that is normalized to a space character
  4187. // when it appears in an XML attribute value?
  4188. static bool IsNormalizableWhitespace(char c) {
  4189. return c == 0x9 || c == 0xA || c == 0xD;
  4190. }
  4191. // May c appear in a well-formed XML document?
  4192. static bool IsValidXmlCharacter(char c) {
  4193. return IsNormalizableWhitespace(c) || c >= 0x20;
  4194. }
  4195. // Returns an XML-escaped copy of the input string str. If
  4196. // is_attribute is true, the text is meant to appear as an attribute
  4197. // value, and normalizable whitespace is preserved by replacing it
  4198. // with character references.
  4199. static std::string EscapeXml(const std::string& str, bool is_attribute);
  4200. // Returns the given string with all characters invalid in XML removed.
  4201. static std::string RemoveInvalidXmlCharacters(const std::string& str);
  4202. // Convenience wrapper around EscapeXml when str is an attribute value.
  4203. static std::string EscapeXmlAttribute(const std::string& str) {
  4204. return EscapeXml(str, true);
  4205. }
  4206. // Convenience wrapper around EscapeXml when str is not an attribute value.
  4207. static std::string EscapeXmlText(const char* str) {
  4208. return EscapeXml(str, false);
  4209. }
  4210. // Verifies that the given attribute belongs to the given element and
  4211. // streams the attribute as XML.
  4212. static void OutputXmlAttribute(std::ostream* stream,
  4213. const std::string& element_name,
  4214. const std::string& name,
  4215. const std::string& value);
  4216. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  4217. static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
  4218. // Streams an XML representation of a TestInfo object.
  4219. static void OutputXmlTestInfo(::std::ostream* stream,
  4220. const char* test_case_name,
  4221. const TestInfo& test_info);
  4222. // Prints an XML representation of a TestCase object
  4223. static void PrintXmlTestCase(::std::ostream* stream,
  4224. const TestCase& test_case);
  4225. // Prints an XML summary of unit_test to output stream out.
  4226. static void PrintXmlUnitTest(::std::ostream* stream,
  4227. const UnitTest& unit_test);
  4228. // Produces a string representing the test properties in a result as space
  4229. // delimited XML attributes based on the property key="value" pairs.
  4230. // When the std::string is not empty, it includes a space at the beginning,
  4231. // to delimit this attribute from prior attributes.
  4232. static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
  4233. // Streams an XML representation of the test properties of a TestResult
  4234. // object.
  4235. static void OutputXmlTestProperties(std::ostream* stream,
  4236. const TestResult& result);
  4237. // The output file.
  4238. const std::string output_file_;
  4239. GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
  4240. };
  4241. // Creates a new XmlUnitTestResultPrinter.
  4242. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
  4243. : output_file_(output_file) {
  4244. if (output_file_.empty()) {
  4245. GTEST_LOG_(FATAL) << "XML output file may not be null";
  4246. }
  4247. }
  4248. // Called after the unit test ends.
  4249. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4250. int /*iteration*/) {
  4251. FILE* xmlout = OpenFileForWriting(output_file_);
  4252. std::stringstream stream;
  4253. PrintXmlUnitTest(&stream, unit_test);
  4254. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  4255. fclose(xmlout);
  4256. }
  4257. void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
  4258. const std::vector<TestCase*>& test_cases) {
  4259. FILE* xmlout = OpenFileForWriting(output_file_);
  4260. std::stringstream stream;
  4261. PrintXmlTestsList(&stream, test_cases);
  4262. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  4263. fclose(xmlout);
  4264. }
  4265. // Returns an XML-escaped copy of the input string str. If is_attribute
  4266. // is true, the text is meant to appear as an attribute value, and
  4267. // normalizable whitespace is preserved by replacing it with character
  4268. // references.
  4269. //
  4270. // Invalid XML characters in str, if any, are stripped from the output.
  4271. // It is expected that most, if not all, of the text processed by this
  4272. // module will consist of ordinary English text.
  4273. // If this module is ever modified to produce version 1.1 XML output,
  4274. // most invalid characters can be retained using character references.
  4275. // FIXME: It might be nice to have a minimally invasive, human-readable
  4276. // escaping scheme for invalid characters, rather than dropping them.
  4277. std::string XmlUnitTestResultPrinter::EscapeXml(
  4278. const std::string& str, bool is_attribute) {
  4279. Message m;
  4280. for (size_t i = 0; i < str.size(); ++i) {
  4281. const char ch = str[i];
  4282. switch (ch) {
  4283. case '<':
  4284. m << "&lt;";
  4285. break;
  4286. case '>':
  4287. m << "&gt;";
  4288. break;
  4289. case '&':
  4290. m << "&amp;";
  4291. break;
  4292. case '\'':
  4293. if (is_attribute)
  4294. m << "&apos;";
  4295. else
  4296. m << '\'';
  4297. break;
  4298. case '"':
  4299. if (is_attribute)
  4300. m << "&quot;";
  4301. else
  4302. m << '"';
  4303. break;
  4304. default:
  4305. if (IsValidXmlCharacter(ch)) {
  4306. if (is_attribute && IsNormalizableWhitespace(ch))
  4307. m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
  4308. << ";";
  4309. else
  4310. m << ch;
  4311. }
  4312. break;
  4313. }
  4314. }
  4315. return m.GetString();
  4316. }
  4317. // Returns the given string with all characters invalid in XML removed.
  4318. // Currently invalid characters are dropped from the string. An
  4319. // alternative is to replace them with certain characters such as . or ?.
  4320. std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
  4321. const std::string& str) {
  4322. std::string output;
  4323. output.reserve(str.size());
  4324. for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
  4325. if (IsValidXmlCharacter(*it))
  4326. output.push_back(*it);
  4327. return output;
  4328. }
  4329. // The following routines generate an XML representation of a UnitTest
  4330. // object.
  4331. // GOOGLETEST_CM0009 DO NOT DELETE
  4332. //
  4333. // This is how Google Test concepts map to the DTD:
  4334. //
  4335. // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
  4336. // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
  4337. // <testcase name="test-name"> <-- corresponds to a TestInfo object
  4338. // <failure message="...">...</failure>
  4339. // <failure message="...">...</failure>
  4340. // <failure message="...">...</failure>
  4341. // <-- individual assertion failures
  4342. // </testcase>
  4343. // </testsuite>
  4344. // </testsuites>
  4345. // Formats the given time in milliseconds as seconds.
  4346. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
  4347. ::std::stringstream ss;
  4348. ss << (static_cast<double>(ms) * 1e-3);
  4349. return ss.str();
  4350. }
  4351. static bool PortableLocaltime(time_t seconds, struct tm* out) {
  4352. #if defined(_MSC_VER)
  4353. return localtime_s(out, &seconds) == 0;
  4354. #elif defined(__MINGW32__) || defined(__MINGW64__)
  4355. // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
  4356. // Windows' localtime(), which has a thread-local tm buffer.
  4357. struct tm* tm_ptr = localtime(&seconds); // NOLINT
  4358. if (tm_ptr == NULL)
  4359. return false;
  4360. *out = *tm_ptr;
  4361. return true;
  4362. #else
  4363. return localtime_r(&seconds, out) != NULL;
  4364. #endif
  4365. }
  4366. // Converts the given epoch time in milliseconds to a date string in the ISO
  4367. // 8601 format, without the timezone information.
  4368. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
  4369. struct tm time_struct;
  4370. if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  4371. return "";
  4372. // YYYY-MM-DDThh:mm:ss
  4373. return StreamableToString(time_struct.tm_year + 1900) + "-" +
  4374. String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  4375. String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  4376. String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  4377. String::FormatIntWidth2(time_struct.tm_min) + ":" +
  4378. String::FormatIntWidth2(time_struct.tm_sec);
  4379. }
  4380. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  4381. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
  4382. const char* data) {
  4383. const char* segment = data;
  4384. *stream << "<![CDATA[";
  4385. for (;;) {
  4386. const char* const next_segment = strstr(segment, "]]>");
  4387. if (next_segment != NULL) {
  4388. stream->write(
  4389. segment, static_cast<std::streamsize>(next_segment - segment));
  4390. *stream << "]]>]]&gt;<![CDATA[";
  4391. segment = next_segment + strlen("]]>");
  4392. } else {
  4393. *stream << segment;
  4394. break;
  4395. }
  4396. }
  4397. *stream << "]]>";
  4398. }
  4399. void XmlUnitTestResultPrinter::OutputXmlAttribute(
  4400. std::ostream* stream,
  4401. const std::string& element_name,
  4402. const std::string& name,
  4403. const std::string& value) {
  4404. const std::vector<std::string>& allowed_names =
  4405. GetReservedAttributesForElement(element_name);
  4406. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4407. allowed_names.end())
  4408. << "Attribute " << name << " is not allowed for element <" << element_name
  4409. << ">.";
  4410. *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
  4411. }
  4412. // Prints an XML representation of a TestInfo object.
  4413. // FIXME: There is also value in printing properties with the plain printer.
  4414. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
  4415. const char* test_case_name,
  4416. const TestInfo& test_info) {
  4417. const TestResult& result = *test_info.result();
  4418. const std::string kTestcase = "testcase";
  4419. if (test_info.is_in_another_shard()) {
  4420. return;
  4421. }
  4422. *stream << " <testcase";
  4423. OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
  4424. if (test_info.value_param() != NULL) {
  4425. OutputXmlAttribute(stream, kTestcase, "value_param",
  4426. test_info.value_param());
  4427. }
  4428. if (test_info.type_param() != NULL) {
  4429. OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
  4430. }
  4431. if (GTEST_FLAG(list_tests)) {
  4432. OutputXmlAttribute(stream, kTestcase, "file", test_info.file());
  4433. OutputXmlAttribute(stream, kTestcase, "line",
  4434. StreamableToString(test_info.line()));
  4435. *stream << " />\n";
  4436. return;
  4437. }
  4438. OutputXmlAttribute(stream, kTestcase, "status",
  4439. test_info.should_run() ? "run" : "notrun");
  4440. OutputXmlAttribute(stream, kTestcase, "time",
  4441. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  4442. OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
  4443. int failures = 0;
  4444. for (int i = 0; i < result.total_part_count(); ++i) {
  4445. const TestPartResult& part = result.GetTestPartResult(i);
  4446. if (part.failed()) {
  4447. if (++failures == 1) {
  4448. *stream << ">\n";
  4449. }
  4450. const std::string location =
  4451. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  4452. part.line_number());
  4453. const std::string summary = location + "\n" + part.summary();
  4454. *stream << " <failure message=\""
  4455. << EscapeXmlAttribute(summary.c_str())
  4456. << "\" type=\"\">";
  4457. const std::string detail = location + "\n" + part.message();
  4458. OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
  4459. *stream << "</failure>\n";
  4460. }
  4461. }
  4462. if (failures == 0 && result.test_property_count() == 0) {
  4463. *stream << " />\n";
  4464. } else {
  4465. if (failures == 0) {
  4466. *stream << ">\n";
  4467. }
  4468. OutputXmlTestProperties(stream, result);
  4469. *stream << " </testcase>\n";
  4470. }
  4471. }
  4472. // Prints an XML representation of a TestCase object
  4473. void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
  4474. const TestCase& test_case) {
  4475. const std::string kTestsuite = "testsuite";
  4476. *stream << " <" << kTestsuite;
  4477. OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
  4478. OutputXmlAttribute(stream, kTestsuite, "tests",
  4479. StreamableToString(test_case.reportable_test_count()));
  4480. if (!GTEST_FLAG(list_tests)) {
  4481. OutputXmlAttribute(stream, kTestsuite, "failures",
  4482. StreamableToString(test_case.failed_test_count()));
  4483. OutputXmlAttribute(
  4484. stream, kTestsuite, "disabled",
  4485. StreamableToString(test_case.reportable_disabled_test_count()));
  4486. OutputXmlAttribute(stream, kTestsuite, "errors", "0");
  4487. OutputXmlAttribute(stream, kTestsuite, "time",
  4488. FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
  4489. *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result());
  4490. }
  4491. *stream << ">\n";
  4492. for (int i = 0; i < test_case.total_test_count(); ++i) {
  4493. if (test_case.GetTestInfo(i)->is_reportable())
  4494. OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
  4495. }
  4496. *stream << " </" << kTestsuite << ">\n";
  4497. }
  4498. // Prints an XML summary of unit_test to output stream out.
  4499. void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
  4500. const UnitTest& unit_test) {
  4501. const std::string kTestsuites = "testsuites";
  4502. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  4503. *stream << "<" << kTestsuites;
  4504. OutputXmlAttribute(stream, kTestsuites, "tests",
  4505. StreamableToString(unit_test.reportable_test_count()));
  4506. OutputXmlAttribute(stream, kTestsuites, "failures",
  4507. StreamableToString(unit_test.failed_test_count()));
  4508. OutputXmlAttribute(
  4509. stream, kTestsuites, "disabled",
  4510. StreamableToString(unit_test.reportable_disabled_test_count()));
  4511. OutputXmlAttribute(stream, kTestsuites, "errors", "0");
  4512. OutputXmlAttribute(
  4513. stream, kTestsuites, "timestamp",
  4514. FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
  4515. OutputXmlAttribute(stream, kTestsuites, "time",
  4516. FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
  4517. if (GTEST_FLAG(shuffle)) {
  4518. OutputXmlAttribute(stream, kTestsuites, "random_seed",
  4519. StreamableToString(unit_test.random_seed()));
  4520. }
  4521. *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
  4522. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  4523. *stream << ">\n";
  4524. for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  4525. if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
  4526. PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
  4527. }
  4528. *stream << "</" << kTestsuites << ">\n";
  4529. }
  4530. void XmlUnitTestResultPrinter::PrintXmlTestsList(
  4531. std::ostream* stream, const std::vector<TestCase*>& test_cases) {
  4532. const std::string kTestsuites = "testsuites";
  4533. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  4534. *stream << "<" << kTestsuites;
  4535. int total_tests = 0;
  4536. for (size_t i = 0; i < test_cases.size(); ++i) {
  4537. total_tests += test_cases[i]->total_test_count();
  4538. }
  4539. OutputXmlAttribute(stream, kTestsuites, "tests",
  4540. StreamableToString(total_tests));
  4541. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  4542. *stream << ">\n";
  4543. for (size_t i = 0; i < test_cases.size(); ++i) {
  4544. PrintXmlTestCase(stream, *test_cases[i]);
  4545. }
  4546. *stream << "</" << kTestsuites << ">\n";
  4547. }
  4548. // Produces a string representing the test properties in a result as space
  4549. // delimited XML attributes based on the property key="value" pairs.
  4550. std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
  4551. const TestResult& result) {
  4552. Message attributes;
  4553. for (int i = 0; i < result.test_property_count(); ++i) {
  4554. const TestProperty& property = result.GetTestProperty(i);
  4555. attributes << " " << property.key() << "="
  4556. << "\"" << EscapeXmlAttribute(property.value()) << "\"";
  4557. }
  4558. return attributes.GetString();
  4559. }
  4560. void XmlUnitTestResultPrinter::OutputXmlTestProperties(
  4561. std::ostream* stream, const TestResult& result) {
  4562. const std::string kProperties = "properties";
  4563. const std::string kProperty = "property";
  4564. if (result.test_property_count() <= 0) {
  4565. return;
  4566. }
  4567. *stream << "<" << kProperties << ">\n";
  4568. for (int i = 0; i < result.test_property_count(); ++i) {
  4569. const TestProperty& property = result.GetTestProperty(i);
  4570. *stream << "<" << kProperty;
  4571. *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
  4572. *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
  4573. *stream << "/>\n";
  4574. }
  4575. *stream << "</" << kProperties << ">\n";
  4576. }
  4577. // End XmlUnitTestResultPrinter
  4578. // This class generates an JSON output file.
  4579. class JsonUnitTestResultPrinter : public EmptyTestEventListener {
  4580. public:
  4581. explicit JsonUnitTestResultPrinter(const char* output_file);
  4582. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  4583. // Prints an JSON summary of all unit tests.
  4584. static void PrintJsonTestList(::std::ostream* stream,
  4585. const std::vector<TestCase*>& test_cases);
  4586. private:
  4587. // Returns an JSON-escaped copy of the input string str.
  4588. static std::string EscapeJson(const std::string& str);
  4589. //// Verifies that the given attribute belongs to the given element and
  4590. //// streams the attribute as JSON.
  4591. static void OutputJsonKey(std::ostream* stream,
  4592. const std::string& element_name,
  4593. const std::string& name,
  4594. const std::string& value,
  4595. const std::string& indent,
  4596. bool comma = true);
  4597. static void OutputJsonKey(std::ostream* stream,
  4598. const std::string& element_name,
  4599. const std::string& name,
  4600. int value,
  4601. const std::string& indent,
  4602. bool comma = true);
  4603. // Streams a JSON representation of a TestInfo object.
  4604. static void OutputJsonTestInfo(::std::ostream* stream,
  4605. const char* test_case_name,
  4606. const TestInfo& test_info);
  4607. // Prints a JSON representation of a TestCase object
  4608. static void PrintJsonTestCase(::std::ostream* stream,
  4609. const TestCase& test_case);
  4610. // Prints a JSON summary of unit_test to output stream out.
  4611. static void PrintJsonUnitTest(::std::ostream* stream,
  4612. const UnitTest& unit_test);
  4613. // Produces a string representing the test properties in a result as
  4614. // a JSON dictionary.
  4615. static std::string TestPropertiesAsJson(const TestResult& result,
  4616. const std::string& indent);
  4617. // The output file.
  4618. const std::string output_file_;
  4619. GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
  4620. };
  4621. // Creates a new JsonUnitTestResultPrinter.
  4622. JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
  4623. : output_file_(output_file) {
  4624. if (output_file_.empty()) {
  4625. GTEST_LOG_(FATAL) << "JSON output file may not be null";
  4626. }
  4627. }
  4628. void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4629. int /*iteration*/) {
  4630. FILE* jsonout = OpenFileForWriting(output_file_);
  4631. std::stringstream stream;
  4632. PrintJsonUnitTest(&stream, unit_test);
  4633. fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
  4634. fclose(jsonout);
  4635. }
  4636. // Returns an JSON-escaped copy of the input string str.
  4637. std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
  4638. Message m;
  4639. for (size_t i = 0; i < str.size(); ++i) {
  4640. const char ch = str[i];
  4641. switch (ch) {
  4642. case '\\':
  4643. case '"':
  4644. case '/':
  4645. m << '\\' << ch;
  4646. break;
  4647. case '\b':
  4648. m << "\\b";
  4649. break;
  4650. case '\t':
  4651. m << "\\t";
  4652. break;
  4653. case '\n':
  4654. m << "\\n";
  4655. break;
  4656. case '\f':
  4657. m << "\\f";
  4658. break;
  4659. case '\r':
  4660. m << "\\r";
  4661. break;
  4662. default:
  4663. if (ch < ' ') {
  4664. m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
  4665. } else {
  4666. m << ch;
  4667. }
  4668. break;
  4669. }
  4670. }
  4671. return m.GetString();
  4672. }
  4673. // The following routines generate an JSON representation of a UnitTest
  4674. // object.
  4675. // Formats the given time in milliseconds as seconds.
  4676. static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
  4677. ::std::stringstream ss;
  4678. ss << (static_cast<double>(ms) * 1e-3) << "s";
  4679. return ss.str();
  4680. }
  4681. // Converts the given epoch time in milliseconds to a date string in the
  4682. // RFC3339 format, without the timezone information.
  4683. static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
  4684. struct tm time_struct;
  4685. if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  4686. return "";
  4687. // YYYY-MM-DDThh:mm:ss
  4688. return StreamableToString(time_struct.tm_year + 1900) + "-" +
  4689. String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  4690. String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  4691. String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  4692. String::FormatIntWidth2(time_struct.tm_min) + ":" +
  4693. String::FormatIntWidth2(time_struct.tm_sec) + "Z";
  4694. }
  4695. static inline std::string Indent(int width) {
  4696. return std::string(width, ' ');
  4697. }
  4698. void JsonUnitTestResultPrinter::OutputJsonKey(
  4699. std::ostream* stream,
  4700. const std::string& element_name,
  4701. const std::string& name,
  4702. const std::string& value,
  4703. const std::string& indent,
  4704. bool comma) {
  4705. const std::vector<std::string>& allowed_names =
  4706. GetReservedAttributesForElement(element_name);
  4707. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4708. allowed_names.end())
  4709. << "Key \"" << name << "\" is not allowed for value \"" << element_name
  4710. << "\".";
  4711. *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
  4712. if (comma)
  4713. *stream << ",\n";
  4714. }
  4715. void JsonUnitTestResultPrinter::OutputJsonKey(
  4716. std::ostream* stream,
  4717. const std::string& element_name,
  4718. const std::string& name,
  4719. int value,
  4720. const std::string& indent,
  4721. bool comma) {
  4722. const std::vector<std::string>& allowed_names =
  4723. GetReservedAttributesForElement(element_name);
  4724. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4725. allowed_names.end())
  4726. << "Key \"" << name << "\" is not allowed for value \"" << element_name
  4727. << "\".";
  4728. *stream << indent << "\"" << name << "\": " << StreamableToString(value);
  4729. if (comma)
  4730. *stream << ",\n";
  4731. }
  4732. // Prints a JSON representation of a TestInfo object.
  4733. void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
  4734. const char* test_case_name,
  4735. const TestInfo& test_info) {
  4736. const TestResult& result = *test_info.result();
  4737. const std::string kTestcase = "testcase";
  4738. const std::string kIndent = Indent(10);
  4739. *stream << Indent(8) << "{\n";
  4740. OutputJsonKey(stream, kTestcase, "name", test_info.name(), kIndent);
  4741. if (test_info.value_param() != NULL) {
  4742. OutputJsonKey(stream, kTestcase, "value_param",
  4743. test_info.value_param(), kIndent);
  4744. }
  4745. if (test_info.type_param() != NULL) {
  4746. OutputJsonKey(stream, kTestcase, "type_param", test_info.type_param(),
  4747. kIndent);
  4748. }
  4749. if (GTEST_FLAG(list_tests)) {
  4750. OutputJsonKey(stream, kTestcase, "file", test_info.file(), kIndent);
  4751. OutputJsonKey(stream, kTestcase, "line", test_info.line(), kIndent, false);
  4752. *stream << "\n" << Indent(8) << "}";
  4753. return;
  4754. }
  4755. OutputJsonKey(stream, kTestcase, "status",
  4756. test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
  4757. OutputJsonKey(stream, kTestcase, "time",
  4758. FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
  4759. OutputJsonKey(stream, kTestcase, "classname", test_case_name, kIndent, false);
  4760. *stream << TestPropertiesAsJson(result, kIndent);
  4761. int failures = 0;
  4762. for (int i = 0; i < result.total_part_count(); ++i) {
  4763. const TestPartResult& part = result.GetTestPartResult(i);
  4764. if (part.failed()) {
  4765. *stream << ",\n";
  4766. if (++failures == 1) {
  4767. *stream << kIndent << "\"" << "failures" << "\": [\n";
  4768. }
  4769. const std::string location =
  4770. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  4771. part.line_number());
  4772. const std::string message = EscapeJson(location + "\n" + part.message());
  4773. *stream << kIndent << " {\n"
  4774. << kIndent << " \"failure\": \"" << message << "\",\n"
  4775. << kIndent << " \"type\": \"\"\n"
  4776. << kIndent << " }";
  4777. }
  4778. }
  4779. if (failures > 0)
  4780. *stream << "\n" << kIndent << "]";
  4781. *stream << "\n" << Indent(8) << "}";
  4782. }
  4783. // Prints an JSON representation of a TestCase object
  4784. void JsonUnitTestResultPrinter::PrintJsonTestCase(std::ostream* stream,
  4785. const TestCase& test_case) {
  4786. const std::string kTestsuite = "testsuite";
  4787. const std::string kIndent = Indent(6);
  4788. *stream << Indent(4) << "{\n";
  4789. OutputJsonKey(stream, kTestsuite, "name", test_case.name(), kIndent);
  4790. OutputJsonKey(stream, kTestsuite, "tests", test_case.reportable_test_count(),
  4791. kIndent);
  4792. if (!GTEST_FLAG(list_tests)) {
  4793. OutputJsonKey(stream, kTestsuite, "failures", test_case.failed_test_count(),
  4794. kIndent);
  4795. OutputJsonKey(stream, kTestsuite, "disabled",
  4796. test_case.reportable_disabled_test_count(), kIndent);
  4797. OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
  4798. OutputJsonKey(stream, kTestsuite, "time",
  4799. FormatTimeInMillisAsDuration(test_case.elapsed_time()),
  4800. kIndent, false);
  4801. *stream << TestPropertiesAsJson(test_case.ad_hoc_test_result(), kIndent)
  4802. << ",\n";
  4803. }
  4804. *stream << kIndent << "\"" << kTestsuite << "\": [\n";
  4805. bool comma = false;
  4806. for (int i = 0; i < test_case.total_test_count(); ++i) {
  4807. if (test_case.GetTestInfo(i)->is_reportable()) {
  4808. if (comma) {
  4809. *stream << ",\n";
  4810. } else {
  4811. comma = true;
  4812. }
  4813. OutputJsonTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
  4814. }
  4815. }
  4816. *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
  4817. }
  4818. // Prints a JSON summary of unit_test to output stream out.
  4819. void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
  4820. const UnitTest& unit_test) {
  4821. const std::string kTestsuites = "testsuites";
  4822. const std::string kIndent = Indent(2);
  4823. *stream << "{\n";
  4824. OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
  4825. kIndent);
  4826. OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
  4827. kIndent);
  4828. OutputJsonKey(stream, kTestsuites, "disabled",
  4829. unit_test.reportable_disabled_test_count(), kIndent);
  4830. OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
  4831. if (GTEST_FLAG(shuffle)) {
  4832. OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
  4833. kIndent);
  4834. }
  4835. OutputJsonKey(stream, kTestsuites, "timestamp",
  4836. FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
  4837. kIndent);
  4838. OutputJsonKey(stream, kTestsuites, "time",
  4839. FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
  4840. false);
  4841. *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
  4842. << ",\n";
  4843. OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  4844. *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  4845. bool comma = false;
  4846. for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  4847. if (unit_test.GetTestCase(i)->reportable_test_count() > 0) {
  4848. if (comma) {
  4849. *stream << ",\n";
  4850. } else {
  4851. comma = true;
  4852. }
  4853. PrintJsonTestCase(stream, *unit_test.GetTestCase(i));
  4854. }
  4855. }
  4856. *stream << "\n" << kIndent << "]\n" << "}\n";
  4857. }
  4858. void JsonUnitTestResultPrinter::PrintJsonTestList(
  4859. std::ostream* stream, const std::vector<TestCase*>& test_cases) {
  4860. const std::string kTestsuites = "testsuites";
  4861. const std::string kIndent = Indent(2);
  4862. *stream << "{\n";
  4863. int total_tests = 0;
  4864. for (size_t i = 0; i < test_cases.size(); ++i) {
  4865. total_tests += test_cases[i]->total_test_count();
  4866. }
  4867. OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
  4868. OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  4869. *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  4870. for (size_t i = 0; i < test_cases.size(); ++i) {
  4871. if (i != 0) {
  4872. *stream << ",\n";
  4873. }
  4874. PrintJsonTestCase(stream, *test_cases[i]);
  4875. }
  4876. *stream << "\n"
  4877. << kIndent << "]\n"
  4878. << "}\n";
  4879. }
  4880. // Produces a string representing the test properties in a result as
  4881. // a JSON dictionary.
  4882. std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
  4883. const TestResult& result, const std::string& indent) {
  4884. Message attributes;
  4885. for (int i = 0; i < result.test_property_count(); ++i) {
  4886. const TestProperty& property = result.GetTestProperty(i);
  4887. attributes << ",\n" << indent << "\"" << property.key() << "\": "
  4888. << "\"" << EscapeJson(property.value()) << "\"";
  4889. }
  4890. return attributes.GetString();
  4891. }
  4892. // End JsonUnitTestResultPrinter
  4893. #if GTEST_CAN_STREAM_RESULTS_
  4894. // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
  4895. // replaces them by "%xx" where xx is their hexadecimal value. For
  4896. // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
  4897. // in both time and space -- important as the input str may contain an
  4898. // arbitrarily long test failure message and stack trace.
  4899. std::string StreamingListener::UrlEncode(const char* str) {
  4900. std::string result;
  4901. result.reserve(strlen(str) + 1);
  4902. for (char ch = *str; ch != '\0'; ch = *++str) {
  4903. switch (ch) {
  4904. case '%':
  4905. case '=':
  4906. case '&':
  4907. case '\n':
  4908. result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
  4909. break;
  4910. default:
  4911. result.push_back(ch);
  4912. break;
  4913. }
  4914. }
  4915. return result;
  4916. }
  4917. void StreamingListener::SocketWriter::MakeConnection() {
  4918. GTEST_CHECK_(sockfd_ == -1)
  4919. << "MakeConnection() can't be called when there is already a connection.";
  4920. addrinfo hints;
  4921. memset(&hints, 0, sizeof(hints));
  4922. hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
  4923. hints.ai_socktype = SOCK_STREAM;
  4924. addrinfo* servinfo = NULL;
  4925. // Use the getaddrinfo() to get a linked list of IP addresses for
  4926. // the given host name.
  4927. const int error_num = getaddrinfo(
  4928. host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
  4929. if (error_num != 0) {
  4930. GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
  4931. << gai_strerror(error_num);
  4932. }
  4933. // Loop through all the results and connect to the first we can.
  4934. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
  4935. cur_addr = cur_addr->ai_next) {
  4936. sockfd_ = socket(
  4937. cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
  4938. if (sockfd_ != -1) {
  4939. // Connect the client socket to the server socket.
  4940. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
  4941. close(sockfd_);
  4942. sockfd_ = -1;
  4943. }
  4944. }
  4945. }
  4946. freeaddrinfo(servinfo); // all done with this structure
  4947. if (sockfd_ == -1) {
  4948. GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
  4949. << host_name_ << ":" << port_num_;
  4950. }
  4951. }
  4952. // End of class Streaming Listener
  4953. #endif // GTEST_CAN_STREAM_RESULTS__
  4954. // class OsStackTraceGetter
  4955. const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
  4956. "... " GTEST_NAME_ " internal frames ...";
  4957. std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
  4958. GTEST_LOCK_EXCLUDED_(mutex_) {
  4959. #if GTEST_HAS_ABSL
  4960. std::string result;
  4961. if (max_depth <= 0) {
  4962. return result;
  4963. }
  4964. max_depth = std::min(max_depth, kMaxStackTraceDepth);
  4965. std::vector<void*> raw_stack(max_depth);
  4966. // Skips the frames requested by the caller, plus this function.
  4967. const int raw_stack_size =
  4968. absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
  4969. void* caller_frame = nullptr;
  4970. {
  4971. MutexLock lock(&mutex_);
  4972. caller_frame = caller_frame_;
  4973. }
  4974. for (int i = 0; i < raw_stack_size; ++i) {
  4975. if (raw_stack[i] == caller_frame &&
  4976. !GTEST_FLAG(show_internal_stack_frames)) {
  4977. // Add a marker to the trace and stop adding frames.
  4978. absl::StrAppend(&result, kElidedFramesMarker, "\n");
  4979. break;
  4980. }
  4981. char tmp[1024];
  4982. const char* symbol = "(unknown)";
  4983. if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
  4984. symbol = tmp;
  4985. }
  4986. char line[1024];
  4987. snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
  4988. result += line;
  4989. }
  4990. return result;
  4991. #else // !GTEST_HAS_ABSL
  4992. static_cast<void>(max_depth);
  4993. static_cast<void>(skip_count);
  4994. return "";
  4995. #endif // GTEST_HAS_ABSL
  4996. }
  4997. void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
  4998. #if GTEST_HAS_ABSL
  4999. void* caller_frame = nullptr;
  5000. if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
  5001. caller_frame = nullptr;
  5002. }
  5003. MutexLock lock(&mutex_);
  5004. caller_frame_ = caller_frame;
  5005. #endif // GTEST_HAS_ABSL
  5006. }
  5007. // A helper class that creates the premature-exit file in its
  5008. // constructor and deletes the file in its destructor.
  5009. class ScopedPrematureExitFile {
  5010. public:
  5011. explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
  5012. : premature_exit_filepath_(premature_exit_filepath ?
  5013. premature_exit_filepath : "") {
  5014. // If a path to the premature-exit file is specified...
  5015. if (!premature_exit_filepath_.empty()) {
  5016. // create the file with a single "0" character in it. I/O
  5017. // errors are ignored as there's nothing better we can do and we
  5018. // don't want to fail the test because of this.
  5019. FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
  5020. fwrite("0", 1, 1, pfile);
  5021. fclose(pfile);
  5022. }
  5023. }
  5024. ~ScopedPrematureExitFile() {
  5025. if (!premature_exit_filepath_.empty()) {
  5026. int retval = remove(premature_exit_filepath_.c_str());
  5027. if (retval) {
  5028. GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
  5029. << premature_exit_filepath_ << "\" with error "
  5030. << retval;
  5031. }
  5032. }
  5033. }
  5034. private:
  5035. const std::string premature_exit_filepath_;
  5036. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
  5037. };
  5038. } // namespace internal
  5039. // class TestEventListeners
  5040. TestEventListeners::TestEventListeners()
  5041. : repeater_(new internal::TestEventRepeater()),
  5042. default_result_printer_(NULL),
  5043. default_xml_generator_(NULL) {
  5044. }
  5045. TestEventListeners::~TestEventListeners() { delete repeater_; }
  5046. // Returns the standard listener responsible for the default console
  5047. // output. Can be removed from the listeners list to shut down default
  5048. // console output. Note that removing this object from the listener list
  5049. // with Release transfers its ownership to the user.
  5050. void TestEventListeners::Append(TestEventListener* listener) {
  5051. repeater_->Append(listener);
  5052. }
  5053. // Removes the given event listener from the list and returns it. It then
  5054. // becomes the caller's responsibility to delete the listener. Returns
  5055. // NULL if the listener is not found in the list.
  5056. TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
  5057. if (listener == default_result_printer_)
  5058. default_result_printer_ = NULL;
  5059. else if (listener == default_xml_generator_)
  5060. default_xml_generator_ = NULL;
  5061. return repeater_->Release(listener);
  5062. }
  5063. // Returns repeater that broadcasts the TestEventListener events to all
  5064. // subscribers.
  5065. TestEventListener* TestEventListeners::repeater() { return repeater_; }
  5066. // Sets the default_result_printer attribute to the provided listener.
  5067. // The listener is also added to the listener list and previous
  5068. // default_result_printer is removed from it and deleted. The listener can
  5069. // also be NULL in which case it will not be added to the list. Does
  5070. // nothing if the previous and the current listener objects are the same.
  5071. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
  5072. if (default_result_printer_ != listener) {
  5073. // It is an error to pass this method a listener that is already in the
  5074. // list.
  5075. delete Release(default_result_printer_);
  5076. default_result_printer_ = listener;
  5077. if (listener != NULL)
  5078. Append(listener);
  5079. }
  5080. }
  5081. // Sets the default_xml_generator attribute to the provided listener. The
  5082. // listener is also added to the listener list and previous
  5083. // default_xml_generator is removed from it and deleted. The listener can
  5084. // also be NULL in which case it will not be added to the list. Does
  5085. // nothing if the previous and the current listener objects are the same.
  5086. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
  5087. if (default_xml_generator_ != listener) {
  5088. // It is an error to pass this method a listener that is already in the
  5089. // list.
  5090. delete Release(default_xml_generator_);
  5091. default_xml_generator_ = listener;
  5092. if (listener != NULL)
  5093. Append(listener);
  5094. }
  5095. }
  5096. // Controls whether events will be forwarded by the repeater to the
  5097. // listeners in the list.
  5098. bool TestEventListeners::EventForwardingEnabled() const {
  5099. return repeater_->forwarding_enabled();
  5100. }
  5101. void TestEventListeners::SuppressEventForwarding() {
  5102. repeater_->set_forwarding_enabled(false);
  5103. }
  5104. // class UnitTest
  5105. // Gets the singleton UnitTest object. The first time this method is
  5106. // called, a UnitTest object is constructed and returned. Consecutive
  5107. // calls will return the same object.
  5108. //
  5109. // We don't protect this under mutex_ as a user is not supposed to
  5110. // call this before main() starts, from which point on the return
  5111. // value will never change.
  5112. UnitTest* UnitTest::GetInstance() {
  5113. // When compiled with MSVC 7.1 in optimized mode, destroying the
  5114. // UnitTest object upon exiting the program messes up the exit code,
  5115. // causing successful tests to appear failed. We have to use a
  5116. // different implementation in this case to bypass the compiler bug.
  5117. // This implementation makes the compiler happy, at the cost of
  5118. // leaking the UnitTest object.
  5119. // CodeGear C++Builder insists on a public destructor for the
  5120. // default implementation. Use this implementation to keep good OO
  5121. // design with private destructor.
  5122. #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  5123. static UnitTest* const instance = new UnitTest;
  5124. return instance;
  5125. #else
  5126. static UnitTest instance;
  5127. return &instance;
  5128. #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  5129. }
  5130. // Gets the number of successful test cases.
  5131. int UnitTest::successful_test_case_count() const {
  5132. return impl()->successful_test_case_count();
  5133. }
  5134. // Gets the number of failed test cases.
  5135. int UnitTest::failed_test_case_count() const {
  5136. return impl()->failed_test_case_count();
  5137. }
  5138. // Gets the number of all test cases.
  5139. int UnitTest::total_test_case_count() const {
  5140. return impl()->total_test_case_count();
  5141. }
  5142. // Gets the number of all test cases that contain at least one test
  5143. // that should run.
  5144. int UnitTest::test_case_to_run_count() const {
  5145. return impl()->test_case_to_run_count();
  5146. }
  5147. // Gets the number of successful tests.
  5148. int UnitTest::successful_test_count() const {
  5149. return impl()->successful_test_count();
  5150. }
  5151. // Gets the number of failed tests.
  5152. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
  5153. // Gets the number of disabled tests that will be reported in the XML report.
  5154. int UnitTest::reportable_disabled_test_count() const {
  5155. return impl()->reportable_disabled_test_count();
  5156. }
  5157. // Gets the number of disabled tests.
  5158. int UnitTest::disabled_test_count() const {
  5159. return impl()->disabled_test_count();
  5160. }
  5161. // Gets the number of tests to be printed in the XML report.
  5162. int UnitTest::reportable_test_count() const {
  5163. return impl()->reportable_test_count();
  5164. }
  5165. // Gets the number of all tests.
  5166. int UnitTest::total_test_count() const { return impl()->total_test_count(); }
  5167. // Gets the number of tests that should run.
  5168. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
  5169. // Gets the time of the test program start, in ms from the start of the
  5170. // UNIX epoch.
  5171. internal::TimeInMillis UnitTest::start_timestamp() const {
  5172. return impl()->start_timestamp();
  5173. }
  5174. // Gets the elapsed time, in milliseconds.
  5175. internal::TimeInMillis UnitTest::elapsed_time() const {
  5176. return impl()->elapsed_time();
  5177. }
  5178. // Returns true iff the unit test passed (i.e. all test cases passed).
  5179. bool UnitTest::Passed() const { return impl()->Passed(); }
  5180. // Returns true iff the unit test failed (i.e. some test case failed
  5181. // or something outside of all tests failed).
  5182. bool UnitTest::Failed() const { return impl()->Failed(); }
  5183. // Gets the i-th test case among all the test cases. i can range from 0 to
  5184. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  5185. const TestCase* UnitTest::GetTestCase(int i) const {
  5186. return impl()->GetTestCase(i);
  5187. }
  5188. // Returns the TestResult containing information on test failures and
  5189. // properties logged outside of individual test cases.
  5190. const TestResult& UnitTest::ad_hoc_test_result() const {
  5191. return *impl()->ad_hoc_test_result();
  5192. }
  5193. // Gets the i-th test case among all the test cases. i can range from 0 to
  5194. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  5195. TestCase* UnitTest::GetMutableTestCase(int i) {
  5196. return impl()->GetMutableTestCase(i);
  5197. }
  5198. // Returns the list of event listeners that can be used to track events
  5199. // inside Google Test.
  5200. TestEventListeners& UnitTest::listeners() {
  5201. return *impl()->listeners();
  5202. }
  5203. // Registers and returns a global test environment. When a test
  5204. // program is run, all global test environments will be set-up in the
  5205. // order they were registered. After all tests in the program have
  5206. // finished, all global test environments will be torn-down in the
  5207. // *reverse* order they were registered.
  5208. //
  5209. // The UnitTest object takes ownership of the given environment.
  5210. //
  5211. // We don't protect this under mutex_, as we only support calling it
  5212. // from the main thread.
  5213. Environment* UnitTest::AddEnvironment(Environment* env) {
  5214. if (env == NULL) {
  5215. return NULL;
  5216. }
  5217. impl_->environments().push_back(env);
  5218. return env;
  5219. }
  5220. // Adds a TestPartResult to the current TestResult object. All Google Test
  5221. // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
  5222. // this to report their results. The user code should use the
  5223. // assertion macros instead of calling this directly.
  5224. void UnitTest::AddTestPartResult(
  5225. TestPartResult::Type result_type,
  5226. const char* file_name,
  5227. int line_number,
  5228. const std::string& message,
  5229. const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
  5230. Message msg;
  5231. msg << message;
  5232. internal::MutexLock lock(&mutex_);
  5233. if (impl_->gtest_trace_stack().size() > 0) {
  5234. msg << "\n" << GTEST_NAME_ << " trace:";
  5235. for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
  5236. i > 0; --i) {
  5237. const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
  5238. msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
  5239. << " " << trace.message;
  5240. }
  5241. }
  5242. if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
  5243. msg << internal::kStackTraceMarker << os_stack_trace;
  5244. }
  5245. const TestPartResult result =
  5246. TestPartResult(result_type, file_name, line_number,
  5247. msg.GetString().c_str());
  5248. impl_->GetTestPartResultReporterForCurrentThread()->
  5249. ReportTestPartResult(result);
  5250. if (result_type != TestPartResult::kSuccess) {
  5251. // gtest_break_on_failure takes precedence over
  5252. // gtest_throw_on_failure. This allows a user to set the latter
  5253. // in the code (perhaps in order to use Google Test assertions
  5254. // with another testing framework) and specify the former on the
  5255. // command line for debugging.
  5256. if (GTEST_FLAG(break_on_failure)) {
  5257. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  5258. // Using DebugBreak on Windows allows gtest to still break into a debugger
  5259. // when a failure happens and both the --gtest_break_on_failure and
  5260. // the --gtest_catch_exceptions flags are specified.
  5261. DebugBreak();
  5262. #elif (!defined(__native_client__)) && \
  5263. ((defined(__clang__) || defined(__GNUC__)) && \
  5264. (defined(__x86_64__) || defined(__i386__)))
  5265. // with clang/gcc we can achieve the same effect on x86 by invoking int3
  5266. asm("int3");
  5267. #else
  5268. // Dereference NULL through a volatile pointer to prevent the compiler
  5269. // from removing. We use this rather than abort() or __builtin_trap() for
  5270. // portability: Symbian doesn't implement abort() well, and some debuggers
  5271. // don't correctly trap abort().
  5272. *static_cast<volatile int*>(NULL) = 1;
  5273. #endif // GTEST_OS_WINDOWS
  5274. } else if (GTEST_FLAG(throw_on_failure)) {
  5275. #if GTEST_HAS_EXCEPTIONS
  5276. throw internal::GoogleTestFailureException(result);
  5277. #else
  5278. // We cannot call abort() as it generates a pop-up in debug mode
  5279. // that cannot be suppressed in VC 7.1 or below.
  5280. exit(1);
  5281. #endif
  5282. }
  5283. }
  5284. }
  5285. // Adds a TestProperty to the current TestResult object when invoked from
  5286. // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
  5287. // from SetUpTestCase or TearDownTestCase, or to the global property set
  5288. // when invoked elsewhere. If the result already contains a property with
  5289. // the same key, the value will be updated.
  5290. void UnitTest::RecordProperty(const std::string& key,
  5291. const std::string& value) {
  5292. impl_->RecordProperty(TestProperty(key, value));
  5293. }
  5294. // Runs all tests in this UnitTest object and prints the result.
  5295. // Returns 0 if successful, or 1 otherwise.
  5296. //
  5297. // We don't protect this under mutex_, as we only support calling it
  5298. // from the main thread.
  5299. int UnitTest::Run() {
  5300. const bool in_death_test_child_process =
  5301. internal::GTEST_FLAG(internal_run_death_test).length() > 0;
  5302. // Google Test implements this protocol for catching that a test
  5303. // program exits before returning control to Google Test:
  5304. //
  5305. // 1. Upon start, Google Test creates a file whose absolute path
  5306. // is specified by the environment variable
  5307. // TEST_PREMATURE_EXIT_FILE.
  5308. // 2. When Google Test has finished its work, it deletes the file.
  5309. //
  5310. // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
  5311. // running a Google-Test-based test program and check the existence
  5312. // of the file at the end of the test execution to see if it has
  5313. // exited prematurely.
  5314. // If we are in the child process of a death test, don't
  5315. // create/delete the premature exit file, as doing so is unnecessary
  5316. // and will confuse the parent process. Otherwise, create/delete
  5317. // the file upon entering/leaving this function. If the program
  5318. // somehow exits before this function has a chance to return, the
  5319. // premature-exit file will be left undeleted, causing a test runner
  5320. // that understands the premature-exit-file protocol to report the
  5321. // test as having failed.
  5322. const internal::ScopedPrematureExitFile premature_exit_file(
  5323. in_death_test_child_process ?
  5324. NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
  5325. // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
  5326. // used for the duration of the program.
  5327. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
  5328. #if GTEST_OS_WINDOWS
  5329. // Either the user wants Google Test to catch exceptions thrown by the
  5330. // tests or this is executing in the context of death test child
  5331. // process. In either case the user does not want to see pop-up dialogs
  5332. // about crashes - they are expected.
  5333. if (impl()->catch_exceptions() || in_death_test_child_process) {
  5334. # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  5335. // SetErrorMode doesn't exist on CE.
  5336. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
  5337. SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
  5338. # endif // !GTEST_OS_WINDOWS_MOBILE
  5339. # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
  5340. // Death test children can be terminated with _abort(). On Windows,
  5341. // _abort() can show a dialog with a warning message. This forces the
  5342. // abort message to go to stderr instead.
  5343. _set_error_mode(_OUT_TO_STDERR);
  5344. # endif
  5345. # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
  5346. // In the debug version, Visual Studio pops up a separate dialog
  5347. // offering a choice to debug the aborted program. We need to suppress
  5348. // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
  5349. // executed. Google Test will notify the user of any unexpected
  5350. // failure via stderr.
  5351. //
  5352. // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
  5353. // Users of prior VC versions shall suffer the agony and pain of
  5354. // clicking through the countless debug dialogs.
  5355. // FIXME: find a way to suppress the abort dialog() in the
  5356. // debug mode when compiled with VC 7.1 or lower.
  5357. if (!GTEST_FLAG(break_on_failure))
  5358. _set_abort_behavior(
  5359. 0x0, // Clear the following flags:
  5360. _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
  5361. # endif
  5362. }
  5363. #endif // GTEST_OS_WINDOWS
  5364. return internal::HandleExceptionsInMethodIfSupported(
  5365. impl(),
  5366. &internal::UnitTestImpl::RunAllTests,
  5367. "auxiliary test code (environments or event listeners)") ? 0 : 1;
  5368. }
  5369. // Returns the working directory when the first TEST() or TEST_F() was
  5370. // executed.
  5371. const char* UnitTest::original_working_dir() const {
  5372. return impl_->original_working_dir_.c_str();
  5373. }
  5374. // Returns the TestCase object for the test that's currently running,
  5375. // or NULL if no test is running.
  5376. const TestCase* UnitTest::current_test_case() const
  5377. GTEST_LOCK_EXCLUDED_(mutex_) {
  5378. internal::MutexLock lock(&mutex_);
  5379. return impl_->current_test_case();
  5380. }
  5381. // Returns the TestInfo object for the test that's currently running,
  5382. // or NULL if no test is running.
  5383. const TestInfo* UnitTest::current_test_info() const
  5384. GTEST_LOCK_EXCLUDED_(mutex_) {
  5385. internal::MutexLock lock(&mutex_);
  5386. return impl_->current_test_info();
  5387. }
  5388. // Returns the random seed used at the start of the current test run.
  5389. int UnitTest::random_seed() const { return impl_->random_seed(); }
  5390. // Returns ParameterizedTestCaseRegistry object used to keep track of
  5391. // value-parameterized tests and instantiate and register them.
  5392. internal::ParameterizedTestCaseRegistry&
  5393. UnitTest::parameterized_test_registry()
  5394. GTEST_LOCK_EXCLUDED_(mutex_) {
  5395. return impl_->parameterized_test_registry();
  5396. }
  5397. // Creates an empty UnitTest.
  5398. UnitTest::UnitTest() {
  5399. impl_ = new internal::UnitTestImpl(this);
  5400. }
  5401. // Destructor of UnitTest.
  5402. UnitTest::~UnitTest() {
  5403. delete impl_;
  5404. }
  5405. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  5406. // Google Test trace stack.
  5407. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
  5408. GTEST_LOCK_EXCLUDED_(mutex_) {
  5409. internal::MutexLock lock(&mutex_);
  5410. impl_->gtest_trace_stack().push_back(trace);
  5411. }
  5412. // Pops a trace from the per-thread Google Test trace stack.
  5413. void UnitTest::PopGTestTrace()
  5414. GTEST_LOCK_EXCLUDED_(mutex_) {
  5415. internal::MutexLock lock(&mutex_);
  5416. impl_->gtest_trace_stack().pop_back();
  5417. }
  5418. namespace internal {
  5419. UnitTestImpl::UnitTestImpl(UnitTest* parent)
  5420. : parent_(parent),
  5421. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
  5422. default_global_test_part_result_reporter_(this),
  5423. default_per_thread_test_part_result_reporter_(this),
  5424. GTEST_DISABLE_MSC_WARNINGS_POP_()
  5425. global_test_part_result_repoter_(
  5426. &default_global_test_part_result_reporter_),
  5427. per_thread_test_part_result_reporter_(
  5428. &default_per_thread_test_part_result_reporter_),
  5429. parameterized_test_registry_(),
  5430. parameterized_tests_registered_(false),
  5431. last_death_test_case_(-1),
  5432. current_test_case_(NULL),
  5433. current_test_info_(NULL),
  5434. ad_hoc_test_result_(),
  5435. os_stack_trace_getter_(NULL),
  5436. post_flag_parse_init_performed_(false),
  5437. random_seed_(0), // Will be overridden by the flag before first use.
  5438. random_(0), // Will be reseeded before first use.
  5439. start_timestamp_(0),
  5440. elapsed_time_(0),
  5441. #if GTEST_HAS_DEATH_TEST
  5442. death_test_factory_(new DefaultDeathTestFactory),
  5443. #endif
  5444. // Will be overridden by the flag before first use.
  5445. catch_exceptions_(false) {
  5446. listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
  5447. }
  5448. UnitTestImpl::~UnitTestImpl() {
  5449. // Deletes every TestCase.
  5450. ForEach(test_cases_, internal::Delete<TestCase>);
  5451. // Deletes every Environment.
  5452. ForEach(environments_, internal::Delete<Environment>);
  5453. delete os_stack_trace_getter_;
  5454. }
  5455. // Adds a TestProperty to the current TestResult object when invoked in a
  5456. // context of a test, to current test case's ad_hoc_test_result when invoke
  5457. // from SetUpTestCase/TearDownTestCase, or to the global property set
  5458. // otherwise. If the result already contains a property with the same key,
  5459. // the value will be updated.
  5460. void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
  5461. std::string xml_element;
  5462. TestResult* test_result; // TestResult appropriate for property recording.
  5463. if (current_test_info_ != NULL) {
  5464. xml_element = "testcase";
  5465. test_result = &(current_test_info_->result_);
  5466. } else if (current_test_case_ != NULL) {
  5467. xml_element = "testsuite";
  5468. test_result = &(current_test_case_->ad_hoc_test_result_);
  5469. } else {
  5470. xml_element = "testsuites";
  5471. test_result = &ad_hoc_test_result_;
  5472. }
  5473. test_result->RecordProperty(xml_element, test_property);
  5474. }
  5475. #if GTEST_HAS_DEATH_TEST
  5476. // Disables event forwarding if the control is currently in a death test
  5477. // subprocess. Must not be called before InitGoogleTest.
  5478. void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
  5479. if (internal_run_death_test_flag_.get() != NULL)
  5480. listeners()->SuppressEventForwarding();
  5481. }
  5482. #endif // GTEST_HAS_DEATH_TEST
  5483. // Initializes event listeners performing XML output as specified by
  5484. // UnitTestOptions. Must not be called before InitGoogleTest.
  5485. void UnitTestImpl::ConfigureXmlOutput() {
  5486. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  5487. if (output_format == "xml") {
  5488. listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
  5489. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  5490. } else if (output_format == "json") {
  5491. listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
  5492. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  5493. } else if (output_format != "") {
  5494. GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
  5495. << output_format << "\" ignored.";
  5496. }
  5497. }
  5498. #if GTEST_CAN_STREAM_RESULTS_
  5499. // Initializes event listeners for streaming test results in string form.
  5500. // Must not be called before InitGoogleTest.
  5501. void UnitTestImpl::ConfigureStreamingOutput() {
  5502. const std::string& target = GTEST_FLAG(stream_result_to);
  5503. if (!target.empty()) {
  5504. const size_t pos = target.find(':');
  5505. if (pos != std::string::npos) {
  5506. listeners()->Append(new StreamingListener(target.substr(0, pos),
  5507. target.substr(pos+1)));
  5508. } else {
  5509. GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
  5510. << "\" ignored.";
  5511. }
  5512. }
  5513. }
  5514. #endif // GTEST_CAN_STREAM_RESULTS_
  5515. // Performs initialization dependent upon flag values obtained in
  5516. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  5517. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  5518. // this function is also called from RunAllTests. Since this function can be
  5519. // called more than once, it has to be idempotent.
  5520. void UnitTestImpl::PostFlagParsingInit() {
  5521. // Ensures that this function does not execute more than once.
  5522. if (!post_flag_parse_init_performed_) {
  5523. post_flag_parse_init_performed_ = true;
  5524. #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  5525. // Register to send notifications about key process state changes.
  5526. listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
  5527. #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  5528. #if GTEST_HAS_DEATH_TEST
  5529. InitDeathTestSubprocessControlInfo();
  5530. SuppressTestEventsIfInSubprocess();
  5531. #endif // GTEST_HAS_DEATH_TEST
  5532. // Registers parameterized tests. This makes parameterized tests
  5533. // available to the UnitTest reflection API without running
  5534. // RUN_ALL_TESTS.
  5535. RegisterParameterizedTests();
  5536. // Configures listeners for XML output. This makes it possible for users
  5537. // to shut down the default XML output before invoking RUN_ALL_TESTS.
  5538. ConfigureXmlOutput();
  5539. #if GTEST_CAN_STREAM_RESULTS_
  5540. // Configures listeners for streaming test results to the specified server.
  5541. ConfigureStreamingOutput();
  5542. #endif // GTEST_CAN_STREAM_RESULTS_
  5543. #if GTEST_HAS_ABSL
  5544. if (GTEST_FLAG(install_failure_signal_handler)) {
  5545. absl::FailureSignalHandlerOptions options;
  5546. absl::InstallFailureSignalHandler(options);
  5547. }
  5548. #endif // GTEST_HAS_ABSL
  5549. }
  5550. }
  5551. // A predicate that checks the name of a TestCase against a known
  5552. // value.
  5553. //
  5554. // This is used for implementation of the UnitTest class only. We put
  5555. // it in the anonymous namespace to prevent polluting the outer
  5556. // namespace.
  5557. //
  5558. // TestCaseNameIs is copyable.
  5559. class TestCaseNameIs {
  5560. public:
  5561. // Constructor.
  5562. explicit TestCaseNameIs(const std::string& name)
  5563. : name_(name) {}
  5564. // Returns true iff the name of test_case matches name_.
  5565. bool operator()(const TestCase* test_case) const {
  5566. return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
  5567. }
  5568. private:
  5569. std::string name_;
  5570. };
  5571. // Finds and returns a TestCase with the given name. If one doesn't
  5572. // exist, creates one and returns it. It's the CALLER'S
  5573. // RESPONSIBILITY to ensure that this function is only called WHEN THE
  5574. // TESTS ARE NOT SHUFFLED.
  5575. //
  5576. // Arguments:
  5577. //
  5578. // test_case_name: name of the test case
  5579. // type_param: the name of the test case's type parameter, or NULL if
  5580. // this is not a typed or a type-parameterized test case.
  5581. // set_up_tc: pointer to the function that sets up the test case
  5582. // tear_down_tc: pointer to the function that tears down the test case
  5583. TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
  5584. const char* type_param,
  5585. Test::SetUpTestCaseFunc set_up_tc,
  5586. Test::TearDownTestCaseFunc tear_down_tc) {
  5587. // Can we find a TestCase with the given name?
  5588. const std::vector<TestCase*>::const_reverse_iterator test_case =
  5589. std::find_if(test_cases_.rbegin(), test_cases_.rend(),
  5590. TestCaseNameIs(test_case_name));
  5591. if (test_case != test_cases_.rend())
  5592. return *test_case;
  5593. // No. Let's create one.
  5594. TestCase* const new_test_case =
  5595. new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
  5596. // Is this a death test case?
  5597. if (internal::UnitTestOptions::MatchesFilter(test_case_name,
  5598. kDeathTestCaseFilter)) {
  5599. // Yes. Inserts the test case after the last death test case
  5600. // defined so far. This only works when the test cases haven't
  5601. // been shuffled. Otherwise we may end up running a death test
  5602. // after a non-death test.
  5603. ++last_death_test_case_;
  5604. test_cases_.insert(test_cases_.begin() + last_death_test_case_,
  5605. new_test_case);
  5606. } else {
  5607. // No. Appends to the end of the list.
  5608. test_cases_.push_back(new_test_case);
  5609. }
  5610. test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
  5611. return new_test_case;
  5612. }
  5613. // Helpers for setting up / tearing down the given environment. They
  5614. // are for use in the ForEach() function.
  5615. static void SetUpEnvironment(Environment* env) { env->SetUp(); }
  5616. static void TearDownEnvironment(Environment* env) { env->TearDown(); }
  5617. // Runs all tests in this UnitTest object, prints the result, and
  5618. // returns true if all tests are successful. If any exception is
  5619. // thrown during a test, the test is considered to be failed, but the
  5620. // rest of the tests will still be run.
  5621. //
  5622. // When parameterized tests are enabled, it expands and registers
  5623. // parameterized tests first in RegisterParameterizedTests().
  5624. // All other functions called from RunAllTests() may safely assume that
  5625. // parameterized tests are ready to be counted and run.
  5626. bool UnitTestImpl::RunAllTests() {
  5627. // True iff Google Test is initialized before RUN_ALL_TESTS() is called.
  5628. const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
  5629. // Do not run any test if the --help flag was specified.
  5630. if (g_help_flag)
  5631. return true;
  5632. // Repeats the call to the post-flag parsing initialization in case the
  5633. // user didn't call InitGoogleTest.
  5634. PostFlagParsingInit();
  5635. // Even if sharding is not on, test runners may want to use the
  5636. // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
  5637. // protocol.
  5638. internal::WriteToShardStatusFileIfNeeded();
  5639. // True iff we are in a subprocess for running a thread-safe-style
  5640. // death test.
  5641. bool in_subprocess_for_death_test = false;
  5642. #if GTEST_HAS_DEATH_TEST
  5643. in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
  5644. # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  5645. if (in_subprocess_for_death_test) {
  5646. GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
  5647. }
  5648. # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  5649. #endif // GTEST_HAS_DEATH_TEST
  5650. const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
  5651. in_subprocess_for_death_test);
  5652. // Compares the full test names with the filter to decide which
  5653. // tests to run.
  5654. const bool has_tests_to_run = FilterTests(should_shard
  5655. ? HONOR_SHARDING_PROTOCOL
  5656. : IGNORE_SHARDING_PROTOCOL) > 0;
  5657. // Lists the tests and exits if the --gtest_list_tests flag was specified.
  5658. if (GTEST_FLAG(list_tests)) {
  5659. // This must be called *after* FilterTests() has been called.
  5660. ListTestsMatchingFilter();
  5661. return true;
  5662. }
  5663. random_seed_ = GTEST_FLAG(shuffle) ?
  5664. GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
  5665. // True iff at least one test has failed.
  5666. bool failed = false;
  5667. TestEventListener* repeater = listeners()->repeater();
  5668. start_timestamp_ = GetTimeInMillis();
  5669. repeater->OnTestProgramStart(*parent_);
  5670. // How many times to repeat the tests? We don't want to repeat them
  5671. // when we are inside the subprocess of a death test.
  5672. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
  5673. // Repeats forever if the repeat count is negative.
  5674. const bool forever = repeat < 0;
  5675. for (int i = 0; forever || i != repeat; i++) {
  5676. // We want to preserve failures generated by ad-hoc test
  5677. // assertions executed before RUN_ALL_TESTS().
  5678. ClearNonAdHocTestResult();
  5679. const TimeInMillis start = GetTimeInMillis();
  5680. // Shuffles test cases and tests if requested.
  5681. if (has_tests_to_run && GTEST_FLAG(shuffle)) {
  5682. random()->Reseed(random_seed_);
  5683. // This should be done before calling OnTestIterationStart(),
  5684. // such that a test event listener can see the actual test order
  5685. // in the event.
  5686. ShuffleTests();
  5687. }
  5688. // Tells the unit test event listeners that the tests are about to start.
  5689. repeater->OnTestIterationStart(*parent_, i);
  5690. // Runs each test case if there is at least one test to run.
  5691. if (has_tests_to_run) {
  5692. // Sets up all environments beforehand.
  5693. repeater->OnEnvironmentsSetUpStart(*parent_);
  5694. ForEach(environments_, SetUpEnvironment);
  5695. repeater->OnEnvironmentsSetUpEnd(*parent_);
  5696. // Runs the tests only if there was no fatal failure during global
  5697. // set-up.
  5698. if (!Test::HasFatalFailure()) {
  5699. for (int test_index = 0; test_index < total_test_case_count();
  5700. test_index++) {
  5701. GetMutableTestCase(test_index)->Run();
  5702. }
  5703. }
  5704. // Tears down all environments in reverse order afterwards.
  5705. repeater->OnEnvironmentsTearDownStart(*parent_);
  5706. std::for_each(environments_.rbegin(), environments_.rend(),
  5707. TearDownEnvironment);
  5708. repeater->OnEnvironmentsTearDownEnd(*parent_);
  5709. }
  5710. elapsed_time_ = GetTimeInMillis() - start;
  5711. // Tells the unit test event listener that the tests have just finished.
  5712. repeater->OnTestIterationEnd(*parent_, i);
  5713. // Gets the result and clears it.
  5714. if (!Passed()) {
  5715. failed = true;
  5716. }
  5717. // Restores the original test order after the iteration. This
  5718. // allows the user to quickly repro a failure that happens in the
  5719. // N-th iteration without repeating the first (N - 1) iterations.
  5720. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
  5721. // case the user somehow changes the value of the flag somewhere
  5722. // (it's always safe to unshuffle the tests).
  5723. UnshuffleTests();
  5724. if (GTEST_FLAG(shuffle)) {
  5725. // Picks a new random seed for each iteration.
  5726. random_seed_ = GetNextRandomSeed(random_seed_);
  5727. }
  5728. }
  5729. repeater->OnTestProgramEnd(*parent_);
  5730. if (!gtest_is_initialized_before_run_all_tests) {
  5731. ColoredPrintf(
  5732. COLOR_RED,
  5733. "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
  5734. "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
  5735. "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
  5736. " will start to enforce the valid usage. "
  5737. "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
  5738. #if GTEST_FOR_GOOGLE_
  5739. ColoredPrintf(COLOR_RED,
  5740. "For more details, see http://wiki/Main/ValidGUnitMain.\n");
  5741. #endif // GTEST_FOR_GOOGLE_
  5742. }
  5743. return !failed;
  5744. }
  5745. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  5746. // if the variable is present. If a file already exists at this location, this
  5747. // function will write over it. If the variable is present, but the file cannot
  5748. // be created, prints an error and exits.
  5749. void WriteToShardStatusFileIfNeeded() {
  5750. const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
  5751. if (test_shard_file != NULL) {
  5752. FILE* const file = posix::FOpen(test_shard_file, "w");
  5753. if (file == NULL) {
  5754. ColoredPrintf(COLOR_RED,
  5755. "Could not write to the test shard status file \"%s\" "
  5756. "specified by the %s environment variable.\n",
  5757. test_shard_file, kTestShardStatusFile);
  5758. fflush(stdout);
  5759. exit(EXIT_FAILURE);
  5760. }
  5761. fclose(file);
  5762. }
  5763. }
  5764. // Checks whether sharding is enabled by examining the relevant
  5765. // environment variable values. If the variables are present,
  5766. // but inconsistent (i.e., shard_index >= total_shards), prints
  5767. // an error and exits. If in_subprocess_for_death_test, sharding is
  5768. // disabled because it must only be applied to the original test
  5769. // process. Otherwise, we could filter out death tests we intended to execute.
  5770. bool ShouldShard(const char* total_shards_env,
  5771. const char* shard_index_env,
  5772. bool in_subprocess_for_death_test) {
  5773. if (in_subprocess_for_death_test) {
  5774. return false;
  5775. }
  5776. const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
  5777. const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
  5778. if (total_shards == -1 && shard_index == -1) {
  5779. return false;
  5780. } else if (total_shards == -1 && shard_index != -1) {
  5781. const Message msg = Message()
  5782. << "Invalid environment variables: you have "
  5783. << kTestShardIndex << " = " << shard_index
  5784. << ", but have left " << kTestTotalShards << " unset.\n";
  5785. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5786. fflush(stdout);
  5787. exit(EXIT_FAILURE);
  5788. } else if (total_shards != -1 && shard_index == -1) {
  5789. const Message msg = Message()
  5790. << "Invalid environment variables: you have "
  5791. << kTestTotalShards << " = " << total_shards
  5792. << ", but have left " << kTestShardIndex << " unset.\n";
  5793. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5794. fflush(stdout);
  5795. exit(EXIT_FAILURE);
  5796. } else if (shard_index < 0 || shard_index >= total_shards) {
  5797. const Message msg = Message()
  5798. << "Invalid environment variables: we require 0 <= "
  5799. << kTestShardIndex << " < " << kTestTotalShards
  5800. << ", but you have " << kTestShardIndex << "=" << shard_index
  5801. << ", " << kTestTotalShards << "=" << total_shards << ".\n";
  5802. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5803. fflush(stdout);
  5804. exit(EXIT_FAILURE);
  5805. }
  5806. return total_shards > 1;
  5807. }
  5808. // Parses the environment variable var as an Int32. If it is unset,
  5809. // returns default_val. If it is not an Int32, prints an error
  5810. // and aborts.
  5811. Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
  5812. const char* str_val = posix::GetEnv(var);
  5813. if (str_val == NULL) {
  5814. return default_val;
  5815. }
  5816. Int32 result;
  5817. if (!ParseInt32(Message() << "The value of environment variable " << var,
  5818. str_val, &result)) {
  5819. exit(EXIT_FAILURE);
  5820. }
  5821. return result;
  5822. }
  5823. // Given the total number of shards, the shard index, and the test id,
  5824. // returns true iff the test should be run on this shard. The test id is
  5825. // some arbitrary but unique non-negative integer assigned to each test
  5826. // method. Assumes that 0 <= shard_index < total_shards.
  5827. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
  5828. return (test_id % total_shards) == shard_index;
  5829. }
  5830. // Compares the name of each test with the user-specified filter to
  5831. // decide whether the test should be run, then records the result in
  5832. // each TestCase and TestInfo object.
  5833. // If shard_tests == true, further filters tests based on sharding
  5834. // variables in the environment - see
  5835. // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
  5836. // . Returns the number of tests that should run.
  5837. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
  5838. const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
  5839. Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
  5840. const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
  5841. Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
  5842. // num_runnable_tests are the number of tests that will
  5843. // run across all shards (i.e., match filter and are not disabled).
  5844. // num_selected_tests are the number of tests to be run on
  5845. // this shard.
  5846. int num_runnable_tests = 0;
  5847. int num_selected_tests = 0;
  5848. for (size_t i = 0; i < test_cases_.size(); i++) {
  5849. TestCase* const test_case = test_cases_[i];
  5850. const std::string &test_case_name = test_case->name();
  5851. test_case->set_should_run(false);
  5852. for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  5853. TestInfo* const test_info = test_case->test_info_list()[j];
  5854. const std::string test_name(test_info->name());
  5855. // A test is disabled if test case name or test name matches
  5856. // kDisableTestFilter.
  5857. const bool is_disabled =
  5858. internal::UnitTestOptions::MatchesFilter(test_case_name,
  5859. kDisableTestFilter) ||
  5860. internal::UnitTestOptions::MatchesFilter(test_name,
  5861. kDisableTestFilter);
  5862. test_info->is_disabled_ = is_disabled;
  5863. const bool matches_filter =
  5864. internal::UnitTestOptions::FilterMatchesTest(test_case_name,
  5865. test_name);
  5866. test_info->matches_filter_ = matches_filter;
  5867. const bool is_runnable =
  5868. (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
  5869. matches_filter;
  5870. const bool is_in_another_shard =
  5871. shard_tests != IGNORE_SHARDING_PROTOCOL &&
  5872. !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
  5873. test_info->is_in_another_shard_ = is_in_another_shard;
  5874. const bool is_selected = is_runnable && !is_in_another_shard;
  5875. num_runnable_tests += is_runnable;
  5876. num_selected_tests += is_selected;
  5877. test_info->should_run_ = is_selected;
  5878. test_case->set_should_run(test_case->should_run() || is_selected);
  5879. }
  5880. }
  5881. return num_selected_tests;
  5882. }
  5883. // Prints the given C-string on a single line by replacing all '\n'
  5884. // characters with string "\\n". If the output takes more than
  5885. // max_length characters, only prints the first max_length characters
  5886. // and "...".
  5887. static void PrintOnOneLine(const char* str, int max_length) {
  5888. if (str != NULL) {
  5889. for (int i = 0; *str != '\0'; ++str) {
  5890. if (i >= max_length) {
  5891. printf("...");
  5892. break;
  5893. }
  5894. if (*str == '\n') {
  5895. printf("\\n");
  5896. i += 2;
  5897. } else {
  5898. printf("%c", *str);
  5899. ++i;
  5900. }
  5901. }
  5902. }
  5903. }
  5904. // Prints the names of the tests matching the user-specified filter flag.
  5905. void UnitTestImpl::ListTestsMatchingFilter() {
  5906. // Print at most this many characters for each type/value parameter.
  5907. const int kMaxParamLength = 250;
  5908. for (size_t i = 0; i < test_cases_.size(); i++) {
  5909. const TestCase* const test_case = test_cases_[i];
  5910. bool printed_test_case_name = false;
  5911. for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  5912. const TestInfo* const test_info =
  5913. test_case->test_info_list()[j];
  5914. if (test_info->matches_filter_) {
  5915. if (!printed_test_case_name) {
  5916. printed_test_case_name = true;
  5917. printf("%s.", test_case->name());
  5918. if (test_case->type_param() != NULL) {
  5919. printf(" # %s = ", kTypeParamLabel);
  5920. // We print the type parameter on a single line to make
  5921. // the output easy to parse by a program.
  5922. PrintOnOneLine(test_case->type_param(), kMaxParamLength);
  5923. }
  5924. printf("\n");
  5925. }
  5926. printf(" %s", test_info->name());
  5927. if (test_info->value_param() != NULL) {
  5928. printf(" # %s = ", kValueParamLabel);
  5929. // We print the value parameter on a single line to make the
  5930. // output easy to parse by a program.
  5931. PrintOnOneLine(test_info->value_param(), kMaxParamLength);
  5932. }
  5933. printf("\n");
  5934. }
  5935. }
  5936. }
  5937. fflush(stdout);
  5938. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  5939. if (output_format == "xml" || output_format == "json") {
  5940. FILE* fileout = OpenFileForWriting(
  5941. UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
  5942. std::stringstream stream;
  5943. if (output_format == "xml") {
  5944. XmlUnitTestResultPrinter(
  5945. UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  5946. .PrintXmlTestsList(&stream, test_cases_);
  5947. } else if (output_format == "json") {
  5948. JsonUnitTestResultPrinter(
  5949. UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  5950. .PrintJsonTestList(&stream, test_cases_);
  5951. }
  5952. fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
  5953. fclose(fileout);
  5954. }
  5955. }
  5956. // Sets the OS stack trace getter.
  5957. //
  5958. // Does nothing if the input and the current OS stack trace getter are
  5959. // the same; otherwise, deletes the old getter and makes the input the
  5960. // current getter.
  5961. void UnitTestImpl::set_os_stack_trace_getter(
  5962. OsStackTraceGetterInterface* getter) {
  5963. if (os_stack_trace_getter_ != getter) {
  5964. delete os_stack_trace_getter_;
  5965. os_stack_trace_getter_ = getter;
  5966. }
  5967. }
  5968. // Returns the current OS stack trace getter if it is not NULL;
  5969. // otherwise, creates an OsStackTraceGetter, makes it the current
  5970. // getter, and returns it.
  5971. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
  5972. if (os_stack_trace_getter_ == NULL) {
  5973. #ifdef GTEST_OS_STACK_TRACE_GETTER_
  5974. os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
  5975. #else
  5976. os_stack_trace_getter_ = new OsStackTraceGetter;
  5977. #endif // GTEST_OS_STACK_TRACE_GETTER_
  5978. }
  5979. return os_stack_trace_getter_;
  5980. }
  5981. // Returns the most specific TestResult currently running.
  5982. TestResult* UnitTestImpl::current_test_result() {
  5983. if (current_test_info_ != NULL) {
  5984. return &current_test_info_->result_;
  5985. }
  5986. if (current_test_case_ != NULL) {
  5987. return &current_test_case_->ad_hoc_test_result_;
  5988. }
  5989. return &ad_hoc_test_result_;
  5990. }
  5991. // Shuffles all test cases, and the tests within each test case,
  5992. // making sure that death tests are still run first.
  5993. void UnitTestImpl::ShuffleTests() {
  5994. // Shuffles the death test cases.
  5995. ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
  5996. // Shuffles the non-death test cases.
  5997. ShuffleRange(random(), last_death_test_case_ + 1,
  5998. static_cast<int>(test_cases_.size()), &test_case_indices_);
  5999. // Shuffles the tests inside each test case.
  6000. for (size_t i = 0; i < test_cases_.size(); i++) {
  6001. test_cases_[i]->ShuffleTests(random());
  6002. }
  6003. }
  6004. // Restores the test cases and tests to their order before the first shuffle.
  6005. void UnitTestImpl::UnshuffleTests() {
  6006. for (size_t i = 0; i < test_cases_.size(); i++) {
  6007. // Unshuffles the tests in each test case.
  6008. test_cases_[i]->UnshuffleTests();
  6009. // Resets the index of each test case.
  6010. test_case_indices_[i] = static_cast<int>(i);
  6011. }
  6012. }
  6013. // Returns the current OS stack trace as an std::string.
  6014. //
  6015. // The maximum number of stack frames to be included is specified by
  6016. // the gtest_stack_trace_depth flag. The skip_count parameter
  6017. // specifies the number of top frames to be skipped, which doesn't
  6018. // count against the number of frames to be included.
  6019. //
  6020. // For example, if Foo() calls Bar(), which in turn calls
  6021. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  6022. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  6023. std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
  6024. int skip_count) {
  6025. // We pass skip_count + 1 to skip this wrapper function in addition
  6026. // to what the user really wants to skip.
  6027. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
  6028. }
  6029. // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
  6030. // suppress unreachable code warnings.
  6031. namespace {
  6032. class ClassUniqueToAlwaysTrue {};
  6033. }
  6034. bool IsTrue(bool condition) { return condition; }
  6035. bool AlwaysTrue() {
  6036. #if GTEST_HAS_EXCEPTIONS
  6037. // This condition is always false so AlwaysTrue() never actually throws,
  6038. // but it makes the compiler think that it may throw.
  6039. if (IsTrue(false))
  6040. throw ClassUniqueToAlwaysTrue();
  6041. #endif // GTEST_HAS_EXCEPTIONS
  6042. return true;
  6043. }
  6044. // If *pstr starts with the given prefix, modifies *pstr to be right
  6045. // past the prefix and returns true; otherwise leaves *pstr unchanged
  6046. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  6047. bool SkipPrefix(const char* prefix, const char** pstr) {
  6048. const size_t prefix_len = strlen(prefix);
  6049. if (strncmp(*pstr, prefix, prefix_len) == 0) {
  6050. *pstr += prefix_len;
  6051. return true;
  6052. }
  6053. return false;
  6054. }
  6055. // Parses a string as a command line flag. The string should have
  6056. // the format "--flag=value". When def_optional is true, the "=value"
  6057. // part can be omitted.
  6058. //
  6059. // Returns the value of the flag, or NULL if the parsing failed.
  6060. static const char* ParseFlagValue(const char* str, const char* flag,
  6061. bool def_optional) {
  6062. // str and flag must not be NULL.
  6063. if (str == NULL || flag == NULL) return NULL;
  6064. // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
  6065. const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
  6066. const size_t flag_len = flag_str.length();
  6067. if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
  6068. // Skips the flag name.
  6069. const char* flag_end = str + flag_len;
  6070. // When def_optional is true, it's OK to not have a "=value" part.
  6071. if (def_optional && (flag_end[0] == '\0')) {
  6072. return flag_end;
  6073. }
  6074. // If def_optional is true and there are more characters after the
  6075. // flag name, or if def_optional is false, there must be a '=' after
  6076. // the flag name.
  6077. if (flag_end[0] != '=') return NULL;
  6078. // Returns the string after "=".
  6079. return flag_end + 1;
  6080. }
  6081. // Parses a string for a bool flag, in the form of either
  6082. // "--flag=value" or "--flag".
  6083. //
  6084. // In the former case, the value is taken as true as long as it does
  6085. // not start with '0', 'f', or 'F'.
  6086. //
  6087. // In the latter case, the value is taken as true.
  6088. //
  6089. // On success, stores the value of the flag in *value, and returns
  6090. // true. On failure, returns false without changing *value.
  6091. static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
  6092. // Gets the value of the flag as a string.
  6093. const char* const value_str = ParseFlagValue(str, flag, true);
  6094. // Aborts if the parsing failed.
  6095. if (value_str == NULL) return false;
  6096. // Converts the string value to a bool.
  6097. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  6098. return true;
  6099. }
  6100. // Parses a string for an Int32 flag, in the form of
  6101. // "--flag=value".
  6102. //
  6103. // On success, stores the value of the flag in *value, and returns
  6104. // true. On failure, returns false without changing *value.
  6105. bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
  6106. // Gets the value of the flag as a string.
  6107. const char* const value_str = ParseFlagValue(str, flag, false);
  6108. // Aborts if the parsing failed.
  6109. if (value_str == NULL) return false;
  6110. // Sets *value to the value of the flag.
  6111. return ParseInt32(Message() << "The value of flag --" << flag,
  6112. value_str, value);
  6113. }
  6114. // Parses a string for a string flag, in the form of
  6115. // "--flag=value".
  6116. //
  6117. // On success, stores the value of the flag in *value, and returns
  6118. // true. On failure, returns false without changing *value.
  6119. template <typename String>
  6120. static bool ParseStringFlag(const char* str, const char* flag, String* value) {
  6121. // Gets the value of the flag as a string.
  6122. const char* const value_str = ParseFlagValue(str, flag, false);
  6123. // Aborts if the parsing failed.
  6124. if (value_str == NULL) return false;
  6125. // Sets *value to the value of the flag.
  6126. *value = value_str;
  6127. return true;
  6128. }
  6129. // Determines whether a string has a prefix that Google Test uses for its
  6130. // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
  6131. // If Google Test detects that a command line flag has its prefix but is not
  6132. // recognized, it will print its help message. Flags starting with
  6133. // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
  6134. // internal flags and do not trigger the help message.
  6135. static bool HasGoogleTestFlagPrefix(const char* str) {
  6136. return (SkipPrefix("--", &str) ||
  6137. SkipPrefix("-", &str) ||
  6138. SkipPrefix("/", &str)) &&
  6139. !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
  6140. (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
  6141. SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
  6142. }
  6143. // Prints a string containing code-encoded text. The following escape
  6144. // sequences can be used in the string to control the text color:
  6145. //
  6146. // @@ prints a single '@' character.
  6147. // @R changes the color to red.
  6148. // @G changes the color to green.
  6149. // @Y changes the color to yellow.
  6150. // @D changes to the default terminal text color.
  6151. //
  6152. // FIXME: Write tests for this once we add stdout
  6153. // capturing to Google Test.
  6154. static void PrintColorEncoded(const char* str) {
  6155. GTestColor color = COLOR_DEFAULT; // The current color.
  6156. // Conceptually, we split the string into segments divided by escape
  6157. // sequences. Then we print one segment at a time. At the end of
  6158. // each iteration, the str pointer advances to the beginning of the
  6159. // next segment.
  6160. for (;;) {
  6161. const char* p = strchr(str, '@');
  6162. if (p == NULL) {
  6163. ColoredPrintf(color, "%s", str);
  6164. return;
  6165. }
  6166. ColoredPrintf(color, "%s", std::string(str, p).c_str());
  6167. const char ch = p[1];
  6168. str = p + 2;
  6169. if (ch == '@') {
  6170. ColoredPrintf(color, "@");
  6171. } else if (ch == 'D') {
  6172. color = COLOR_DEFAULT;
  6173. } else if (ch == 'R') {
  6174. color = COLOR_RED;
  6175. } else if (ch == 'G') {
  6176. color = COLOR_GREEN;
  6177. } else if (ch == 'Y') {
  6178. color = COLOR_YELLOW;
  6179. } else {
  6180. --str;
  6181. }
  6182. }
  6183. }
  6184. static const char kColorEncodedHelpMessage[] =
  6185. "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
  6186. "following command line flags to control its behavior:\n"
  6187. "\n"
  6188. "Test Selection:\n"
  6189. " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
  6190. " List the names of all tests instead of running them. The name of\n"
  6191. " TEST(Foo, Bar) is \"Foo.Bar\".\n"
  6192. " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
  6193. "[@G-@YNEGATIVE_PATTERNS]@D\n"
  6194. " Run only the tests whose name matches one of the positive patterns but\n"
  6195. " none of the negative patterns. '?' matches any single character; '*'\n"
  6196. " matches any substring; ':' separates two patterns.\n"
  6197. " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
  6198. " Run all disabled tests too.\n"
  6199. "\n"
  6200. "Test Execution:\n"
  6201. " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
  6202. " Run the tests repeatedly; use a negative count to repeat forever.\n"
  6203. " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
  6204. " Randomize tests' orders on every iteration.\n"
  6205. " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
  6206. " Random number seed to use for shuffling test orders (between 1 and\n"
  6207. " 99999, or 0 to use a seed based on the current time).\n"
  6208. "\n"
  6209. "Test Output:\n"
  6210. " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
  6211. " Enable/disable colored output. The default is @Gauto@D.\n"
  6212. " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
  6213. " Don't print the elapsed time of each test.\n"
  6214. " @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
  6215. GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
  6216. " Generate a JSON or XML report in the given directory or with the given\n"
  6217. " file name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
  6218. # if GTEST_CAN_STREAM_RESULTS_
  6219. " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
  6220. " Stream test results to the given server.\n"
  6221. # endif // GTEST_CAN_STREAM_RESULTS_
  6222. "\n"
  6223. "Assertion Behavior:\n"
  6224. # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  6225. " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
  6226. " Set the default death test style.\n"
  6227. # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  6228. " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
  6229. " Turn assertion failures into debugger break-points.\n"
  6230. " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
  6231. " Turn assertion failures into C++ exceptions for use by an external\n"
  6232. " test framework.\n"
  6233. " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
  6234. " Do not report exceptions as test failures. Instead, allow them\n"
  6235. " to crash the program or throw a pop-up (on Windows).\n"
  6236. "\n"
  6237. "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
  6238. "the corresponding\n"
  6239. "environment variable of a flag (all letters in upper-case). For example, to\n"
  6240. "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
  6241. "color=no@D or set\n"
  6242. "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
  6243. "\n"
  6244. "For more information, please read the " GTEST_NAME_ " documentation at\n"
  6245. "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
  6246. "(not one in your own code or tests), please report it to\n"
  6247. "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
  6248. static bool ParseGoogleTestFlag(const char* const arg) {
  6249. return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
  6250. &GTEST_FLAG(also_run_disabled_tests)) ||
  6251. ParseBoolFlag(arg, kBreakOnFailureFlag,
  6252. &GTEST_FLAG(break_on_failure)) ||
  6253. ParseBoolFlag(arg, kCatchExceptionsFlag,
  6254. &GTEST_FLAG(catch_exceptions)) ||
  6255. ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
  6256. ParseStringFlag(arg, kDeathTestStyleFlag,
  6257. &GTEST_FLAG(death_test_style)) ||
  6258. ParseBoolFlag(arg, kDeathTestUseFork,
  6259. &GTEST_FLAG(death_test_use_fork)) ||
  6260. ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
  6261. ParseStringFlag(arg, kInternalRunDeathTestFlag,
  6262. &GTEST_FLAG(internal_run_death_test)) ||
  6263. ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
  6264. ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
  6265. ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
  6266. ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
  6267. ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
  6268. ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
  6269. ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
  6270. ParseInt32Flag(arg, kStackTraceDepthFlag,
  6271. &GTEST_FLAG(stack_trace_depth)) ||
  6272. ParseStringFlag(arg, kStreamResultToFlag,
  6273. &GTEST_FLAG(stream_result_to)) ||
  6274. ParseBoolFlag(arg, kThrowOnFailureFlag,
  6275. &GTEST_FLAG(throw_on_failure));
  6276. }
  6277. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  6278. static void LoadFlagsFromFile(const std::string& path) {
  6279. FILE* flagfile = posix::FOpen(path.c_str(), "r");
  6280. if (!flagfile) {
  6281. GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
  6282. << "\"";
  6283. }
  6284. std::string contents(ReadEntireFile(flagfile));
  6285. posix::FClose(flagfile);
  6286. std::vector<std::string> lines;
  6287. SplitString(contents, '\n', &lines);
  6288. for (size_t i = 0; i < lines.size(); ++i) {
  6289. if (lines[i].empty())
  6290. continue;
  6291. if (!ParseGoogleTestFlag(lines[i].c_str()))
  6292. g_help_flag = true;
  6293. }
  6294. }
  6295. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  6296. // Parses the command line for Google Test flags, without initializing
  6297. // other parts of Google Test. The type parameter CharType can be
  6298. // instantiated to either char or wchar_t.
  6299. template <typename CharType>
  6300. void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
  6301. for (int i = 1; i < *argc; i++) {
  6302. const std::string arg_string = StreamableToString(argv[i]);
  6303. const char* const arg = arg_string.c_str();
  6304. using internal::ParseBoolFlag;
  6305. using internal::ParseInt32Flag;
  6306. using internal::ParseStringFlag;
  6307. bool remove_flag = false;
  6308. if (ParseGoogleTestFlag(arg)) {
  6309. remove_flag = true;
  6310. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  6311. } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
  6312. LoadFlagsFromFile(GTEST_FLAG(flagfile));
  6313. remove_flag = true;
  6314. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  6315. } else if (arg_string == "--help" || arg_string == "-h" ||
  6316. arg_string == "-?" || arg_string == "/?" ||
  6317. HasGoogleTestFlagPrefix(arg)) {
  6318. // Both help flag and unrecognized Google Test flags (excluding
  6319. // internal ones) trigger help display.
  6320. g_help_flag = true;
  6321. }
  6322. if (remove_flag) {
  6323. // Shift the remainder of the argv list left by one. Note
  6324. // that argv has (*argc + 1) elements, the last one always being
  6325. // NULL. The following loop moves the trailing NULL element as
  6326. // well.
  6327. for (int j = i; j != *argc; j++) {
  6328. argv[j] = argv[j + 1];
  6329. }
  6330. // Decrements the argument count.
  6331. (*argc)--;
  6332. // We also need to decrement the iterator as we just removed
  6333. // an element.
  6334. i--;
  6335. }
  6336. }
  6337. if (g_help_flag) {
  6338. // We print the help here instead of in RUN_ALL_TESTS(), as the
  6339. // latter may not be called at all if the user is using Google
  6340. // Test with another testing framework.
  6341. PrintColorEncoded(kColorEncodedHelpMessage);
  6342. }
  6343. }
  6344. // Parses the command line for Google Test flags, without initializing
  6345. // other parts of Google Test.
  6346. void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
  6347. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  6348. // Fix the value of *_NSGetArgc() on macOS, but iff
  6349. // *_NSGetArgv() == argv
  6350. // Only applicable to char** version of argv
  6351. #if GTEST_OS_MAC
  6352. #ifndef GTEST_OS_IOS
  6353. if (*_NSGetArgv() == argv) {
  6354. *_NSGetArgc() = *argc;
  6355. }
  6356. #endif
  6357. #endif
  6358. }
  6359. void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
  6360. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  6361. }
  6362. // The internal implementation of InitGoogleTest().
  6363. //
  6364. // The type parameter CharType can be instantiated to either char or
  6365. // wchar_t.
  6366. template <typename CharType>
  6367. void InitGoogleTestImpl(int* argc, CharType** argv) {
  6368. // We don't want to run the initialization code twice.
  6369. if (GTestIsInitialized()) return;
  6370. if (*argc <= 0) return;
  6371. g_argvs.clear();
  6372. for (int i = 0; i != *argc; i++) {
  6373. g_argvs.push_back(StreamableToString(argv[i]));
  6374. }
  6375. #if GTEST_HAS_ABSL
  6376. absl::InitializeSymbolizer(g_argvs[0].c_str());
  6377. #endif // GTEST_HAS_ABSL
  6378. ParseGoogleTestFlagsOnly(argc, argv);
  6379. GetUnitTestImpl()->PostFlagParsingInit();
  6380. }
  6381. } // namespace internal
  6382. // Initializes Google Test. This must be called before calling
  6383. // RUN_ALL_TESTS(). In particular, it parses a command line for the
  6384. // flags that Google Test recognizes. Whenever a Google Test flag is
  6385. // seen, it is removed from argv, and *argc is decremented.
  6386. //
  6387. // No value is returned. Instead, the Google Test flag variables are
  6388. // updated.
  6389. //
  6390. // Calling the function for the second time has no user-visible effect.
  6391. void InitGoogleTest(int* argc, char** argv) {
  6392. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6393. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  6394. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6395. internal::InitGoogleTestImpl(argc, argv);
  6396. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6397. }
  6398. // This overloaded version can be used in Windows programs compiled in
  6399. // UNICODE mode.
  6400. void InitGoogleTest(int* argc, wchar_t** argv) {
  6401. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6402. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  6403. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6404. internal::InitGoogleTestImpl(argc, argv);
  6405. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6406. }
  6407. std::string TempDir() {
  6408. #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
  6409. return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
  6410. #endif
  6411. #if GTEST_OS_WINDOWS_MOBILE
  6412. return "\\temp\\";
  6413. #elif GTEST_OS_WINDOWS
  6414. const char* temp_dir = internal::posix::GetEnv("TEMP");
  6415. if (temp_dir == NULL || temp_dir[0] == '\0')
  6416. return "\\temp\\";
  6417. else if (temp_dir[strlen(temp_dir) - 1] == '\\')
  6418. return temp_dir;
  6419. else
  6420. return std::string(temp_dir) + "\\";
  6421. #elif GTEST_OS_LINUX_ANDROID
  6422. return "/sdcard/";
  6423. #else
  6424. return "/tmp/";
  6425. #endif // GTEST_OS_WINDOWS_MOBILE
  6426. }
  6427. // Class ScopedTrace
  6428. // Pushes the given source file location and message onto a per-thread
  6429. // trace stack maintained by Google Test.
  6430. void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
  6431. internal::TraceInfo trace;
  6432. trace.file = file;
  6433. trace.line = line;
  6434. trace.message.swap(message);
  6435. UnitTest::GetInstance()->PushGTestTrace(trace);
  6436. }
  6437. // Pops the info pushed by the c'tor.
  6438. ScopedTrace::~ScopedTrace()
  6439. GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
  6440. UnitTest::GetInstance()->PopGTestTrace();
  6441. }
  6442. } // namespace testing
  6443. // Copyright 2005, Google Inc.
  6444. // All rights reserved.
  6445. //
  6446. // Redistribution and use in source and binary forms, with or without
  6447. // modification, are permitted provided that the following conditions are
  6448. // met:
  6449. //
  6450. // * Redistributions of source code must retain the above copyright
  6451. // notice, this list of conditions and the following disclaimer.
  6452. // * Redistributions in binary form must reproduce the above
  6453. // copyright notice, this list of conditions and the following disclaimer
  6454. // in the documentation and/or other materials provided with the
  6455. // distribution.
  6456. // * Neither the name of Google Inc. nor the names of its
  6457. // contributors may be used to endorse or promote products derived from
  6458. // this software without specific prior written permission.
  6459. //
  6460. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6461. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6462. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6463. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6464. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6465. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6466. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6467. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6468. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6469. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6470. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6471. //
  6472. // This file implements death tests.
  6473. #if GTEST_HAS_DEATH_TEST
  6474. # if GTEST_OS_MAC
  6475. # include <crt_externs.h>
  6476. # endif // GTEST_OS_MAC
  6477. # include <errno.h>
  6478. # include <fcntl.h>
  6479. # include <limits.h>
  6480. # if GTEST_OS_LINUX
  6481. # include <signal.h>
  6482. # endif // GTEST_OS_LINUX
  6483. # include <stdarg.h>
  6484. # if GTEST_OS_WINDOWS
  6485. # include <windows.h>
  6486. # else
  6487. # include <sys/mman.h>
  6488. # include <sys/wait.h>
  6489. # endif // GTEST_OS_WINDOWS
  6490. # if GTEST_OS_QNX
  6491. # include <spawn.h>
  6492. # endif // GTEST_OS_QNX
  6493. # if GTEST_OS_FUCHSIA
  6494. # include <lib/fdio/io.h>
  6495. # include <lib/fdio/spawn.h>
  6496. # include <zircon/processargs.h>
  6497. # include <zircon/syscalls.h>
  6498. # include <zircon/syscalls/port.h>
  6499. # endif // GTEST_OS_FUCHSIA
  6500. #endif // GTEST_HAS_DEATH_TEST
  6501. namespace testing {
  6502. // Constants.
  6503. // The default death test style.
  6504. //
  6505. // This is defined in internal/gtest-port.h as "fast", but can be overridden by
  6506. // a definition in internal/custom/gtest-port.h. The recommended value, which is
  6507. // used internally at Google, is "threadsafe".
  6508. static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
  6509. GTEST_DEFINE_string_(
  6510. death_test_style,
  6511. internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
  6512. "Indicates how to run a death test in a forked child process: "
  6513. "\"threadsafe\" (child process re-executes the test binary "
  6514. "from the beginning, running only the specific death test) or "
  6515. "\"fast\" (child process runs the death test immediately "
  6516. "after forking).");
  6517. GTEST_DEFINE_bool_(
  6518. death_test_use_fork,
  6519. internal::BoolFromGTestEnv("death_test_use_fork", false),
  6520. "Instructs to use fork()/_exit() instead of clone() in death tests. "
  6521. "Ignored and always uses fork() on POSIX systems where clone() is not "
  6522. "implemented. Useful when running under valgrind or similar tools if "
  6523. "those do not support clone(). Valgrind 3.3.1 will just fail if "
  6524. "it sees an unsupported combination of clone() flags. "
  6525. "It is not recommended to use this flag w/o valgrind though it will "
  6526. "work in 99% of the cases. Once valgrind is fixed, this flag will "
  6527. "most likely be removed.");
  6528. namespace internal {
  6529. GTEST_DEFINE_string_(
  6530. internal_run_death_test, "",
  6531. "Indicates the file, line number, temporal index of "
  6532. "the single death test to run, and a file descriptor to "
  6533. "which a success code may be sent, all separated by "
  6534. "the '|' characters. This flag is specified if and only if the current "
  6535. "process is a sub-process launched for running a thread-safe "
  6536. "death test. FOR INTERNAL USE ONLY.");
  6537. } // namespace internal
  6538. #if GTEST_HAS_DEATH_TEST
  6539. namespace internal {
  6540. // Valid only for fast death tests. Indicates the code is running in the
  6541. // child process of a fast style death test.
  6542. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6543. static bool g_in_fast_death_test_child = false;
  6544. # endif
  6545. // Returns a Boolean value indicating whether the caller is currently
  6546. // executing in the context of the death test child process. Tools such as
  6547. // Valgrind heap checkers may need this to modify their behavior in death
  6548. // tests. IMPORTANT: This is an internal utility. Using it may break the
  6549. // implementation of death tests. User code MUST NOT use it.
  6550. bool InDeathTestChild() {
  6551. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6552. // On Windows and Fuchsia, death tests are thread-safe regardless of the value
  6553. // of the death_test_style flag.
  6554. return !GTEST_FLAG(internal_run_death_test).empty();
  6555. # else
  6556. if (GTEST_FLAG(death_test_style) == "threadsafe")
  6557. return !GTEST_FLAG(internal_run_death_test).empty();
  6558. else
  6559. return g_in_fast_death_test_child;
  6560. #endif
  6561. }
  6562. } // namespace internal
  6563. // ExitedWithCode constructor.
  6564. ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
  6565. }
  6566. // ExitedWithCode function-call operator.
  6567. bool ExitedWithCode::operator()(int exit_status) const {
  6568. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6569. return exit_status == exit_code_;
  6570. # else
  6571. return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
  6572. # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6573. }
  6574. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6575. // KilledBySignal constructor.
  6576. KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
  6577. }
  6578. // KilledBySignal function-call operator.
  6579. bool KilledBySignal::operator()(int exit_status) const {
  6580. # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
  6581. {
  6582. bool result;
  6583. if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
  6584. return result;
  6585. }
  6586. }
  6587. # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
  6588. return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
  6589. }
  6590. # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6591. namespace internal {
  6592. // Utilities needed for death tests.
  6593. // Generates a textual description of a given exit code, in the format
  6594. // specified by wait(2).
  6595. static std::string ExitSummary(int exit_code) {
  6596. Message m;
  6597. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6598. m << "Exited with exit status " << exit_code;
  6599. # else
  6600. if (WIFEXITED(exit_code)) {
  6601. m << "Exited with exit status " << WEXITSTATUS(exit_code);
  6602. } else if (WIFSIGNALED(exit_code)) {
  6603. m << "Terminated by signal " << WTERMSIG(exit_code);
  6604. }
  6605. # ifdef WCOREDUMP
  6606. if (WCOREDUMP(exit_code)) {
  6607. m << " (core dumped)";
  6608. }
  6609. # endif
  6610. # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6611. return m.GetString();
  6612. }
  6613. // Returns true if exit_status describes a process that was terminated
  6614. // by a signal, or exited normally with a nonzero exit code.
  6615. bool ExitedUnsuccessfully(int exit_status) {
  6616. return !ExitedWithCode(0)(exit_status);
  6617. }
  6618. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6619. // Generates a textual failure message when a death test finds more than
  6620. // one thread running, or cannot determine the number of threads, prior
  6621. // to executing the given statement. It is the responsibility of the
  6622. // caller not to pass a thread_count of 1.
  6623. static std::string DeathTestThreadWarning(size_t thread_count) {
  6624. Message msg;
  6625. msg << "Death tests use fork(), which is unsafe particularly"
  6626. << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
  6627. if (thread_count == 0) {
  6628. msg << "couldn't detect the number of threads.";
  6629. } else {
  6630. msg << "detected " << thread_count << " threads.";
  6631. }
  6632. msg << " See "
  6633. "https://github.com/google/googletest/blob/master/googletest/docs/"
  6634. "advanced.md#death-tests-and-threads"
  6635. << " for more explanation and suggested solutions, especially if"
  6636. << " this is the last message you see before your test times out.";
  6637. return msg.GetString();
  6638. }
  6639. # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6640. // Flag characters for reporting a death test that did not die.
  6641. static const char kDeathTestLived = 'L';
  6642. static const char kDeathTestReturned = 'R';
  6643. static const char kDeathTestThrew = 'T';
  6644. static const char kDeathTestInternalError = 'I';
  6645. #if GTEST_OS_FUCHSIA
  6646. // File descriptor used for the pipe in the child process.
  6647. static const int kFuchsiaReadPipeFd = 3;
  6648. #endif
  6649. // An enumeration describing all of the possible ways that a death test can
  6650. // conclude. DIED means that the process died while executing the test
  6651. // code; LIVED means that process lived beyond the end of the test code;
  6652. // RETURNED means that the test statement attempted to execute a return
  6653. // statement, which is not allowed; THREW means that the test statement
  6654. // returned control by throwing an exception. IN_PROGRESS means the test
  6655. // has not yet concluded.
  6656. // FIXME: Unify names and possibly values for
  6657. // AbortReason, DeathTestOutcome, and flag characters above.
  6658. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
  6659. // Routine for aborting the program which is safe to call from an
  6660. // exec-style death test child process, in which case the error
  6661. // message is propagated back to the parent process. Otherwise, the
  6662. // message is simply printed to stderr. In either case, the program
  6663. // then exits with status 1.
  6664. static void DeathTestAbort(const std::string& message) {
  6665. // On a POSIX system, this function may be called from a threadsafe-style
  6666. // death test child process, which operates on a very small stack. Use
  6667. // the heap for any additional non-minuscule memory requirements.
  6668. const InternalRunDeathTestFlag* const flag =
  6669. GetUnitTestImpl()->internal_run_death_test_flag();
  6670. if (flag != NULL) {
  6671. FILE* parent = posix::FDOpen(flag->write_fd(), "w");
  6672. fputc(kDeathTestInternalError, parent);
  6673. fprintf(parent, "%s", message.c_str());
  6674. fflush(parent);
  6675. _exit(1);
  6676. } else {
  6677. fprintf(stderr, "%s", message.c_str());
  6678. fflush(stderr);
  6679. posix::Abort();
  6680. }
  6681. }
  6682. // A replacement for CHECK that calls DeathTestAbort if the assertion
  6683. // fails.
  6684. # define GTEST_DEATH_TEST_CHECK_(expression) \
  6685. do { \
  6686. if (!::testing::internal::IsTrue(expression)) { \
  6687. DeathTestAbort( \
  6688. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  6689. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  6690. + #expression); \
  6691. } \
  6692. } while (::testing::internal::AlwaysFalse())
  6693. // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
  6694. // evaluating any system call that fulfills two conditions: it must return
  6695. // -1 on failure, and set errno to EINTR when it is interrupted and
  6696. // should be tried again. The macro expands to a loop that repeatedly
  6697. // evaluates the expression as long as it evaluates to -1 and sets
  6698. // errno to EINTR. If the expression evaluates to -1 but errno is
  6699. // something other than EINTR, DeathTestAbort is called.
  6700. # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
  6701. do { \
  6702. int gtest_retval; \
  6703. do { \
  6704. gtest_retval = (expression); \
  6705. } while (gtest_retval == -1 && errno == EINTR); \
  6706. if (gtest_retval == -1) { \
  6707. DeathTestAbort( \
  6708. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  6709. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  6710. + #expression + " != -1"); \
  6711. } \
  6712. } while (::testing::internal::AlwaysFalse())
  6713. // Returns the message describing the last system error in errno.
  6714. std::string GetLastErrnoDescription() {
  6715. return errno == 0 ? "" : posix::StrError(errno);
  6716. }
  6717. // This is called from a death test parent process to read a failure
  6718. // message from the death test child process and log it with the FATAL
  6719. // severity. On Windows, the message is read from a pipe handle. On other
  6720. // platforms, it is read from a file descriptor.
  6721. static void FailFromInternalError(int fd) {
  6722. Message error;
  6723. char buffer[256];
  6724. int num_read;
  6725. do {
  6726. while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
  6727. buffer[num_read] = '\0';
  6728. error << buffer;
  6729. }
  6730. } while (num_read == -1 && errno == EINTR);
  6731. if (num_read == 0) {
  6732. GTEST_LOG_(FATAL) << error.GetString();
  6733. } else {
  6734. const int last_error = errno;
  6735. GTEST_LOG_(FATAL) << "Error while reading death test internal: "
  6736. << GetLastErrnoDescription() << " [" << last_error << "]";
  6737. }
  6738. }
  6739. // Death test constructor. Increments the running death test count
  6740. // for the current test.
  6741. DeathTest::DeathTest() {
  6742. TestInfo* const info = GetUnitTestImpl()->current_test_info();
  6743. if (info == NULL) {
  6744. DeathTestAbort("Cannot run a death test outside of a TEST or "
  6745. "TEST_F construct");
  6746. }
  6747. }
  6748. // Creates and returns a death test by dispatching to the current
  6749. // death test factory.
  6750. bool DeathTest::Create(const char* statement, const RE* regex,
  6751. const char* file, int line, DeathTest** test) {
  6752. return GetUnitTestImpl()->death_test_factory()->Create(
  6753. statement, regex, file, line, test);
  6754. }
  6755. const char* DeathTest::LastMessage() {
  6756. return last_death_test_message_.c_str();
  6757. }
  6758. void DeathTest::set_last_death_test_message(const std::string& message) {
  6759. last_death_test_message_ = message;
  6760. }
  6761. std::string DeathTest::last_death_test_message_;
  6762. // Provides cross platform implementation for some death functionality.
  6763. class DeathTestImpl : public DeathTest {
  6764. protected:
  6765. DeathTestImpl(const char* a_statement, const RE* a_regex)
  6766. : statement_(a_statement),
  6767. regex_(a_regex),
  6768. spawned_(false),
  6769. status_(-1),
  6770. outcome_(IN_PROGRESS),
  6771. read_fd_(-1),
  6772. write_fd_(-1) {}
  6773. // read_fd_ is expected to be closed and cleared by a derived class.
  6774. ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
  6775. void Abort(AbortReason reason);
  6776. virtual bool Passed(bool status_ok);
  6777. const char* statement() const { return statement_; }
  6778. const RE* regex() const { return regex_; }
  6779. bool spawned() const { return spawned_; }
  6780. void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
  6781. int status() const { return status_; }
  6782. void set_status(int a_status) { status_ = a_status; }
  6783. DeathTestOutcome outcome() const { return outcome_; }
  6784. void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
  6785. int read_fd() const { return read_fd_; }
  6786. void set_read_fd(int fd) { read_fd_ = fd; }
  6787. int write_fd() const { return write_fd_; }
  6788. void set_write_fd(int fd) { write_fd_ = fd; }
  6789. // Called in the parent process only. Reads the result code of the death
  6790. // test child process via a pipe, interprets it to set the outcome_
  6791. // member, and closes read_fd_. Outputs diagnostics and terminates in
  6792. // case of unexpected codes.
  6793. void ReadAndInterpretStatusByte();
  6794. private:
  6795. // The textual content of the code this object is testing. This class
  6796. // doesn't own this string and should not attempt to delete it.
  6797. const char* const statement_;
  6798. // The regular expression which test output must match. DeathTestImpl
  6799. // doesn't own this object and should not attempt to delete it.
  6800. const RE* const regex_;
  6801. // True if the death test child process has been successfully spawned.
  6802. bool spawned_;
  6803. // The exit status of the child process.
  6804. int status_;
  6805. // How the death test concluded.
  6806. DeathTestOutcome outcome_;
  6807. // Descriptor to the read end of the pipe to the child process. It is
  6808. // always -1 in the child process. The child keeps its write end of the
  6809. // pipe in write_fd_.
  6810. int read_fd_;
  6811. // Descriptor to the child's write end of the pipe to the parent process.
  6812. // It is always -1 in the parent process. The parent keeps its end of the
  6813. // pipe in read_fd_.
  6814. int write_fd_;
  6815. };
  6816. // Called in the parent process only. Reads the result code of the death
  6817. // test child process via a pipe, interprets it to set the outcome_
  6818. // member, and closes read_fd_. Outputs diagnostics and terminates in
  6819. // case of unexpected codes.
  6820. void DeathTestImpl::ReadAndInterpretStatusByte() {
  6821. char flag;
  6822. int bytes_read;
  6823. // The read() here blocks until data is available (signifying the
  6824. // failure of the death test) or until the pipe is closed (signifying
  6825. // its success), so it's okay to call this in the parent before
  6826. // the child process has exited.
  6827. do {
  6828. bytes_read = posix::Read(read_fd(), &flag, 1);
  6829. } while (bytes_read == -1 && errno == EINTR);
  6830. if (bytes_read == 0) {
  6831. set_outcome(DIED);
  6832. } else if (bytes_read == 1) {
  6833. switch (flag) {
  6834. case kDeathTestReturned:
  6835. set_outcome(RETURNED);
  6836. break;
  6837. case kDeathTestThrew:
  6838. set_outcome(THREW);
  6839. break;
  6840. case kDeathTestLived:
  6841. set_outcome(LIVED);
  6842. break;
  6843. case kDeathTestInternalError:
  6844. FailFromInternalError(read_fd()); // Does not return.
  6845. break;
  6846. default:
  6847. GTEST_LOG_(FATAL) << "Death test child process reported "
  6848. << "unexpected status byte ("
  6849. << static_cast<unsigned int>(flag) << ")";
  6850. }
  6851. } else {
  6852. GTEST_LOG_(FATAL) << "Read from death test child process failed: "
  6853. << GetLastErrnoDescription();
  6854. }
  6855. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
  6856. set_read_fd(-1);
  6857. }
  6858. // Signals that the death test code which should have exited, didn't.
  6859. // Should be called only in a death test child process.
  6860. // Writes a status byte to the child's status file descriptor, then
  6861. // calls _exit(1).
  6862. void DeathTestImpl::Abort(AbortReason reason) {
  6863. // The parent process considers the death test to be a failure if
  6864. // it finds any data in our pipe. So, here we write a single flag byte
  6865. // to the pipe, then exit.
  6866. const char status_ch =
  6867. reason == TEST_DID_NOT_DIE ? kDeathTestLived :
  6868. reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
  6869. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
  6870. // We are leaking the descriptor here because on some platforms (i.e.,
  6871. // when built as Windows DLL), destructors of global objects will still
  6872. // run after calling _exit(). On such systems, write_fd_ will be
  6873. // indirectly closed from the destructor of UnitTestImpl, causing double
  6874. // close if it is also closed here. On debug configurations, double close
  6875. // may assert. As there are no in-process buffers to flush here, we are
  6876. // relying on the OS to close the descriptor after the process terminates
  6877. // when the destructors are not run.
  6878. _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
  6879. }
  6880. // Returns an indented copy of stderr output for a death test.
  6881. // This makes distinguishing death test output lines from regular log lines
  6882. // much easier.
  6883. static ::std::string FormatDeathTestOutput(const ::std::string& output) {
  6884. ::std::string ret;
  6885. for (size_t at = 0; ; ) {
  6886. const size_t line_end = output.find('\n', at);
  6887. ret += "[ DEATH ] ";
  6888. if (line_end == ::std::string::npos) {
  6889. ret += output.substr(at);
  6890. break;
  6891. }
  6892. ret += output.substr(at, line_end + 1 - at);
  6893. at = line_end + 1;
  6894. }
  6895. return ret;
  6896. }
  6897. // Assesses the success or failure of a death test, using both private
  6898. // members which have previously been set, and one argument:
  6899. //
  6900. // Private data members:
  6901. // outcome: An enumeration describing how the death test
  6902. // concluded: DIED, LIVED, THREW, or RETURNED. The death test
  6903. // fails in the latter three cases.
  6904. // status: The exit status of the child process. On *nix, it is in the
  6905. // in the format specified by wait(2). On Windows, this is the
  6906. // value supplied to the ExitProcess() API or a numeric code
  6907. // of the exception that terminated the program.
  6908. // regex: A regular expression object to be applied to
  6909. // the test's captured standard error output; the death test
  6910. // fails if it does not match.
  6911. //
  6912. // Argument:
  6913. // status_ok: true if exit_status is acceptable in the context of
  6914. // this particular death test, which fails if it is false
  6915. //
  6916. // Returns true iff all of the above conditions are met. Otherwise, the
  6917. // first failing condition, in the order given above, is the one that is
  6918. // reported. Also sets the last death test message string.
  6919. bool DeathTestImpl::Passed(bool status_ok) {
  6920. if (!spawned())
  6921. return false;
  6922. const std::string error_message = GetCapturedStderr();
  6923. bool success = false;
  6924. Message buffer;
  6925. buffer << "Death test: " << statement() << "\n";
  6926. switch (outcome()) {
  6927. case LIVED:
  6928. buffer << " Result: failed to die.\n"
  6929. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6930. break;
  6931. case THREW:
  6932. buffer << " Result: threw an exception.\n"
  6933. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6934. break;
  6935. case RETURNED:
  6936. buffer << " Result: illegal return in test statement.\n"
  6937. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6938. break;
  6939. case DIED:
  6940. if (status_ok) {
  6941. # if GTEST_USES_PCRE
  6942. // PCRE regexes support embedded NULs.
  6943. const bool matched = RE::PartialMatch(error_message, *regex());
  6944. # else
  6945. const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
  6946. # endif // GTEST_USES_PCRE
  6947. if (matched) {
  6948. success = true;
  6949. } else {
  6950. buffer << " Result: died but not with expected error.\n"
  6951. << " Expected: " << regex()->pattern() << "\n"
  6952. << "Actual msg:\n" << FormatDeathTestOutput(error_message);
  6953. }
  6954. } else {
  6955. buffer << " Result: died but not with expected exit code:\n"
  6956. << " " << ExitSummary(status()) << "\n"
  6957. << "Actual msg:\n" << FormatDeathTestOutput(error_message);
  6958. }
  6959. break;
  6960. case IN_PROGRESS:
  6961. default:
  6962. GTEST_LOG_(FATAL)
  6963. << "DeathTest::Passed somehow called before conclusion of test";
  6964. }
  6965. DeathTest::set_last_death_test_message(buffer.GetString());
  6966. return success;
  6967. }
  6968. # if GTEST_OS_WINDOWS
  6969. // WindowsDeathTest implements death tests on Windows. Due to the
  6970. // specifics of starting new processes on Windows, death tests there are
  6971. // always threadsafe, and Google Test considers the
  6972. // --gtest_death_test_style=fast setting to be equivalent to
  6973. // --gtest_death_test_style=threadsafe there.
  6974. //
  6975. // A few implementation notes: Like the Linux version, the Windows
  6976. // implementation uses pipes for child-to-parent communication. But due to
  6977. // the specifics of pipes on Windows, some extra steps are required:
  6978. //
  6979. // 1. The parent creates a communication pipe and stores handles to both
  6980. // ends of it.
  6981. // 2. The parent starts the child and provides it with the information
  6982. // necessary to acquire the handle to the write end of the pipe.
  6983. // 3. The child acquires the write end of the pipe and signals the parent
  6984. // using a Windows event.
  6985. // 4. Now the parent can release the write end of the pipe on its side. If
  6986. // this is done before step 3, the object's reference count goes down to
  6987. // 0 and it is destroyed, preventing the child from acquiring it. The
  6988. // parent now has to release it, or read operations on the read end of
  6989. // the pipe will not return when the child terminates.
  6990. // 5. The parent reads child's output through the pipe (outcome code and
  6991. // any possible error messages) from the pipe, and its stderr and then
  6992. // determines whether to fail the test.
  6993. //
  6994. // Note: to distinguish Win32 API calls from the local method and function
  6995. // calls, the former are explicitly resolved in the global namespace.
  6996. //
  6997. class WindowsDeathTest : public DeathTestImpl {
  6998. public:
  6999. WindowsDeathTest(const char* a_statement,
  7000. const RE* a_regex,
  7001. const char* file,
  7002. int line)
  7003. : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
  7004. // All of these virtual functions are inherited from DeathTest.
  7005. virtual int Wait();
  7006. virtual TestRole AssumeRole();
  7007. private:
  7008. // The name of the file in which the death test is located.
  7009. const char* const file_;
  7010. // The line number on which the death test is located.
  7011. const int line_;
  7012. // Handle to the write end of the pipe to the child process.
  7013. AutoHandle write_handle_;
  7014. // Child process handle.
  7015. AutoHandle child_handle_;
  7016. // Event the child process uses to signal the parent that it has
  7017. // acquired the handle to the write end of the pipe. After seeing this
  7018. // event the parent can release its own handles to make sure its
  7019. // ReadFile() calls return when the child terminates.
  7020. AutoHandle event_handle_;
  7021. };
  7022. // Waits for the child in a death test to exit, returning its exit
  7023. // status, or 0 if no child process exists. As a side effect, sets the
  7024. // outcome data member.
  7025. int WindowsDeathTest::Wait() {
  7026. if (!spawned())
  7027. return 0;
  7028. // Wait until the child either signals that it has acquired the write end
  7029. // of the pipe or it dies.
  7030. const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
  7031. switch (::WaitForMultipleObjects(2,
  7032. wait_handles,
  7033. FALSE, // Waits for any of the handles.
  7034. INFINITE)) {
  7035. case WAIT_OBJECT_0:
  7036. case WAIT_OBJECT_0 + 1:
  7037. break;
  7038. default:
  7039. GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
  7040. }
  7041. // The child has acquired the write end of the pipe or exited.
  7042. // We release the handle on our side and continue.
  7043. write_handle_.Reset();
  7044. event_handle_.Reset();
  7045. ReadAndInterpretStatusByte();
  7046. // Waits for the child process to exit if it haven't already. This
  7047. // returns immediately if the child has already exited, regardless of
  7048. // whether previous calls to WaitForMultipleObjects synchronized on this
  7049. // handle or not.
  7050. GTEST_DEATH_TEST_CHECK_(
  7051. WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
  7052. INFINITE));
  7053. DWORD status_code;
  7054. GTEST_DEATH_TEST_CHECK_(
  7055. ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
  7056. child_handle_.Reset();
  7057. set_status(static_cast<int>(status_code));
  7058. return status();
  7059. }
  7060. // The AssumeRole process for a Windows death test. It creates a child
  7061. // process with the same executable as the current process to run the
  7062. // death test. The child process is given the --gtest_filter and
  7063. // --gtest_internal_run_death_test flags such that it knows to run the
  7064. // current death test only.
  7065. DeathTest::TestRole WindowsDeathTest::AssumeRole() {
  7066. const UnitTestImpl* const impl = GetUnitTestImpl();
  7067. const InternalRunDeathTestFlag* const flag =
  7068. impl->internal_run_death_test_flag();
  7069. const TestInfo* const info = impl->current_test_info();
  7070. const int death_test_index = info->result()->death_test_count();
  7071. if (flag != NULL) {
  7072. // ParseInternalRunDeathTestFlag() has performed all the necessary
  7073. // processing.
  7074. set_write_fd(flag->write_fd());
  7075. return EXECUTE_TEST;
  7076. }
  7077. // WindowsDeathTest uses an anonymous pipe to communicate results of
  7078. // a death test.
  7079. SECURITY_ATTRIBUTES handles_are_inheritable = {
  7080. sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
  7081. HANDLE read_handle, write_handle;
  7082. GTEST_DEATH_TEST_CHECK_(
  7083. ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
  7084. 0) // Default buffer size.
  7085. != FALSE);
  7086. set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
  7087. O_RDONLY));
  7088. write_handle_.Reset(write_handle);
  7089. event_handle_.Reset(::CreateEvent(
  7090. &handles_are_inheritable,
  7091. TRUE, // The event will automatically reset to non-signaled state.
  7092. FALSE, // The initial state is non-signalled.
  7093. NULL)); // The even is unnamed.
  7094. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
  7095. const std::string filter_flag =
  7096. std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
  7097. info->test_case_name() + "." + info->name();
  7098. const std::string internal_flag =
  7099. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
  7100. "=" + file_ + "|" + StreamableToString(line_) + "|" +
  7101. StreamableToString(death_test_index) + "|" +
  7102. StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
  7103. // size_t has the same width as pointers on both 32-bit and 64-bit
  7104. // Windows platforms.
  7105. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
  7106. "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
  7107. "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
  7108. char executable_path[_MAX_PATH + 1]; // NOLINT
  7109. GTEST_DEATH_TEST_CHECK_(
  7110. _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
  7111. executable_path,
  7112. _MAX_PATH));
  7113. std::string command_line =
  7114. std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
  7115. internal_flag + "\"";
  7116. DeathTest::set_last_death_test_message("");
  7117. CaptureStderr();
  7118. // Flush the log buffers since the log streams are shared with the child.
  7119. FlushInfoLog();
  7120. // The child process will share the standard handles with the parent.
  7121. STARTUPINFOA startup_info;
  7122. memset(&startup_info, 0, sizeof(STARTUPINFO));
  7123. startup_info.dwFlags = STARTF_USESTDHANDLES;
  7124. startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
  7125. startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
  7126. startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
  7127. PROCESS_INFORMATION process_info;
  7128. GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
  7129. executable_path,
  7130. const_cast<char*>(command_line.c_str()),
  7131. NULL, // Retuned process handle is not inheritable.
  7132. NULL, // Retuned thread handle is not inheritable.
  7133. TRUE, // Child inherits all inheritable handles (for write_handle_).
  7134. 0x0, // Default creation flags.
  7135. NULL, // Inherit the parent's environment.
  7136. UnitTest::GetInstance()->original_working_dir(),
  7137. &startup_info,
  7138. &process_info) != FALSE);
  7139. child_handle_.Reset(process_info.hProcess);
  7140. ::CloseHandle(process_info.hThread);
  7141. set_spawned(true);
  7142. return OVERSEE_TEST;
  7143. }
  7144. # elif GTEST_OS_FUCHSIA
  7145. class FuchsiaDeathTest : public DeathTestImpl {
  7146. public:
  7147. FuchsiaDeathTest(const char* a_statement,
  7148. const RE* a_regex,
  7149. const char* file,
  7150. int line)
  7151. : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
  7152. virtual ~FuchsiaDeathTest() {
  7153. zx_status_t status = zx_handle_close(child_process_);
  7154. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7155. status = zx_handle_close(port_);
  7156. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7157. }
  7158. // All of these virtual functions are inherited from DeathTest.
  7159. virtual int Wait();
  7160. virtual TestRole AssumeRole();
  7161. private:
  7162. // The name of the file in which the death test is located.
  7163. const char* const file_;
  7164. // The line number on which the death test is located.
  7165. const int line_;
  7166. zx_handle_t child_process_ = ZX_HANDLE_INVALID;
  7167. zx_handle_t port_ = ZX_HANDLE_INVALID;
  7168. };
  7169. // Utility class for accumulating command-line arguments.
  7170. class Arguments {
  7171. public:
  7172. Arguments() {
  7173. args_.push_back(NULL);
  7174. }
  7175. ~Arguments() {
  7176. for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
  7177. ++i) {
  7178. free(*i);
  7179. }
  7180. }
  7181. void AddArgument(const char* argument) {
  7182. args_.insert(args_.end() - 1, posix::StrDup(argument));
  7183. }
  7184. template <typename Str>
  7185. void AddArguments(const ::std::vector<Str>& arguments) {
  7186. for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
  7187. i != arguments.end();
  7188. ++i) {
  7189. args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
  7190. }
  7191. }
  7192. char* const* Argv() {
  7193. return &args_[0];
  7194. }
  7195. int size() {
  7196. return args_.size() - 1;
  7197. }
  7198. private:
  7199. std::vector<char*> args_;
  7200. };
  7201. // Waits for the child in a death test to exit, returning its exit
  7202. // status, or 0 if no child process exists. As a side effect, sets the
  7203. // outcome data member.
  7204. int FuchsiaDeathTest::Wait() {
  7205. if (!spawned())
  7206. return 0;
  7207. // Register to wait for the child process to terminate.
  7208. zx_status_t status_zx;
  7209. status_zx = zx_object_wait_async(child_process_,
  7210. port_,
  7211. 0 /* key */,
  7212. ZX_PROCESS_TERMINATED,
  7213. ZX_WAIT_ASYNC_ONCE);
  7214. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7215. // Wait for it to terminate, or an exception to be received.
  7216. zx_port_packet_t packet;
  7217. status_zx = zx_port_wait(port_, ZX_TIME_INFINITE, &packet);
  7218. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7219. if (ZX_PKT_IS_EXCEPTION(packet.type)) {
  7220. // Process encountered an exception. Kill it directly rather than letting
  7221. // other handlers process the event.
  7222. status_zx = zx_task_kill(child_process_);
  7223. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7224. // Now wait for |child_process_| to terminate.
  7225. zx_signals_t signals = 0;
  7226. status_zx = zx_object_wait_one(
  7227. child_process_, ZX_PROCESS_TERMINATED, ZX_TIME_INFINITE, &signals);
  7228. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7229. GTEST_DEATH_TEST_CHECK_(signals & ZX_PROCESS_TERMINATED);
  7230. } else {
  7231. // Process terminated.
  7232. GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
  7233. GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
  7234. }
  7235. ReadAndInterpretStatusByte();
  7236. zx_info_process_t buffer;
  7237. status_zx = zx_object_get_info(
  7238. child_process_,
  7239. ZX_INFO_PROCESS,
  7240. &buffer,
  7241. sizeof(buffer),
  7242. nullptr,
  7243. nullptr);
  7244. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7245. GTEST_DEATH_TEST_CHECK_(buffer.exited);
  7246. set_status(buffer.return_code);
  7247. return status();
  7248. }
  7249. // The AssumeRole process for a Fuchsia death test. It creates a child
  7250. // process with the same executable as the current process to run the
  7251. // death test. The child process is given the --gtest_filter and
  7252. // --gtest_internal_run_death_test flags such that it knows to run the
  7253. // current death test only.
  7254. DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
  7255. const UnitTestImpl* const impl = GetUnitTestImpl();
  7256. const InternalRunDeathTestFlag* const flag =
  7257. impl->internal_run_death_test_flag();
  7258. const TestInfo* const info = impl->current_test_info();
  7259. const int death_test_index = info->result()->death_test_count();
  7260. if (flag != NULL) {
  7261. // ParseInternalRunDeathTestFlag() has performed all the necessary
  7262. // processing.
  7263. set_write_fd(kFuchsiaReadPipeFd);
  7264. return EXECUTE_TEST;
  7265. }
  7266. CaptureStderr();
  7267. // Flush the log buffers since the log streams are shared with the child.
  7268. FlushInfoLog();
  7269. // Build the child process command line.
  7270. const std::string filter_flag =
  7271. std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
  7272. + info->test_case_name() + "." + info->name();
  7273. const std::string internal_flag =
  7274. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
  7275. + file_ + "|"
  7276. + StreamableToString(line_) + "|"
  7277. + StreamableToString(death_test_index);
  7278. Arguments args;
  7279. args.AddArguments(GetInjectableArgvs());
  7280. args.AddArgument(filter_flag.c_str());
  7281. args.AddArgument(internal_flag.c_str());
  7282. // Build the pipe for communication with the child.
  7283. zx_status_t status;
  7284. zx_handle_t child_pipe_handle;
  7285. uint32_t type;
  7286. status = fdio_pipe_half(&child_pipe_handle, &type);
  7287. GTEST_DEATH_TEST_CHECK_(status >= 0);
  7288. set_read_fd(status);
  7289. // Set the pipe handle for the child.
  7290. fdio_spawn_action_t add_handle_action = {};
  7291. add_handle_action.action = FDIO_SPAWN_ACTION_ADD_HANDLE;
  7292. add_handle_action.h.id = PA_HND(type, kFuchsiaReadPipeFd);
  7293. add_handle_action.h.handle = child_pipe_handle;
  7294. // Spawn the child process.
  7295. status = fdio_spawn_etc(ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL,
  7296. args.Argv()[0], args.Argv(), nullptr, 1,
  7297. &add_handle_action, &child_process_, nullptr);
  7298. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7299. // Create an exception port and attach it to the |child_process_|, to allow
  7300. // us to suppress the system default exception handler from firing.
  7301. status = zx_port_create(0, &port_);
  7302. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7303. status = zx_task_bind_exception_port(
  7304. child_process_, port_, 0 /* key */, 0 /*options */);
  7305. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7306. set_spawned(true);
  7307. return OVERSEE_TEST;
  7308. }
  7309. #else // We are neither on Windows, nor on Fuchsia.
  7310. // ForkingDeathTest provides implementations for most of the abstract
  7311. // methods of the DeathTest interface. Only the AssumeRole method is
  7312. // left undefined.
  7313. class ForkingDeathTest : public DeathTestImpl {
  7314. public:
  7315. ForkingDeathTest(const char* statement, const RE* regex);
  7316. // All of these virtual functions are inherited from DeathTest.
  7317. virtual int Wait();
  7318. protected:
  7319. void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
  7320. private:
  7321. // PID of child process during death test; 0 in the child process itself.
  7322. pid_t child_pid_;
  7323. };
  7324. // Constructs a ForkingDeathTest.
  7325. ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
  7326. : DeathTestImpl(a_statement, a_regex),
  7327. child_pid_(-1) {}
  7328. // Waits for the child in a death test to exit, returning its exit
  7329. // status, or 0 if no child process exists. As a side effect, sets the
  7330. // outcome data member.
  7331. int ForkingDeathTest::Wait() {
  7332. if (!spawned())
  7333. return 0;
  7334. ReadAndInterpretStatusByte();
  7335. int status_value;
  7336. GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
  7337. set_status(status_value);
  7338. return status_value;
  7339. }
  7340. // A concrete death test class that forks, then immediately runs the test
  7341. // in the child process.
  7342. class NoExecDeathTest : public ForkingDeathTest {
  7343. public:
  7344. NoExecDeathTest(const char* a_statement, const RE* a_regex) :
  7345. ForkingDeathTest(a_statement, a_regex) { }
  7346. virtual TestRole AssumeRole();
  7347. };
  7348. // The AssumeRole process for a fork-and-run death test. It implements a
  7349. // straightforward fork, with a simple pipe to transmit the status byte.
  7350. DeathTest::TestRole NoExecDeathTest::AssumeRole() {
  7351. const size_t thread_count = GetThreadCount();
  7352. if (thread_count != 1) {
  7353. GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
  7354. }
  7355. int pipe_fd[2];
  7356. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  7357. DeathTest::set_last_death_test_message("");
  7358. CaptureStderr();
  7359. // When we fork the process below, the log file buffers are copied, but the
  7360. // file descriptors are shared. We flush all log files here so that closing
  7361. // the file descriptors in the child process doesn't throw off the
  7362. // synchronization between descriptors and buffers in the parent process.
  7363. // This is as close to the fork as possible to avoid a race condition in case
  7364. // there are multiple threads running before the death test, and another
  7365. // thread writes to the log file.
  7366. FlushInfoLog();
  7367. const pid_t child_pid = fork();
  7368. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  7369. set_child_pid(child_pid);
  7370. if (child_pid == 0) {
  7371. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
  7372. set_write_fd(pipe_fd[1]);
  7373. // Redirects all logging to stderr in the child process to prevent
  7374. // concurrent writes to the log files. We capture stderr in the parent
  7375. // process and append the child process' output to a log.
  7376. LogToStderr();
  7377. // Event forwarding to the listeners of event listener API mush be shut
  7378. // down in death test subprocesses.
  7379. GetUnitTestImpl()->listeners()->SuppressEventForwarding();
  7380. g_in_fast_death_test_child = true;
  7381. return EXECUTE_TEST;
  7382. } else {
  7383. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  7384. set_read_fd(pipe_fd[0]);
  7385. set_spawned(true);
  7386. return OVERSEE_TEST;
  7387. }
  7388. }
  7389. // A concrete death test class that forks and re-executes the main
  7390. // program from the beginning, with command-line flags set that cause
  7391. // only this specific death test to be run.
  7392. class ExecDeathTest : public ForkingDeathTest {
  7393. public:
  7394. ExecDeathTest(const char* a_statement, const RE* a_regex,
  7395. const char* file, int line) :
  7396. ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
  7397. virtual TestRole AssumeRole();
  7398. private:
  7399. static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
  7400. ::std::vector<std::string> args = GetInjectableArgvs();
  7401. # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
  7402. ::std::vector<std::string> extra_args =
  7403. GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
  7404. args.insert(args.end(), extra_args.begin(), extra_args.end());
  7405. # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
  7406. return args;
  7407. }
  7408. // The name of the file in which the death test is located.
  7409. const char* const file_;
  7410. // The line number on which the death test is located.
  7411. const int line_;
  7412. };
  7413. // Utility class for accumulating command-line arguments.
  7414. class Arguments {
  7415. public:
  7416. Arguments() {
  7417. args_.push_back(NULL);
  7418. }
  7419. ~Arguments() {
  7420. for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
  7421. ++i) {
  7422. free(*i);
  7423. }
  7424. }
  7425. void AddArgument(const char* argument) {
  7426. args_.insert(args_.end() - 1, posix::StrDup(argument));
  7427. }
  7428. template <typename Str>
  7429. void AddArguments(const ::std::vector<Str>& arguments) {
  7430. for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
  7431. i != arguments.end();
  7432. ++i) {
  7433. args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
  7434. }
  7435. }
  7436. char* const* Argv() {
  7437. return &args_[0];
  7438. }
  7439. private:
  7440. std::vector<char*> args_;
  7441. };
  7442. // A struct that encompasses the arguments to the child process of a
  7443. // threadsafe-style death test process.
  7444. struct ExecDeathTestArgs {
  7445. char* const* argv; // Command-line arguments for the child's call to exec
  7446. int close_fd; // File descriptor to close; the read end of a pipe
  7447. };
  7448. # if GTEST_OS_MAC
  7449. inline char** GetEnviron() {
  7450. // When Google Test is built as a framework on MacOS X, the environ variable
  7451. // is unavailable. Apple's documentation (man environ) recommends using
  7452. // _NSGetEnviron() instead.
  7453. return *_NSGetEnviron();
  7454. }
  7455. # else
  7456. // Some POSIX platforms expect you to declare environ. extern "C" makes
  7457. // it reside in the global namespace.
  7458. extern "C" char** environ;
  7459. inline char** GetEnviron() { return environ; }
  7460. # endif // GTEST_OS_MAC
  7461. # if !GTEST_OS_QNX
  7462. // The main function for a threadsafe-style death test child process.
  7463. // This function is called in a clone()-ed process and thus must avoid
  7464. // any potentially unsafe operations like malloc or libc functions.
  7465. static int ExecDeathTestChildMain(void* child_arg) {
  7466. ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
  7467. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
  7468. // We need to execute the test program in the same environment where
  7469. // it was originally invoked. Therefore we change to the original
  7470. // working directory first.
  7471. const char* const original_dir =
  7472. UnitTest::GetInstance()->original_working_dir();
  7473. // We can safely call chdir() as it's a direct system call.
  7474. if (chdir(original_dir) != 0) {
  7475. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  7476. GetLastErrnoDescription());
  7477. return EXIT_FAILURE;
  7478. }
  7479. // We can safely call execve() as it's a direct system call. We
  7480. // cannot use execvp() as it's a libc function and thus potentially
  7481. // unsafe. Since execve() doesn't search the PATH, the user must
  7482. // invoke the test program via a valid path that contains at least
  7483. // one path separator.
  7484. execve(args->argv[0], args->argv, GetEnviron());
  7485. DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
  7486. original_dir + " failed: " +
  7487. GetLastErrnoDescription());
  7488. return EXIT_FAILURE;
  7489. }
  7490. # endif // !GTEST_OS_QNX
  7491. # if GTEST_HAS_CLONE
  7492. // Two utility routines that together determine the direction the stack
  7493. // grows.
  7494. // This could be accomplished more elegantly by a single recursive
  7495. // function, but we want to guard against the unlikely possibility of
  7496. // a smart compiler optimizing the recursion away.
  7497. //
  7498. // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
  7499. // StackLowerThanAddress into StackGrowsDown, which then doesn't give
  7500. // correct answer.
  7501. static void StackLowerThanAddress(const void* ptr,
  7502. bool* result) GTEST_NO_INLINE_;
  7503. static void StackLowerThanAddress(const void* ptr, bool* result) {
  7504. int dummy;
  7505. *result = (&dummy < ptr);
  7506. }
  7507. // Make sure AddressSanitizer does not tamper with the stack here.
  7508. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  7509. static bool StackGrowsDown() {
  7510. int dummy = 0;
  7511. bool result;
  7512. StackLowerThanAddress(&dummy, &result);
  7513. return result;
  7514. }
  7515. # endif // GTEST_HAS_CLONE
  7516. // Spawns a child process with the same executable as the current process in
  7517. // a thread-safe manner and instructs it to run the death test. The
  7518. // implementation uses fork(2) + exec. On systems where clone(2) is
  7519. // available, it is used instead, being slightly more thread-safe. On QNX,
  7520. // fork supports only single-threaded environments, so this function uses
  7521. // spawn(2) there instead. The function dies with an error message if
  7522. // anything goes wrong.
  7523. static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
  7524. ExecDeathTestArgs args = { argv, close_fd };
  7525. pid_t child_pid = -1;
  7526. # if GTEST_OS_QNX
  7527. // Obtains the current directory and sets it to be closed in the child
  7528. // process.
  7529. const int cwd_fd = open(".", O_RDONLY);
  7530. GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
  7531. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
  7532. // We need to execute the test program in the same environment where
  7533. // it was originally invoked. Therefore we change to the original
  7534. // working directory first.
  7535. const char* const original_dir =
  7536. UnitTest::GetInstance()->original_working_dir();
  7537. // We can safely call chdir() as it's a direct system call.
  7538. if (chdir(original_dir) != 0) {
  7539. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  7540. GetLastErrnoDescription());
  7541. return EXIT_FAILURE;
  7542. }
  7543. int fd_flags;
  7544. // Set close_fd to be closed after spawn.
  7545. GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
  7546. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
  7547. fd_flags | FD_CLOEXEC));
  7548. struct inheritance inherit = {0};
  7549. // spawn is a system call.
  7550. child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
  7551. // Restores the current working directory.
  7552. GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
  7553. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
  7554. # else // GTEST_OS_QNX
  7555. # if GTEST_OS_LINUX
  7556. // When a SIGPROF signal is received while fork() or clone() are executing,
  7557. // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
  7558. // it after the call to fork()/clone() is complete.
  7559. struct sigaction saved_sigprof_action;
  7560. struct sigaction ignore_sigprof_action;
  7561. memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
  7562. sigemptyset(&ignore_sigprof_action.sa_mask);
  7563. ignore_sigprof_action.sa_handler = SIG_IGN;
  7564. GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
  7565. SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
  7566. # endif // GTEST_OS_LINUX
  7567. # if GTEST_HAS_CLONE
  7568. const bool use_fork = GTEST_FLAG(death_test_use_fork);
  7569. if (!use_fork) {
  7570. static const bool stack_grows_down = StackGrowsDown();
  7571. const size_t stack_size = getpagesize();
  7572. // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
  7573. void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
  7574. MAP_ANON | MAP_PRIVATE, -1, 0);
  7575. GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
  7576. // Maximum stack alignment in bytes: For a downward-growing stack, this
  7577. // amount is subtracted from size of the stack space to get an address
  7578. // that is within the stack space and is aligned on all systems we care
  7579. // about. As far as I know there is no ABI with stack alignment greater
  7580. // than 64. We assume stack and stack_size already have alignment of
  7581. // kMaxStackAlignment.
  7582. const size_t kMaxStackAlignment = 64;
  7583. void* const stack_top =
  7584. static_cast<char*>(stack) +
  7585. (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
  7586. GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
  7587. reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
  7588. child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
  7589. GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
  7590. }
  7591. # else
  7592. const bool use_fork = true;
  7593. # endif // GTEST_HAS_CLONE
  7594. if (use_fork && (child_pid = fork()) == 0) {
  7595. ExecDeathTestChildMain(&args);
  7596. _exit(0);
  7597. }
  7598. # endif // GTEST_OS_QNX
  7599. # if GTEST_OS_LINUX
  7600. GTEST_DEATH_TEST_CHECK_SYSCALL_(
  7601. sigaction(SIGPROF, &saved_sigprof_action, NULL));
  7602. # endif // GTEST_OS_LINUX
  7603. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  7604. return child_pid;
  7605. }
  7606. // The AssumeRole process for a fork-and-exec death test. It re-executes the
  7607. // main program from the beginning, setting the --gtest_filter
  7608. // and --gtest_internal_run_death_test flags to cause only the current
  7609. // death test to be re-run.
  7610. DeathTest::TestRole ExecDeathTest::AssumeRole() {
  7611. const UnitTestImpl* const impl = GetUnitTestImpl();
  7612. const InternalRunDeathTestFlag* const flag =
  7613. impl->internal_run_death_test_flag();
  7614. const TestInfo* const info = impl->current_test_info();
  7615. const int death_test_index = info->result()->death_test_count();
  7616. if (flag != NULL) {
  7617. set_write_fd(flag->write_fd());
  7618. return EXECUTE_TEST;
  7619. }
  7620. int pipe_fd[2];
  7621. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  7622. // Clear the close-on-exec flag on the write end of the pipe, lest
  7623. // it be closed when the child process does an exec:
  7624. GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
  7625. const std::string filter_flag =
  7626. std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
  7627. + info->test_case_name() + "." + info->name();
  7628. const std::string internal_flag =
  7629. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
  7630. + file_ + "|" + StreamableToString(line_) + "|"
  7631. + StreamableToString(death_test_index) + "|"
  7632. + StreamableToString(pipe_fd[1]);
  7633. Arguments args;
  7634. args.AddArguments(GetArgvsForDeathTestChildProcess());
  7635. args.AddArgument(filter_flag.c_str());
  7636. args.AddArgument(internal_flag.c_str());
  7637. DeathTest::set_last_death_test_message("");
  7638. CaptureStderr();
  7639. // See the comment in NoExecDeathTest::AssumeRole for why the next line
  7640. // is necessary.
  7641. FlushInfoLog();
  7642. const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
  7643. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  7644. set_child_pid(child_pid);
  7645. set_read_fd(pipe_fd[0]);
  7646. set_spawned(true);
  7647. return OVERSEE_TEST;
  7648. }
  7649. # endif // !GTEST_OS_WINDOWS
  7650. // Creates a concrete DeathTest-derived class that depends on the
  7651. // --gtest_death_test_style flag, and sets the pointer pointed to
  7652. // by the "test" argument to its address. If the test should be
  7653. // skipped, sets that pointer to NULL. Returns true, unless the
  7654. // flag is set to an invalid value.
  7655. bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
  7656. const char* file, int line,
  7657. DeathTest** test) {
  7658. UnitTestImpl* const impl = GetUnitTestImpl();
  7659. const InternalRunDeathTestFlag* const flag =
  7660. impl->internal_run_death_test_flag();
  7661. const int death_test_index = impl->current_test_info()
  7662. ->increment_death_test_count();
  7663. if (flag != NULL) {
  7664. if (death_test_index > flag->index()) {
  7665. DeathTest::set_last_death_test_message(
  7666. "Death test count (" + StreamableToString(death_test_index)
  7667. + ") somehow exceeded expected maximum ("
  7668. + StreamableToString(flag->index()) + ")");
  7669. return false;
  7670. }
  7671. if (!(flag->file() == file && flag->line() == line &&
  7672. flag->index() == death_test_index)) {
  7673. *test = NULL;
  7674. return true;
  7675. }
  7676. }
  7677. # if GTEST_OS_WINDOWS
  7678. if (GTEST_FLAG(death_test_style) == "threadsafe" ||
  7679. GTEST_FLAG(death_test_style) == "fast") {
  7680. *test = new WindowsDeathTest(statement, regex, file, line);
  7681. }
  7682. # elif GTEST_OS_FUCHSIA
  7683. if (GTEST_FLAG(death_test_style) == "threadsafe" ||
  7684. GTEST_FLAG(death_test_style) == "fast") {
  7685. *test = new FuchsiaDeathTest(statement, regex, file, line);
  7686. }
  7687. # else
  7688. if (GTEST_FLAG(death_test_style) == "threadsafe") {
  7689. *test = new ExecDeathTest(statement, regex, file, line);
  7690. } else if (GTEST_FLAG(death_test_style) == "fast") {
  7691. *test = new NoExecDeathTest(statement, regex);
  7692. }
  7693. # endif // GTEST_OS_WINDOWS
  7694. else { // NOLINT - this is more readable than unbalanced brackets inside #if.
  7695. DeathTest::set_last_death_test_message(
  7696. "Unknown death test style \"" + GTEST_FLAG(death_test_style)
  7697. + "\" encountered");
  7698. return false;
  7699. }
  7700. return true;
  7701. }
  7702. # if GTEST_OS_WINDOWS
  7703. // Recreates the pipe and event handles from the provided parameters,
  7704. // signals the event, and returns a file descriptor wrapped around the pipe
  7705. // handle. This function is called in the child process only.
  7706. static int GetStatusFileDescriptor(unsigned int parent_process_id,
  7707. size_t write_handle_as_size_t,
  7708. size_t event_handle_as_size_t) {
  7709. AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
  7710. FALSE, // Non-inheritable.
  7711. parent_process_id));
  7712. if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
  7713. DeathTestAbort("Unable to open parent process " +
  7714. StreamableToString(parent_process_id));
  7715. }
  7716. // FIXME: Replace the following check with a
  7717. // compile-time assertion when available.
  7718. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
  7719. const HANDLE write_handle =
  7720. reinterpret_cast<HANDLE>(write_handle_as_size_t);
  7721. HANDLE dup_write_handle;
  7722. // The newly initialized handle is accessible only in the parent
  7723. // process. To obtain one accessible within the child, we need to use
  7724. // DuplicateHandle.
  7725. if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
  7726. ::GetCurrentProcess(), &dup_write_handle,
  7727. 0x0, // Requested privileges ignored since
  7728. // DUPLICATE_SAME_ACCESS is used.
  7729. FALSE, // Request non-inheritable handler.
  7730. DUPLICATE_SAME_ACCESS)) {
  7731. DeathTestAbort("Unable to duplicate the pipe handle " +
  7732. StreamableToString(write_handle_as_size_t) +
  7733. " from the parent process " +
  7734. StreamableToString(parent_process_id));
  7735. }
  7736. const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
  7737. HANDLE dup_event_handle;
  7738. if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
  7739. ::GetCurrentProcess(), &dup_event_handle,
  7740. 0x0,
  7741. FALSE,
  7742. DUPLICATE_SAME_ACCESS)) {
  7743. DeathTestAbort("Unable to duplicate the event handle " +
  7744. StreamableToString(event_handle_as_size_t) +
  7745. " from the parent process " +
  7746. StreamableToString(parent_process_id));
  7747. }
  7748. const int write_fd =
  7749. ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
  7750. if (write_fd == -1) {
  7751. DeathTestAbort("Unable to convert pipe handle " +
  7752. StreamableToString(write_handle_as_size_t) +
  7753. " to a file descriptor");
  7754. }
  7755. // Signals the parent that the write end of the pipe has been acquired
  7756. // so the parent can release its own write end.
  7757. ::SetEvent(dup_event_handle);
  7758. return write_fd;
  7759. }
  7760. # endif // GTEST_OS_WINDOWS
  7761. // Returns a newly created InternalRunDeathTestFlag object with fields
  7762. // initialized from the GTEST_FLAG(internal_run_death_test) flag if
  7763. // the flag is specified; otherwise returns NULL.
  7764. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
  7765. if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
  7766. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
  7767. // can use it here.
  7768. int line = -1;
  7769. int index = -1;
  7770. ::std::vector< ::std::string> fields;
  7771. SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
  7772. int write_fd = -1;
  7773. # if GTEST_OS_WINDOWS
  7774. unsigned int parent_process_id = 0;
  7775. size_t write_handle_as_size_t = 0;
  7776. size_t event_handle_as_size_t = 0;
  7777. if (fields.size() != 6
  7778. || !ParseNaturalNumber(fields[1], &line)
  7779. || !ParseNaturalNumber(fields[2], &index)
  7780. || !ParseNaturalNumber(fields[3], &parent_process_id)
  7781. || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
  7782. || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
  7783. DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
  7784. GTEST_FLAG(internal_run_death_test));
  7785. }
  7786. write_fd = GetStatusFileDescriptor(parent_process_id,
  7787. write_handle_as_size_t,
  7788. event_handle_as_size_t);
  7789. # elif GTEST_OS_FUCHSIA
  7790. if (fields.size() != 3
  7791. || !ParseNaturalNumber(fields[1], &line)
  7792. || !ParseNaturalNumber(fields[2], &index)) {
  7793. DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
  7794. + GTEST_FLAG(internal_run_death_test));
  7795. }
  7796. # else
  7797. if (fields.size() != 4
  7798. || !ParseNaturalNumber(fields[1], &line)
  7799. || !ParseNaturalNumber(fields[2], &index)
  7800. || !ParseNaturalNumber(fields[3], &write_fd)) {
  7801. DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
  7802. + GTEST_FLAG(internal_run_death_test));
  7803. }
  7804. # endif // GTEST_OS_WINDOWS
  7805. return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
  7806. }
  7807. } // namespace internal
  7808. #endif // GTEST_HAS_DEATH_TEST
  7809. } // namespace testing
  7810. // Copyright 2008, Google Inc.
  7811. // All rights reserved.
  7812. //
  7813. // Redistribution and use in source and binary forms, with or without
  7814. // modification, are permitted provided that the following conditions are
  7815. // met:
  7816. //
  7817. // * Redistributions of source code must retain the above copyright
  7818. // notice, this list of conditions and the following disclaimer.
  7819. // * Redistributions in binary form must reproduce the above
  7820. // copyright notice, this list of conditions and the following disclaimer
  7821. // in the documentation and/or other materials provided with the
  7822. // distribution.
  7823. // * Neither the name of Google Inc. nor the names of its
  7824. // contributors may be used to endorse or promote products derived from
  7825. // this software without specific prior written permission.
  7826. //
  7827. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7828. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7829. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7830. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7831. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7832. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7833. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7834. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7835. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7836. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7837. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7838. #include <stdlib.h>
  7839. #if GTEST_OS_WINDOWS_MOBILE
  7840. # include <windows.h>
  7841. #elif GTEST_OS_WINDOWS
  7842. # include <direct.h>
  7843. # include <io.h>
  7844. #elif GTEST_OS_SYMBIAN
  7845. // Symbian OpenC has PATH_MAX in sys/syslimits.h
  7846. # include <sys/syslimits.h>
  7847. #else
  7848. # include <limits.h>
  7849. # include <climits> // Some Linux distributions define PATH_MAX here.
  7850. #endif // GTEST_OS_WINDOWS_MOBILE
  7851. #if GTEST_OS_WINDOWS
  7852. # define GTEST_PATH_MAX_ _MAX_PATH
  7853. #elif defined(PATH_MAX)
  7854. # define GTEST_PATH_MAX_ PATH_MAX
  7855. #elif defined(_XOPEN_PATH_MAX)
  7856. # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
  7857. #else
  7858. # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
  7859. #endif // GTEST_OS_WINDOWS
  7860. namespace testing {
  7861. namespace internal {
  7862. #if GTEST_OS_WINDOWS
  7863. // On Windows, '\\' is the standard path separator, but many tools and the
  7864. // Windows API also accept '/' as an alternate path separator. Unless otherwise
  7865. // noted, a file path can contain either kind of path separators, or a mixture
  7866. // of them.
  7867. const char kPathSeparator = '\\';
  7868. const char kAlternatePathSeparator = '/';
  7869. const char kAlternatePathSeparatorString[] = "/";
  7870. # if GTEST_OS_WINDOWS_MOBILE
  7871. // Windows CE doesn't have a current directory. You should not use
  7872. // the current directory in tests on Windows CE, but this at least
  7873. // provides a reasonable fallback.
  7874. const char kCurrentDirectoryString[] = "\\";
  7875. // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
  7876. const DWORD kInvalidFileAttributes = 0xffffffff;
  7877. # else
  7878. const char kCurrentDirectoryString[] = ".\\";
  7879. # endif // GTEST_OS_WINDOWS_MOBILE
  7880. #else
  7881. const char kPathSeparator = '/';
  7882. const char kCurrentDirectoryString[] = "./";
  7883. #endif // GTEST_OS_WINDOWS
  7884. // Returns whether the given character is a valid path separator.
  7885. static bool IsPathSeparator(char c) {
  7886. #if GTEST_HAS_ALT_PATH_SEP_
  7887. return (c == kPathSeparator) || (c == kAlternatePathSeparator);
  7888. #else
  7889. return c == kPathSeparator;
  7890. #endif
  7891. }
  7892. // Returns the current working directory, or "" if unsuccessful.
  7893. FilePath FilePath::GetCurrentDir() {
  7894. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
  7895. // Windows CE doesn't have a current directory, so we just return
  7896. // something reasonable.
  7897. return FilePath(kCurrentDirectoryString);
  7898. #elif GTEST_OS_WINDOWS
  7899. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  7900. return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
  7901. #else
  7902. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  7903. char* result = getcwd(cwd, sizeof(cwd));
  7904. # if GTEST_OS_NACL
  7905. // getcwd will likely fail in NaCl due to the sandbox, so return something
  7906. // reasonable. The user may have provided a shim implementation for getcwd,
  7907. // however, so fallback only when failure is detected.
  7908. return FilePath(result == NULL ? kCurrentDirectoryString : cwd);
  7909. # endif // GTEST_OS_NACL
  7910. return FilePath(result == NULL ? "" : cwd);
  7911. #endif // GTEST_OS_WINDOWS_MOBILE
  7912. }
  7913. // Returns a copy of the FilePath with the case-insensitive extension removed.
  7914. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
  7915. // FilePath("dir/file"). If a case-insensitive extension is not
  7916. // found, returns a copy of the original FilePath.
  7917. FilePath FilePath::RemoveExtension(const char* extension) const {
  7918. const std::string dot_extension = std::string(".") + extension;
  7919. if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
  7920. return FilePath(pathname_.substr(
  7921. 0, pathname_.length() - dot_extension.length()));
  7922. }
  7923. return *this;
  7924. }
  7925. // Returns a pointer to the last occurrence of a valid path separator in
  7926. // the FilePath. On Windows, for example, both '/' and '\' are valid path
  7927. // separators. Returns NULL if no path separator was found.
  7928. const char* FilePath::FindLastPathSeparator() const {
  7929. const char* const last_sep = strrchr(c_str(), kPathSeparator);
  7930. #if GTEST_HAS_ALT_PATH_SEP_
  7931. const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
  7932. // Comparing two pointers of which only one is NULL is undefined.
  7933. if (last_alt_sep != NULL &&
  7934. (last_sep == NULL || last_alt_sep > last_sep)) {
  7935. return last_alt_sep;
  7936. }
  7937. #endif
  7938. return last_sep;
  7939. }
  7940. // Returns a copy of the FilePath with the directory part removed.
  7941. // Example: FilePath("path/to/file").RemoveDirectoryName() returns
  7942. // FilePath("file"). If there is no directory part ("just_a_file"), it returns
  7943. // the FilePath unmodified. If there is no file part ("just_a_dir/") it
  7944. // returns an empty FilePath ("").
  7945. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  7946. FilePath FilePath::RemoveDirectoryName() const {
  7947. const char* const last_sep = FindLastPathSeparator();
  7948. return last_sep ? FilePath(last_sep + 1) : *this;
  7949. }
  7950. // RemoveFileName returns the directory path with the filename removed.
  7951. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
  7952. // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
  7953. // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
  7954. // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
  7955. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  7956. FilePath FilePath::RemoveFileName() const {
  7957. const char* const last_sep = FindLastPathSeparator();
  7958. std::string dir;
  7959. if (last_sep) {
  7960. dir = std::string(c_str(), last_sep + 1 - c_str());
  7961. } else {
  7962. dir = kCurrentDirectoryString;
  7963. }
  7964. return FilePath(dir);
  7965. }
  7966. // Helper functions for naming files in a directory for xml output.
  7967. // Given directory = "dir", base_name = "test", number = 0,
  7968. // extension = "xml", returns "dir/test.xml". If number is greater
  7969. // than zero (e.g., 12), returns "dir/test_12.xml".
  7970. // On Windows platform, uses \ as the separator rather than /.
  7971. FilePath FilePath::MakeFileName(const FilePath& directory,
  7972. const FilePath& base_name,
  7973. int number,
  7974. const char* extension) {
  7975. std::string file;
  7976. if (number == 0) {
  7977. file = base_name.string() + "." + extension;
  7978. } else {
  7979. file = base_name.string() + "_" + StreamableToString(number)
  7980. + "." + extension;
  7981. }
  7982. return ConcatPaths(directory, FilePath(file));
  7983. }
  7984. // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
  7985. // On Windows, uses \ as the separator rather than /.
  7986. FilePath FilePath::ConcatPaths(const FilePath& directory,
  7987. const FilePath& relative_path) {
  7988. if (directory.IsEmpty())
  7989. return relative_path;
  7990. const FilePath dir(directory.RemoveTrailingPathSeparator());
  7991. return FilePath(dir.string() + kPathSeparator + relative_path.string());
  7992. }
  7993. // Returns true if pathname describes something findable in the file-system,
  7994. // either a file, directory, or whatever.
  7995. bool FilePath::FileOrDirectoryExists() const {
  7996. #if GTEST_OS_WINDOWS_MOBILE
  7997. LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
  7998. const DWORD attributes = GetFileAttributes(unicode);
  7999. delete [] unicode;
  8000. return attributes != kInvalidFileAttributes;
  8001. #else
  8002. posix::StatStruct file_stat;
  8003. return posix::Stat(pathname_.c_str(), &file_stat) == 0;
  8004. #endif // GTEST_OS_WINDOWS_MOBILE
  8005. }
  8006. // Returns true if pathname describes a directory in the file-system
  8007. // that exists.
  8008. bool FilePath::DirectoryExists() const {
  8009. bool result = false;
  8010. #if GTEST_OS_WINDOWS
  8011. // Don't strip off trailing separator if path is a root directory on
  8012. // Windows (like "C:\\").
  8013. const FilePath& path(IsRootDirectory() ? *this :
  8014. RemoveTrailingPathSeparator());
  8015. #else
  8016. const FilePath& path(*this);
  8017. #endif
  8018. #if GTEST_OS_WINDOWS_MOBILE
  8019. LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
  8020. const DWORD attributes = GetFileAttributes(unicode);
  8021. delete [] unicode;
  8022. if ((attributes != kInvalidFileAttributes) &&
  8023. (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  8024. result = true;
  8025. }
  8026. #else
  8027. posix::StatStruct file_stat;
  8028. result = posix::Stat(path.c_str(), &file_stat) == 0 &&
  8029. posix::IsDir(file_stat);
  8030. #endif // GTEST_OS_WINDOWS_MOBILE
  8031. return result;
  8032. }
  8033. // Returns true if pathname describes a root directory. (Windows has one
  8034. // root directory per disk drive.)
  8035. bool FilePath::IsRootDirectory() const {
  8036. #if GTEST_OS_WINDOWS
  8037. // FIXME: on Windows a network share like
  8038. // \\server\share can be a root directory, although it cannot be the
  8039. // current directory. Handle this properly.
  8040. return pathname_.length() == 3 && IsAbsolutePath();
  8041. #else
  8042. return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
  8043. #endif
  8044. }
  8045. // Returns true if pathname describes an absolute path.
  8046. bool FilePath::IsAbsolutePath() const {
  8047. const char* const name = pathname_.c_str();
  8048. #if GTEST_OS_WINDOWS
  8049. return pathname_.length() >= 3 &&
  8050. ((name[0] >= 'a' && name[0] <= 'z') ||
  8051. (name[0] >= 'A' && name[0] <= 'Z')) &&
  8052. name[1] == ':' &&
  8053. IsPathSeparator(name[2]);
  8054. #else
  8055. return IsPathSeparator(name[0]);
  8056. #endif
  8057. }
  8058. // Returns a pathname for a file that does not currently exist. The pathname
  8059. // will be directory/base_name.extension or
  8060. // directory/base_name_<number>.extension if directory/base_name.extension
  8061. // already exists. The number will be incremented until a pathname is found
  8062. // that does not already exist.
  8063. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
  8064. // There could be a race condition if two or more processes are calling this
  8065. // function at the same time -- they could both pick the same filename.
  8066. FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
  8067. const FilePath& base_name,
  8068. const char* extension) {
  8069. FilePath full_pathname;
  8070. int number = 0;
  8071. do {
  8072. full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
  8073. } while (full_pathname.FileOrDirectoryExists());
  8074. return full_pathname;
  8075. }
  8076. // Returns true if FilePath ends with a path separator, which indicates that
  8077. // it is intended to represent a directory. Returns false otherwise.
  8078. // This does NOT check that a directory (or file) actually exists.
  8079. bool FilePath::IsDirectory() const {
  8080. return !pathname_.empty() &&
  8081. IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
  8082. }
  8083. // Create directories so that path exists. Returns true if successful or if
  8084. // the directories already exist; returns false if unable to create directories
  8085. // for any reason.
  8086. bool FilePath::CreateDirectoriesRecursively() const {
  8087. if (!this->IsDirectory()) {
  8088. return false;
  8089. }
  8090. if (pathname_.length() == 0 || this->DirectoryExists()) {
  8091. return true;
  8092. }
  8093. const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
  8094. return parent.CreateDirectoriesRecursively() && this->CreateFolder();
  8095. }
  8096. // Create the directory so that path exists. Returns true if successful or
  8097. // if the directory already exists; returns false if unable to create the
  8098. // directory for any reason, including if the parent directory does not
  8099. // exist. Not named "CreateDirectory" because that's a macro on Windows.
  8100. bool FilePath::CreateFolder() const {
  8101. #if GTEST_OS_WINDOWS_MOBILE
  8102. FilePath removed_sep(this->RemoveTrailingPathSeparator());
  8103. LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
  8104. int result = CreateDirectory(unicode, NULL) ? 0 : -1;
  8105. delete [] unicode;
  8106. #elif GTEST_OS_WINDOWS
  8107. int result = _mkdir(pathname_.c_str());
  8108. #else
  8109. int result = mkdir(pathname_.c_str(), 0777);
  8110. #endif // GTEST_OS_WINDOWS_MOBILE
  8111. if (result == -1) {
  8112. return this->DirectoryExists(); // An error is OK if the directory exists.
  8113. }
  8114. return true; // No error.
  8115. }
  8116. // If input name has a trailing separator character, remove it and return the
  8117. // name, otherwise return the name string unmodified.
  8118. // On Windows platform, uses \ as the separator, other platforms use /.
  8119. FilePath FilePath::RemoveTrailingPathSeparator() const {
  8120. return IsDirectory()
  8121. ? FilePath(pathname_.substr(0, pathname_.length() - 1))
  8122. : *this;
  8123. }
  8124. // Removes any redundant separators that might be in the pathname.
  8125. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
  8126. // redundancies that might be in a pathname involving "." or "..".
  8127. // FIXME: handle Windows network shares (e.g. \\server\share).
  8128. void FilePath::Normalize() {
  8129. if (pathname_.c_str() == NULL) {
  8130. pathname_ = "";
  8131. return;
  8132. }
  8133. const char* src = pathname_.c_str();
  8134. char* const dest = new char[pathname_.length() + 1];
  8135. char* dest_ptr = dest;
  8136. memset(dest_ptr, 0, pathname_.length() + 1);
  8137. while (*src != '\0') {
  8138. *dest_ptr = *src;
  8139. if (!IsPathSeparator(*src)) {
  8140. src++;
  8141. } else {
  8142. #if GTEST_HAS_ALT_PATH_SEP_
  8143. if (*dest_ptr == kAlternatePathSeparator) {
  8144. *dest_ptr = kPathSeparator;
  8145. }
  8146. #endif
  8147. while (IsPathSeparator(*src))
  8148. src++;
  8149. }
  8150. dest_ptr++;
  8151. }
  8152. *dest_ptr = '\0';
  8153. pathname_ = dest;
  8154. delete[] dest;
  8155. }
  8156. } // namespace internal
  8157. } // namespace testing
  8158. // Copyright 2008, Google Inc.
  8159. // All rights reserved.
  8160. //
  8161. // Redistribution and use in source and binary forms, with or without
  8162. // modification, are permitted provided that the following conditions are
  8163. // met:
  8164. //
  8165. // * Redistributions of source code must retain the above copyright
  8166. // notice, this list of conditions and the following disclaimer.
  8167. // * Redistributions in binary form must reproduce the above
  8168. // copyright notice, this list of conditions and the following disclaimer
  8169. // in the documentation and/or other materials provided with the
  8170. // distribution.
  8171. // * Neither the name of Google Inc. nor the names of its
  8172. // contributors may be used to endorse or promote products derived from
  8173. // this software without specific prior written permission.
  8174. //
  8175. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8176. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8177. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8178. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8179. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8180. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8181. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8182. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8183. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8184. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8185. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8186. #include <limits.h>
  8187. #include <stdlib.h>
  8188. #include <stdio.h>
  8189. #include <string.h>
  8190. #include <fstream>
  8191. #if GTEST_OS_WINDOWS
  8192. # include <windows.h>
  8193. # include <io.h>
  8194. # include <sys/stat.h>
  8195. # include <map> // Used in ThreadLocal.
  8196. #else
  8197. # include <unistd.h>
  8198. #endif // GTEST_OS_WINDOWS
  8199. #if GTEST_OS_MAC
  8200. # include <mach/mach_init.h>
  8201. # include <mach/task.h>
  8202. # include <mach/vm_map.h>
  8203. #endif // GTEST_OS_MAC
  8204. #if GTEST_OS_QNX
  8205. # include <devctl.h>
  8206. # include <fcntl.h>
  8207. # include <sys/procfs.h>
  8208. #endif // GTEST_OS_QNX
  8209. #if GTEST_OS_AIX
  8210. # include <procinfo.h>
  8211. # include <sys/types.h>
  8212. #endif // GTEST_OS_AIX
  8213. #if GTEST_OS_FUCHSIA
  8214. # include <zircon/process.h>
  8215. # include <zircon/syscalls.h>
  8216. #endif // GTEST_OS_FUCHSIA
  8217. namespace testing {
  8218. namespace internal {
  8219. #if defined(_MSC_VER) || defined(__BORLANDC__)
  8220. // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
  8221. const int kStdOutFileno = 1;
  8222. const int kStdErrFileno = 2;
  8223. #else
  8224. const int kStdOutFileno = STDOUT_FILENO;
  8225. const int kStdErrFileno = STDERR_FILENO;
  8226. #endif // _MSC_VER
  8227. #if GTEST_OS_LINUX
  8228. namespace {
  8229. template <typename T>
  8230. T ReadProcFileField(const std::string& filename, int field) {
  8231. std::string dummy;
  8232. std::ifstream file(filename.c_str());
  8233. while (field-- > 0) {
  8234. file >> dummy;
  8235. }
  8236. T output = 0;
  8237. file >> output;
  8238. return output;
  8239. }
  8240. } // namespace
  8241. // Returns the number of active threads, or 0 when there is an error.
  8242. size_t GetThreadCount() {
  8243. const std::string filename =
  8244. (Message() << "/proc/" << getpid() << "/stat").GetString();
  8245. return ReadProcFileField<int>(filename, 19);
  8246. }
  8247. #elif GTEST_OS_MAC
  8248. size_t GetThreadCount() {
  8249. const task_t task = mach_task_self();
  8250. mach_msg_type_number_t thread_count;
  8251. thread_act_array_t thread_list;
  8252. const kern_return_t status = task_threads(task, &thread_list, &thread_count);
  8253. if (status == KERN_SUCCESS) {
  8254. // task_threads allocates resources in thread_list and we need to free them
  8255. // to avoid leaks.
  8256. vm_deallocate(task,
  8257. reinterpret_cast<vm_address_t>(thread_list),
  8258. sizeof(thread_t) * thread_count);
  8259. return static_cast<size_t>(thread_count);
  8260. } else {
  8261. return 0;
  8262. }
  8263. }
  8264. #elif GTEST_OS_QNX
  8265. // Returns the number of threads running in the process, or 0 to indicate that
  8266. // we cannot detect it.
  8267. size_t GetThreadCount() {
  8268. const int fd = open("/proc/self/as", O_RDONLY);
  8269. if (fd < 0) {
  8270. return 0;
  8271. }
  8272. procfs_info process_info;
  8273. const int status =
  8274. devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
  8275. close(fd);
  8276. if (status == EOK) {
  8277. return static_cast<size_t>(process_info.num_threads);
  8278. } else {
  8279. return 0;
  8280. }
  8281. }
  8282. #elif GTEST_OS_AIX
  8283. size_t GetThreadCount() {
  8284. struct procentry64 entry;
  8285. pid_t pid = getpid();
  8286. int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1);
  8287. if (status == 1) {
  8288. return entry.pi_thcount;
  8289. } else {
  8290. return 0;
  8291. }
  8292. }
  8293. #elif GTEST_OS_FUCHSIA
  8294. size_t GetThreadCount() {
  8295. int dummy_buffer;
  8296. size_t avail;
  8297. zx_status_t status = zx_object_get_info(
  8298. zx_process_self(),
  8299. ZX_INFO_PROCESS_THREADS,
  8300. &dummy_buffer,
  8301. 0,
  8302. nullptr,
  8303. &avail);
  8304. if (status == ZX_OK) {
  8305. return avail;
  8306. } else {
  8307. return 0;
  8308. }
  8309. }
  8310. #else
  8311. size_t GetThreadCount() {
  8312. // There's no portable way to detect the number of threads, so we just
  8313. // return 0 to indicate that we cannot detect it.
  8314. return 0;
  8315. }
  8316. #endif // GTEST_OS_LINUX
  8317. #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
  8318. void SleepMilliseconds(int n) {
  8319. ::Sleep(n);
  8320. }
  8321. AutoHandle::AutoHandle()
  8322. : handle_(INVALID_HANDLE_VALUE) {}
  8323. AutoHandle::AutoHandle(Handle handle)
  8324. : handle_(handle) {}
  8325. AutoHandle::~AutoHandle() {
  8326. Reset();
  8327. }
  8328. AutoHandle::Handle AutoHandle::Get() const {
  8329. return handle_;
  8330. }
  8331. void AutoHandle::Reset() {
  8332. Reset(INVALID_HANDLE_VALUE);
  8333. }
  8334. void AutoHandle::Reset(HANDLE handle) {
  8335. // Resetting with the same handle we already own is invalid.
  8336. if (handle_ != handle) {
  8337. if (IsCloseable()) {
  8338. ::CloseHandle(handle_);
  8339. }
  8340. handle_ = handle;
  8341. } else {
  8342. GTEST_CHECK_(!IsCloseable())
  8343. << "Resetting a valid handle to itself is likely a programmer error "
  8344. "and thus not allowed.";
  8345. }
  8346. }
  8347. bool AutoHandle::IsCloseable() const {
  8348. // Different Windows APIs may use either of these values to represent an
  8349. // invalid handle.
  8350. return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;
  8351. }
  8352. Notification::Notification()
  8353. : event_(::CreateEvent(NULL, // Default security attributes.
  8354. TRUE, // Do not reset automatically.
  8355. FALSE, // Initially unset.
  8356. NULL)) { // Anonymous event.
  8357. GTEST_CHECK_(event_.Get() != NULL);
  8358. }
  8359. void Notification::Notify() {
  8360. GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
  8361. }
  8362. void Notification::WaitForNotification() {
  8363. GTEST_CHECK_(
  8364. ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
  8365. }
  8366. Mutex::Mutex()
  8367. : owner_thread_id_(0),
  8368. type_(kDynamic),
  8369. critical_section_init_phase_(0),
  8370. critical_section_(new CRITICAL_SECTION) {
  8371. ::InitializeCriticalSection(critical_section_);
  8372. }
  8373. Mutex::~Mutex() {
  8374. // Static mutexes are leaked intentionally. It is not thread-safe to try
  8375. // to clean them up.
  8376. // FIXME: Switch to Slim Reader/Writer (SRW) Locks, which requires
  8377. // nothing to clean it up but is available only on Vista and later.
  8378. // https://docs.microsoft.com/en-us/windows/desktop/Sync/slim-reader-writer--srw--locks
  8379. if (type_ == kDynamic) {
  8380. ::DeleteCriticalSection(critical_section_);
  8381. delete critical_section_;
  8382. critical_section_ = NULL;
  8383. }
  8384. }
  8385. void Mutex::Lock() {
  8386. ThreadSafeLazyInit();
  8387. ::EnterCriticalSection(critical_section_);
  8388. owner_thread_id_ = ::GetCurrentThreadId();
  8389. }
  8390. void Mutex::Unlock() {
  8391. ThreadSafeLazyInit();
  8392. // We don't protect writing to owner_thread_id_ here, as it's the
  8393. // caller's responsibility to ensure that the current thread holds the
  8394. // mutex when this is called.
  8395. owner_thread_id_ = 0;
  8396. ::LeaveCriticalSection(critical_section_);
  8397. }
  8398. // Does nothing if the current thread holds the mutex. Otherwise, crashes
  8399. // with high probability.
  8400. void Mutex::AssertHeld() {
  8401. ThreadSafeLazyInit();
  8402. GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
  8403. << "The current thread is not holding the mutex @" << this;
  8404. }
  8405. namespace {
  8406. // Use the RAII idiom to flag mem allocs that are intentionally never
  8407. // deallocated. The motivation is to silence the false positive mem leaks
  8408. // that are reported by the debug version of MS's CRT which can only detect
  8409. // if an alloc is missing a matching deallocation.
  8410. // Example:
  8411. // MemoryIsNotDeallocated memory_is_not_deallocated;
  8412. // critical_section_ = new CRITICAL_SECTION;
  8413. //
  8414. class MemoryIsNotDeallocated
  8415. {
  8416. public:
  8417. MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
  8418. #ifdef _MSC_VER
  8419. old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  8420. // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
  8421. // doesn't report mem leak if there's no matching deallocation.
  8422. _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
  8423. #endif // _MSC_VER
  8424. }
  8425. ~MemoryIsNotDeallocated() {
  8426. #ifdef _MSC_VER
  8427. // Restore the original _CRTDBG_ALLOC_MEM_DF flag
  8428. _CrtSetDbgFlag(old_crtdbg_flag_);
  8429. #endif // _MSC_VER
  8430. }
  8431. private:
  8432. int old_crtdbg_flag_;
  8433. GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
  8434. };
  8435. } // namespace
  8436. // Initializes owner_thread_id_ and critical_section_ in static mutexes.
  8437. void Mutex::ThreadSafeLazyInit() {
  8438. // Dynamic mutexes are initialized in the constructor.
  8439. if (type_ == kStatic) {
  8440. switch (
  8441. ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
  8442. case 0:
  8443. // If critical_section_init_phase_ was 0 before the exchange, we
  8444. // are the first to test it and need to perform the initialization.
  8445. owner_thread_id_ = 0;
  8446. {
  8447. // Use RAII to flag that following mem alloc is never deallocated.
  8448. MemoryIsNotDeallocated memory_is_not_deallocated;
  8449. critical_section_ = new CRITICAL_SECTION;
  8450. }
  8451. ::InitializeCriticalSection(critical_section_);
  8452. // Updates the critical_section_init_phase_ to 2 to signal
  8453. // initialization complete.
  8454. GTEST_CHECK_(::InterlockedCompareExchange(
  8455. &critical_section_init_phase_, 2L, 1L) ==
  8456. 1L);
  8457. break;
  8458. case 1:
  8459. // Somebody else is already initializing the mutex; spin until they
  8460. // are done.
  8461. while (::InterlockedCompareExchange(&critical_section_init_phase_,
  8462. 2L,
  8463. 2L) != 2L) {
  8464. // Possibly yields the rest of the thread's time slice to other
  8465. // threads.
  8466. ::Sleep(0);
  8467. }
  8468. break;
  8469. case 2:
  8470. break; // The mutex is already initialized and ready for use.
  8471. default:
  8472. GTEST_CHECK_(false)
  8473. << "Unexpected value of critical_section_init_phase_ "
  8474. << "while initializing a static mutex.";
  8475. }
  8476. }
  8477. }
  8478. namespace {
  8479. class ThreadWithParamSupport : public ThreadWithParamBase {
  8480. public:
  8481. static HANDLE CreateThread(Runnable* runnable,
  8482. Notification* thread_can_start) {
  8483. ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
  8484. DWORD thread_id;
  8485. // FIXME: Consider to use _beginthreadex instead.
  8486. HANDLE thread_handle = ::CreateThread(
  8487. NULL, // Default security.
  8488. 0, // Default stack size.
  8489. &ThreadWithParamSupport::ThreadMain,
  8490. param, // Parameter to ThreadMainStatic
  8491. 0x0, // Default creation flags.
  8492. &thread_id); // Need a valid pointer for the call to work under Win98.
  8493. GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error "
  8494. << ::GetLastError() << ".";
  8495. if (thread_handle == NULL) {
  8496. delete param;
  8497. }
  8498. return thread_handle;
  8499. }
  8500. private:
  8501. struct ThreadMainParam {
  8502. ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
  8503. : runnable_(runnable),
  8504. thread_can_start_(thread_can_start) {
  8505. }
  8506. scoped_ptr<Runnable> runnable_;
  8507. // Does not own.
  8508. Notification* thread_can_start_;
  8509. };
  8510. static DWORD WINAPI ThreadMain(void* ptr) {
  8511. // Transfers ownership.
  8512. scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
  8513. if (param->thread_can_start_ != NULL)
  8514. param->thread_can_start_->WaitForNotification();
  8515. param->runnable_->Run();
  8516. return 0;
  8517. }
  8518. // Prohibit instantiation.
  8519. ThreadWithParamSupport();
  8520. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
  8521. };
  8522. } // namespace
  8523. ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
  8524. Notification* thread_can_start)
  8525. : thread_(ThreadWithParamSupport::CreateThread(runnable,
  8526. thread_can_start)) {
  8527. }
  8528. ThreadWithParamBase::~ThreadWithParamBase() {
  8529. Join();
  8530. }
  8531. void ThreadWithParamBase::Join() {
  8532. GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
  8533. << "Failed to join the thread with error " << ::GetLastError() << ".";
  8534. }
  8535. // Maps a thread to a set of ThreadIdToThreadLocals that have values
  8536. // instantiated on that thread and notifies them when the thread exits. A
  8537. // ThreadLocal instance is expected to persist until all threads it has
  8538. // values on have terminated.
  8539. class ThreadLocalRegistryImpl {
  8540. public:
  8541. // Registers thread_local_instance as having value on the current thread.
  8542. // Returns a value that can be used to identify the thread from other threads.
  8543. static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
  8544. const ThreadLocalBase* thread_local_instance) {
  8545. DWORD current_thread = ::GetCurrentThreadId();
  8546. MutexLock lock(&mutex_);
  8547. ThreadIdToThreadLocals* const thread_to_thread_locals =
  8548. GetThreadLocalsMapLocked();
  8549. ThreadIdToThreadLocals::iterator thread_local_pos =
  8550. thread_to_thread_locals->find(current_thread);
  8551. if (thread_local_pos == thread_to_thread_locals->end()) {
  8552. thread_local_pos = thread_to_thread_locals->insert(
  8553. std::make_pair(current_thread, ThreadLocalValues())).first;
  8554. StartWatcherThreadFor(current_thread);
  8555. }
  8556. ThreadLocalValues& thread_local_values = thread_local_pos->second;
  8557. ThreadLocalValues::iterator value_pos =
  8558. thread_local_values.find(thread_local_instance);
  8559. if (value_pos == thread_local_values.end()) {
  8560. value_pos =
  8561. thread_local_values
  8562. .insert(std::make_pair(
  8563. thread_local_instance,
  8564. linked_ptr<ThreadLocalValueHolderBase>(
  8565. thread_local_instance->NewValueForCurrentThread())))
  8566. .first;
  8567. }
  8568. return value_pos->second.get();
  8569. }
  8570. static void OnThreadLocalDestroyed(
  8571. const ThreadLocalBase* thread_local_instance) {
  8572. std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
  8573. // Clean up the ThreadLocalValues data structure while holding the lock, but
  8574. // defer the destruction of the ThreadLocalValueHolderBases.
  8575. {
  8576. MutexLock lock(&mutex_);
  8577. ThreadIdToThreadLocals* const thread_to_thread_locals =
  8578. GetThreadLocalsMapLocked();
  8579. for (ThreadIdToThreadLocals::iterator it =
  8580. thread_to_thread_locals->begin();
  8581. it != thread_to_thread_locals->end();
  8582. ++it) {
  8583. ThreadLocalValues& thread_local_values = it->second;
  8584. ThreadLocalValues::iterator value_pos =
  8585. thread_local_values.find(thread_local_instance);
  8586. if (value_pos != thread_local_values.end()) {
  8587. value_holders.push_back(value_pos->second);
  8588. thread_local_values.erase(value_pos);
  8589. // This 'if' can only be successful at most once, so theoretically we
  8590. // could break out of the loop here, but we don't bother doing so.
  8591. }
  8592. }
  8593. }
  8594. // Outside the lock, let the destructor for 'value_holders' deallocate the
  8595. // ThreadLocalValueHolderBases.
  8596. }
  8597. static void OnThreadExit(DWORD thread_id) {
  8598. GTEST_CHECK_(thread_id != 0) << ::GetLastError();
  8599. std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
  8600. // Clean up the ThreadIdToThreadLocals data structure while holding the
  8601. // lock, but defer the destruction of the ThreadLocalValueHolderBases.
  8602. {
  8603. MutexLock lock(&mutex_);
  8604. ThreadIdToThreadLocals* const thread_to_thread_locals =
  8605. GetThreadLocalsMapLocked();
  8606. ThreadIdToThreadLocals::iterator thread_local_pos =
  8607. thread_to_thread_locals->find(thread_id);
  8608. if (thread_local_pos != thread_to_thread_locals->end()) {
  8609. ThreadLocalValues& thread_local_values = thread_local_pos->second;
  8610. for (ThreadLocalValues::iterator value_pos =
  8611. thread_local_values.begin();
  8612. value_pos != thread_local_values.end();
  8613. ++value_pos) {
  8614. value_holders.push_back(value_pos->second);
  8615. }
  8616. thread_to_thread_locals->erase(thread_local_pos);
  8617. }
  8618. }
  8619. // Outside the lock, let the destructor for 'value_holders' deallocate the
  8620. // ThreadLocalValueHolderBases.
  8621. }
  8622. private:
  8623. // In a particular thread, maps a ThreadLocal object to its value.
  8624. typedef std::map<const ThreadLocalBase*,
  8625. linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
  8626. // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
  8627. // thread's ID.
  8628. typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
  8629. // Holds the thread id and thread handle that we pass from
  8630. // StartWatcherThreadFor to WatcherThreadFunc.
  8631. typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
  8632. static void StartWatcherThreadFor(DWORD thread_id) {
  8633. // The returned handle will be kept in thread_map and closed by
  8634. // watcher_thread in WatcherThreadFunc.
  8635. HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
  8636. FALSE,
  8637. thread_id);
  8638. GTEST_CHECK_(thread != NULL);
  8639. // We need to pass a valid thread ID pointer into CreateThread for it
  8640. // to work correctly under Win98.
  8641. DWORD watcher_thread_id;
  8642. HANDLE watcher_thread = ::CreateThread(
  8643. NULL, // Default security.
  8644. 0, // Default stack size
  8645. &ThreadLocalRegistryImpl::WatcherThreadFunc,
  8646. reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
  8647. CREATE_SUSPENDED,
  8648. &watcher_thread_id);
  8649. GTEST_CHECK_(watcher_thread != NULL);
  8650. // Give the watcher thread the same priority as ours to avoid being
  8651. // blocked by it.
  8652. ::SetThreadPriority(watcher_thread,
  8653. ::GetThreadPriority(::GetCurrentThread()));
  8654. ::ResumeThread(watcher_thread);
  8655. ::CloseHandle(watcher_thread);
  8656. }
  8657. // Monitors exit from a given thread and notifies those
  8658. // ThreadIdToThreadLocals about thread termination.
  8659. static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
  8660. const ThreadIdAndHandle* tah =
  8661. reinterpret_cast<const ThreadIdAndHandle*>(param);
  8662. GTEST_CHECK_(
  8663. ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
  8664. OnThreadExit(tah->first);
  8665. ::CloseHandle(tah->second);
  8666. delete tah;
  8667. return 0;
  8668. }
  8669. // Returns map of thread local instances.
  8670. static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
  8671. mutex_.AssertHeld();
  8672. MemoryIsNotDeallocated memory_is_not_deallocated;
  8673. static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
  8674. return map;
  8675. }
  8676. // Protects access to GetThreadLocalsMapLocked() and its return value.
  8677. static Mutex mutex_;
  8678. // Protects access to GetThreadMapLocked() and its return value.
  8679. static Mutex thread_map_mutex_;
  8680. };
  8681. Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
  8682. Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
  8683. ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
  8684. const ThreadLocalBase* thread_local_instance) {
  8685. return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
  8686. thread_local_instance);
  8687. }
  8688. void ThreadLocalRegistry::OnThreadLocalDestroyed(
  8689. const ThreadLocalBase* thread_local_instance) {
  8690. ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
  8691. }
  8692. #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
  8693. #if GTEST_USES_POSIX_RE
  8694. // Implements RE. Currently only needed for death tests.
  8695. RE::~RE() {
  8696. if (is_valid_) {
  8697. // regfree'ing an invalid regex might crash because the content
  8698. // of the regex is undefined. Since the regex's are essentially
  8699. // the same, one cannot be valid (or invalid) without the other
  8700. // being so too.
  8701. regfree(&partial_regex_);
  8702. regfree(&full_regex_);
  8703. }
  8704. free(const_cast<char*>(pattern_));
  8705. }
  8706. // Returns true iff regular expression re matches the entire str.
  8707. bool RE::FullMatch(const char* str, const RE& re) {
  8708. if (!re.is_valid_) return false;
  8709. regmatch_t match;
  8710. return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
  8711. }
  8712. // Returns true iff regular expression re matches a substring of str
  8713. // (including str itself).
  8714. bool RE::PartialMatch(const char* str, const RE& re) {
  8715. if (!re.is_valid_) return false;
  8716. regmatch_t match;
  8717. return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
  8718. }
  8719. // Initializes an RE from its string representation.
  8720. void RE::Init(const char* regex) {
  8721. pattern_ = posix::StrDup(regex);
  8722. // Reserves enough bytes to hold the regular expression used for a
  8723. // full match.
  8724. const size_t full_regex_len = strlen(regex) + 10;
  8725. char* const full_pattern = new char[full_regex_len];
  8726. snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
  8727. is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
  8728. // We want to call regcomp(&partial_regex_, ...) even if the
  8729. // previous expression returns false. Otherwise partial_regex_ may
  8730. // not be properly initialized can may cause trouble when it's
  8731. // freed.
  8732. //
  8733. // Some implementation of POSIX regex (e.g. on at least some
  8734. // versions of Cygwin) doesn't accept the empty string as a valid
  8735. // regex. We change it to an equivalent form "()" to be safe.
  8736. if (is_valid_) {
  8737. const char* const partial_regex = (*regex == '\0') ? "()" : regex;
  8738. is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
  8739. }
  8740. EXPECT_TRUE(is_valid_)
  8741. << "Regular expression \"" << regex
  8742. << "\" is not a valid POSIX Extended regular expression.";
  8743. delete[] full_pattern;
  8744. }
  8745. #elif GTEST_USES_SIMPLE_RE
  8746. // Returns true iff ch appears anywhere in str (excluding the
  8747. // terminating '\0' character).
  8748. bool IsInSet(char ch, const char* str) {
  8749. return ch != '\0' && strchr(str, ch) != NULL;
  8750. }
  8751. // Returns true iff ch belongs to the given classification. Unlike
  8752. // similar functions in <ctype.h>, these aren't affected by the
  8753. // current locale.
  8754. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
  8755. bool IsAsciiPunct(char ch) {
  8756. return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
  8757. }
  8758. bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
  8759. bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
  8760. bool IsAsciiWordChar(char ch) {
  8761. return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
  8762. ('0' <= ch && ch <= '9') || ch == '_';
  8763. }
  8764. // Returns true iff "\\c" is a supported escape sequence.
  8765. bool IsValidEscape(char c) {
  8766. return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
  8767. }
  8768. // Returns true iff the given atom (specified by escaped and pattern)
  8769. // matches ch. The result is undefined if the atom is invalid.
  8770. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
  8771. if (escaped) { // "\\p" where p is pattern_char.
  8772. switch (pattern_char) {
  8773. case 'd': return IsAsciiDigit(ch);
  8774. case 'D': return !IsAsciiDigit(ch);
  8775. case 'f': return ch == '\f';
  8776. case 'n': return ch == '\n';
  8777. case 'r': return ch == '\r';
  8778. case 's': return IsAsciiWhiteSpace(ch);
  8779. case 'S': return !IsAsciiWhiteSpace(ch);
  8780. case 't': return ch == '\t';
  8781. case 'v': return ch == '\v';
  8782. case 'w': return IsAsciiWordChar(ch);
  8783. case 'W': return !IsAsciiWordChar(ch);
  8784. }
  8785. return IsAsciiPunct(pattern_char) && pattern_char == ch;
  8786. }
  8787. return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
  8788. }
  8789. // Helper function used by ValidateRegex() to format error messages.
  8790. static std::string FormatRegexSyntaxError(const char* regex, int index) {
  8791. return (Message() << "Syntax error at index " << index
  8792. << " in simple regular expression \"" << regex << "\": ").GetString();
  8793. }
  8794. // Generates non-fatal failures and returns false if regex is invalid;
  8795. // otherwise returns true.
  8796. bool ValidateRegex(const char* regex) {
  8797. if (regex == NULL) {
  8798. // FIXME: fix the source file location in the
  8799. // assertion failures to match where the regex is used in user
  8800. // code.
  8801. ADD_FAILURE() << "NULL is not a valid simple regular expression.";
  8802. return false;
  8803. }
  8804. bool is_valid = true;
  8805. // True iff ?, *, or + can follow the previous atom.
  8806. bool prev_repeatable = false;
  8807. for (int i = 0; regex[i]; i++) {
  8808. if (regex[i] == '\\') { // An escape sequence
  8809. i++;
  8810. if (regex[i] == '\0') {
  8811. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  8812. << "'\\' cannot appear at the end.";
  8813. return false;
  8814. }
  8815. if (!IsValidEscape(regex[i])) {
  8816. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  8817. << "invalid escape sequence \"\\" << regex[i] << "\".";
  8818. is_valid = false;
  8819. }
  8820. prev_repeatable = true;
  8821. } else { // Not an escape sequence.
  8822. const char ch = regex[i];
  8823. if (ch == '^' && i > 0) {
  8824. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  8825. << "'^' can only appear at the beginning.";
  8826. is_valid = false;
  8827. } else if (ch == '$' && regex[i + 1] != '\0') {
  8828. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  8829. << "'$' can only appear at the end.";
  8830. is_valid = false;
  8831. } else if (IsInSet(ch, "()[]{}|")) {
  8832. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  8833. << "'" << ch << "' is unsupported.";
  8834. is_valid = false;
  8835. } else if (IsRepeat(ch) && !prev_repeatable) {
  8836. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  8837. << "'" << ch << "' can only follow a repeatable token.";
  8838. is_valid = false;
  8839. }
  8840. prev_repeatable = !IsInSet(ch, "^$?*+");
  8841. }
  8842. }
  8843. return is_valid;
  8844. }
  8845. // Matches a repeated regex atom followed by a valid simple regular
  8846. // expression. The regex atom is defined as c if escaped is false,
  8847. // or \c otherwise. repeat is the repetition meta character (?, *,
  8848. // or +). The behavior is undefined if str contains too many
  8849. // characters to be indexable by size_t, in which case the test will
  8850. // probably time out anyway. We are fine with this limitation as
  8851. // std::string has it too.
  8852. bool MatchRepetitionAndRegexAtHead(
  8853. bool escaped, char c, char repeat, const char* regex,
  8854. const char* str) {
  8855. const size_t min_count = (repeat == '+') ? 1 : 0;
  8856. const size_t max_count = (repeat == '?') ? 1 :
  8857. static_cast<size_t>(-1) - 1;
  8858. // We cannot call numeric_limits::max() as it conflicts with the
  8859. // max() macro on Windows.
  8860. for (size_t i = 0; i <= max_count; ++i) {
  8861. // We know that the atom matches each of the first i characters in str.
  8862. if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
  8863. // We have enough matches at the head, and the tail matches too.
  8864. // Since we only care about *whether* the pattern matches str
  8865. // (as opposed to *how* it matches), there is no need to find a
  8866. // greedy match.
  8867. return true;
  8868. }
  8869. if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
  8870. return false;
  8871. }
  8872. return false;
  8873. }
  8874. // Returns true iff regex matches a prefix of str. regex must be a
  8875. // valid simple regular expression and not start with "^", or the
  8876. // result is undefined.
  8877. bool MatchRegexAtHead(const char* regex, const char* str) {
  8878. if (*regex == '\0') // An empty regex matches a prefix of anything.
  8879. return true;
  8880. // "$" only matches the end of a string. Note that regex being
  8881. // valid guarantees that there's nothing after "$" in it.
  8882. if (*regex == '$')
  8883. return *str == '\0';
  8884. // Is the first thing in regex an escape sequence?
  8885. const bool escaped = *regex == '\\';
  8886. if (escaped)
  8887. ++regex;
  8888. if (IsRepeat(regex[1])) {
  8889. // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
  8890. // here's an indirect recursion. It terminates as the regex gets
  8891. // shorter in each recursion.
  8892. return MatchRepetitionAndRegexAtHead(
  8893. escaped, regex[0], regex[1], regex + 2, str);
  8894. } else {
  8895. // regex isn't empty, isn't "$", and doesn't start with a
  8896. // repetition. We match the first atom of regex with the first
  8897. // character of str and recurse.
  8898. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
  8899. MatchRegexAtHead(regex + 1, str + 1);
  8900. }
  8901. }
  8902. // Returns true iff regex matches any substring of str. regex must be
  8903. // a valid simple regular expression, or the result is undefined.
  8904. //
  8905. // The algorithm is recursive, but the recursion depth doesn't exceed
  8906. // the regex length, so we won't need to worry about running out of
  8907. // stack space normally. In rare cases the time complexity can be
  8908. // exponential with respect to the regex length + the string length,
  8909. // but usually it's must faster (often close to linear).
  8910. bool MatchRegexAnywhere(const char* regex, const char* str) {
  8911. if (regex == NULL || str == NULL)
  8912. return false;
  8913. if (*regex == '^')
  8914. return MatchRegexAtHead(regex + 1, str);
  8915. // A successful match can be anywhere in str.
  8916. do {
  8917. if (MatchRegexAtHead(regex, str))
  8918. return true;
  8919. } while (*str++ != '\0');
  8920. return false;
  8921. }
  8922. // Implements the RE class.
  8923. RE::~RE() {
  8924. free(const_cast<char*>(pattern_));
  8925. free(const_cast<char*>(full_pattern_));
  8926. }
  8927. // Returns true iff regular expression re matches the entire str.
  8928. bool RE::FullMatch(const char* str, const RE& re) {
  8929. return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
  8930. }
  8931. // Returns true iff regular expression re matches a substring of str
  8932. // (including str itself).
  8933. bool RE::PartialMatch(const char* str, const RE& re) {
  8934. return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
  8935. }
  8936. // Initializes an RE from its string representation.
  8937. void RE::Init(const char* regex) {
  8938. pattern_ = full_pattern_ = NULL;
  8939. if (regex != NULL) {
  8940. pattern_ = posix::StrDup(regex);
  8941. }
  8942. is_valid_ = ValidateRegex(regex);
  8943. if (!is_valid_) {
  8944. // No need to calculate the full pattern when the regex is invalid.
  8945. return;
  8946. }
  8947. const size_t len = strlen(regex);
  8948. // Reserves enough bytes to hold the regular expression used for a
  8949. // full match: we need space to prepend a '^', append a '$', and
  8950. // terminate the string with '\0'.
  8951. char* buffer = static_cast<char*>(malloc(len + 3));
  8952. full_pattern_ = buffer;
  8953. if (*regex != '^')
  8954. *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
  8955. // We don't use snprintf or strncpy, as they trigger a warning when
  8956. // compiled with VC++ 8.0.
  8957. memcpy(buffer, regex, len);
  8958. buffer += len;
  8959. if (len == 0 || regex[len - 1] != '$')
  8960. *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
  8961. *buffer = '\0';
  8962. }
  8963. #endif // GTEST_USES_POSIX_RE
  8964. const char kUnknownFile[] = "unknown file";
  8965. // Formats a source file path and a line number as they would appear
  8966. // in an error message from the compiler used to compile this code.
  8967. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
  8968. const std::string file_name(file == NULL ? kUnknownFile : file);
  8969. if (line < 0) {
  8970. return file_name + ":";
  8971. }
  8972. #ifdef _MSC_VER
  8973. return file_name + "(" + StreamableToString(line) + "):";
  8974. #else
  8975. return file_name + ":" + StreamableToString(line) + ":";
  8976. #endif // _MSC_VER
  8977. }
  8978. // Formats a file location for compiler-independent XML output.
  8979. // Although this function is not platform dependent, we put it next to
  8980. // FormatFileLocation in order to contrast the two functions.
  8981. // Note that FormatCompilerIndependentFileLocation() does NOT append colon
  8982. // to the file location it produces, unlike FormatFileLocation().
  8983. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
  8984. const char* file, int line) {
  8985. const std::string file_name(file == NULL ? kUnknownFile : file);
  8986. if (line < 0)
  8987. return file_name;
  8988. else
  8989. return file_name + ":" + StreamableToString(line);
  8990. }
  8991. GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
  8992. : severity_(severity) {
  8993. const char* const marker =
  8994. severity == GTEST_INFO ? "[ INFO ]" :
  8995. severity == GTEST_WARNING ? "[WARNING]" :
  8996. severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
  8997. GetStream() << ::std::endl << marker << " "
  8998. << FormatFileLocation(file, line).c_str() << ": ";
  8999. }
  9000. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  9001. GTestLog::~GTestLog() {
  9002. GetStream() << ::std::endl;
  9003. if (severity_ == GTEST_FATAL) {
  9004. fflush(stderr);
  9005. posix::Abort();
  9006. }
  9007. }
  9008. // Disable Microsoft deprecation warnings for POSIX functions called from
  9009. // this class (creat, dup, dup2, and close)
  9010. GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
  9011. #if GTEST_HAS_STREAM_REDIRECTION
  9012. // Object that captures an output stream (stdout/stderr).
  9013. class CapturedStream {
  9014. public:
  9015. // The ctor redirects the stream to a temporary file.
  9016. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
  9017. # if GTEST_OS_WINDOWS
  9018. char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  9019. char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  9020. ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
  9021. const UINT success = ::GetTempFileNameA(temp_dir_path,
  9022. "gtest_redir",
  9023. 0, // Generate unique file name.
  9024. temp_file_path);
  9025. GTEST_CHECK_(success != 0)
  9026. << "Unable to create a temporary file in " << temp_dir_path;
  9027. const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
  9028. GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
  9029. << temp_file_path;
  9030. filename_ = temp_file_path;
  9031. # else
  9032. // There's no guarantee that a test has write access to the current
  9033. // directory, so we create the temporary file in the /tmp directory
  9034. // instead. We use /tmp on most systems, and /sdcard on Android.
  9035. // That's because Android doesn't have /tmp.
  9036. # if GTEST_OS_LINUX_ANDROID
  9037. // Note: Android applications are expected to call the framework's
  9038. // Context.getExternalStorageDirectory() method through JNI to get
  9039. // the location of the world-writable SD Card directory. However,
  9040. // this requires a Context handle, which cannot be retrieved
  9041. // globally from native code. Doing so also precludes running the
  9042. // code as part of a regular standalone executable, which doesn't
  9043. // run in a Dalvik process (e.g. when running it through 'adb shell').
  9044. //
  9045. // The location /sdcard is directly accessible from native code
  9046. // and is the only location (unofficially) supported by the Android
  9047. // team. It's generally a symlink to the real SD Card mount point
  9048. // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
  9049. // other OEM-customized locations. Never rely on these, and always
  9050. // use /sdcard.
  9051. char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
  9052. # else
  9053. char name_template[] = "/tmp/captured_stream.XXXXXX";
  9054. # endif // GTEST_OS_LINUX_ANDROID
  9055. const int captured_fd = mkstemp(name_template);
  9056. filename_ = name_template;
  9057. # endif // GTEST_OS_WINDOWS
  9058. fflush(NULL);
  9059. dup2(captured_fd, fd_);
  9060. close(captured_fd);
  9061. }
  9062. ~CapturedStream() {
  9063. remove(filename_.c_str());
  9064. }
  9065. std::string GetCapturedString() {
  9066. if (uncaptured_fd_ != -1) {
  9067. // Restores the original stream.
  9068. fflush(NULL);
  9069. dup2(uncaptured_fd_, fd_);
  9070. close(uncaptured_fd_);
  9071. uncaptured_fd_ = -1;
  9072. }
  9073. FILE* const file = posix::FOpen(filename_.c_str(), "r");
  9074. const std::string content = ReadEntireFile(file);
  9075. posix::FClose(file);
  9076. return content;
  9077. }
  9078. private:
  9079. const int fd_; // A stream to capture.
  9080. int uncaptured_fd_;
  9081. // Name of the temporary file holding the stderr output.
  9082. ::std::string filename_;
  9083. GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
  9084. };
  9085. GTEST_DISABLE_MSC_DEPRECATED_POP_()
  9086. static CapturedStream* g_captured_stderr = NULL;
  9087. static CapturedStream* g_captured_stdout = NULL;
  9088. // Starts capturing an output stream (stdout/stderr).
  9089. static void CaptureStream(int fd, const char* stream_name,
  9090. CapturedStream** stream) {
  9091. if (*stream != NULL) {
  9092. GTEST_LOG_(FATAL) << "Only one " << stream_name
  9093. << " capturer can exist at a time.";
  9094. }
  9095. *stream = new CapturedStream(fd);
  9096. }
  9097. // Stops capturing the output stream and returns the captured string.
  9098. static std::string GetCapturedStream(CapturedStream** captured_stream) {
  9099. const std::string content = (*captured_stream)->GetCapturedString();
  9100. delete *captured_stream;
  9101. *captured_stream = NULL;
  9102. return content;
  9103. }
  9104. // Starts capturing stdout.
  9105. void CaptureStdout() {
  9106. CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
  9107. }
  9108. // Starts capturing stderr.
  9109. void CaptureStderr() {
  9110. CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
  9111. }
  9112. // Stops capturing stdout and returns the captured string.
  9113. std::string GetCapturedStdout() {
  9114. return GetCapturedStream(&g_captured_stdout);
  9115. }
  9116. // Stops capturing stderr and returns the captured string.
  9117. std::string GetCapturedStderr() {
  9118. return GetCapturedStream(&g_captured_stderr);
  9119. }
  9120. #endif // GTEST_HAS_STREAM_REDIRECTION
  9121. size_t GetFileSize(FILE* file) {
  9122. fseek(file, 0, SEEK_END);
  9123. return static_cast<size_t>(ftell(file));
  9124. }
  9125. std::string ReadEntireFile(FILE* file) {
  9126. const size_t file_size = GetFileSize(file);
  9127. char* const buffer = new char[file_size];
  9128. size_t bytes_last_read = 0; // # of bytes read in the last fread()
  9129. size_t bytes_read = 0; // # of bytes read so far
  9130. fseek(file, 0, SEEK_SET);
  9131. // Keeps reading the file until we cannot read further or the
  9132. // pre-determined file size is reached.
  9133. do {
  9134. bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
  9135. bytes_read += bytes_last_read;
  9136. } while (bytes_last_read > 0 && bytes_read < file_size);
  9137. const std::string content(buffer, bytes_read);
  9138. delete[] buffer;
  9139. return content;
  9140. }
  9141. #if GTEST_HAS_DEATH_TEST
  9142. static const std::vector<std::string>* g_injected_test_argvs = NULL; // Owned.
  9143. std::vector<std::string> GetInjectableArgvs() {
  9144. if (g_injected_test_argvs != NULL) {
  9145. return *g_injected_test_argvs;
  9146. }
  9147. return GetArgvs();
  9148. }
  9149. void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
  9150. if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
  9151. g_injected_test_argvs = new_argvs;
  9152. }
  9153. void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
  9154. SetInjectableArgvs(
  9155. new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
  9156. }
  9157. #if GTEST_HAS_GLOBAL_STRING
  9158. void SetInjectableArgvs(const std::vector< ::string>& new_argvs) {
  9159. SetInjectableArgvs(
  9160. new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
  9161. }
  9162. #endif // GTEST_HAS_GLOBAL_STRING
  9163. void ClearInjectableArgvs() {
  9164. delete g_injected_test_argvs;
  9165. g_injected_test_argvs = NULL;
  9166. }
  9167. #endif // GTEST_HAS_DEATH_TEST
  9168. #if GTEST_OS_WINDOWS_MOBILE
  9169. namespace posix {
  9170. void Abort() {
  9171. DebugBreak();
  9172. TerminateProcess(GetCurrentProcess(), 1);
  9173. }
  9174. } // namespace posix
  9175. #endif // GTEST_OS_WINDOWS_MOBILE
  9176. // Returns the name of the environment variable corresponding to the
  9177. // given flag. For example, FlagToEnvVar("foo") will return
  9178. // "GTEST_FOO" in the open-source version.
  9179. static std::string FlagToEnvVar(const char* flag) {
  9180. const std::string full_flag =
  9181. (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
  9182. Message env_var;
  9183. for (size_t i = 0; i != full_flag.length(); i++) {
  9184. env_var << ToUpper(full_flag.c_str()[i]);
  9185. }
  9186. return env_var.GetString();
  9187. }
  9188. // Parses 'str' for a 32-bit signed integer. If successful, writes
  9189. // the result to *value and returns true; otherwise leaves *value
  9190. // unchanged and returns false.
  9191. bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
  9192. // Parses the environment variable as a decimal integer.
  9193. char* end = NULL;
  9194. const long long_value = strtol(str, &end, 10); // NOLINT
  9195. // Has strtol() consumed all characters in the string?
  9196. if (*end != '\0') {
  9197. // No - an invalid character was encountered.
  9198. Message msg;
  9199. msg << "WARNING: " << src_text
  9200. << " is expected to be a 32-bit integer, but actually"
  9201. << " has value \"" << str << "\".\n";
  9202. printf("%s", msg.GetString().c_str());
  9203. fflush(stdout);
  9204. return false;
  9205. }
  9206. // Is the parsed value in the range of an Int32?
  9207. const Int32 result = static_cast<Int32>(long_value);
  9208. if (long_value == LONG_MAX || long_value == LONG_MIN ||
  9209. // The parsed value overflows as a long. (strtol() returns
  9210. // LONG_MAX or LONG_MIN when the input overflows.)
  9211. result != long_value
  9212. // The parsed value overflows as an Int32.
  9213. ) {
  9214. Message msg;
  9215. msg << "WARNING: " << src_text
  9216. << " is expected to be a 32-bit integer, but actually"
  9217. << " has value " << str << ", which overflows.\n";
  9218. printf("%s", msg.GetString().c_str());
  9219. fflush(stdout);
  9220. return false;
  9221. }
  9222. *value = result;
  9223. return true;
  9224. }
  9225. // Reads and returns the Boolean environment variable corresponding to
  9226. // the given flag; if it's not set, returns default_value.
  9227. //
  9228. // The value is considered true iff it's not "0".
  9229. bool BoolFromGTestEnv(const char* flag, bool default_value) {
  9230. #if defined(GTEST_GET_BOOL_FROM_ENV_)
  9231. return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
  9232. #else
  9233. const std::string env_var = FlagToEnvVar(flag);
  9234. const char* const string_value = posix::GetEnv(env_var.c_str());
  9235. return string_value == NULL ?
  9236. default_value : strcmp(string_value, "0") != 0;
  9237. #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
  9238. }
  9239. // Reads and returns a 32-bit integer stored in the environment
  9240. // variable corresponding to the given flag; if it isn't set or
  9241. // doesn't represent a valid 32-bit integer, returns default_value.
  9242. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
  9243. #if defined(GTEST_GET_INT32_FROM_ENV_)
  9244. return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
  9245. #else
  9246. const std::string env_var = FlagToEnvVar(flag);
  9247. const char* const string_value = posix::GetEnv(env_var.c_str());
  9248. if (string_value == NULL) {
  9249. // The environment variable is not set.
  9250. return default_value;
  9251. }
  9252. Int32 result = default_value;
  9253. if (!ParseInt32(Message() << "Environment variable " << env_var,
  9254. string_value, &result)) {
  9255. printf("The default value %s is used.\n",
  9256. (Message() << default_value).GetString().c_str());
  9257. fflush(stdout);
  9258. return default_value;
  9259. }
  9260. return result;
  9261. #endif // defined(GTEST_GET_INT32_FROM_ENV_)
  9262. }
  9263. // As a special case for the 'output' flag, if GTEST_OUTPUT is not
  9264. // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
  9265. // system. The value of XML_OUTPUT_FILE is a filename without the
  9266. // "xml:" prefix of GTEST_OUTPUT.
  9267. // Note that this is meant to be called at the call site so it does
  9268. // not check that the flag is 'output'
  9269. // In essence this checks an env variable called XML_OUTPUT_FILE
  9270. // and if it is set we prepend "xml:" to its value, if it not set we return ""
  9271. std::string OutputFlagAlsoCheckEnvVar(){
  9272. std::string default_value_for_output_flag = "";
  9273. const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
  9274. if (NULL != xml_output_file_env) {
  9275. default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
  9276. }
  9277. return default_value_for_output_flag;
  9278. }
  9279. // Reads and returns the string environment variable corresponding to
  9280. // the given flag; if it's not set, returns default_value.
  9281. const char* StringFromGTestEnv(const char* flag, const char* default_value) {
  9282. #if defined(GTEST_GET_STRING_FROM_ENV_)
  9283. return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
  9284. #else
  9285. const std::string env_var = FlagToEnvVar(flag);
  9286. const char* const value = posix::GetEnv(env_var.c_str());
  9287. return value == NULL ? default_value : value;
  9288. #endif // defined(GTEST_GET_STRING_FROM_ENV_)
  9289. }
  9290. } // namespace internal
  9291. } // namespace testing
  9292. // Copyright 2007, Google Inc.
  9293. // All rights reserved.
  9294. //
  9295. // Redistribution and use in source and binary forms, with or without
  9296. // modification, are permitted provided that the following conditions are
  9297. // met:
  9298. //
  9299. // * Redistributions of source code must retain the above copyright
  9300. // notice, this list of conditions and the following disclaimer.
  9301. // * Redistributions in binary form must reproduce the above
  9302. // copyright notice, this list of conditions and the following disclaimer
  9303. // in the documentation and/or other materials provided with the
  9304. // distribution.
  9305. // * Neither the name of Google Inc. nor the names of its
  9306. // contributors may be used to endorse or promote products derived from
  9307. // this software without specific prior written permission.
  9308. //
  9309. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  9310. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  9311. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  9312. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9313. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  9314. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9315. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  9316. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9317. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  9318. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  9319. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9320. // Google Test - The Google C++ Testing and Mocking Framework
  9321. //
  9322. // This file implements a universal value printer that can print a
  9323. // value of any type T:
  9324. //
  9325. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  9326. //
  9327. // It uses the << operator when possible, and prints the bytes in the
  9328. // object otherwise. A user can override its behavior for a class
  9329. // type Foo by defining either operator<<(::std::ostream&, const Foo&)
  9330. // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
  9331. // defines Foo.
  9332. #include <stdio.h>
  9333. #include <cctype>
  9334. #include <cwchar>
  9335. #include <ostream> // NOLINT
  9336. #include <string>
  9337. namespace testing {
  9338. namespace {
  9339. using ::std::ostream;
  9340. // Prints a segment of bytes in the given object.
  9341. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  9342. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  9343. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  9344. void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
  9345. size_t count, ostream* os) {
  9346. char text[5] = "";
  9347. for (size_t i = 0; i != count; i++) {
  9348. const size_t j = start + i;
  9349. if (i != 0) {
  9350. // Organizes the bytes into groups of 2 for easy parsing by
  9351. // human.
  9352. if ((j % 2) == 0)
  9353. *os << ' ';
  9354. else
  9355. *os << '-';
  9356. }
  9357. GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
  9358. *os << text;
  9359. }
  9360. }
  9361. // Prints the bytes in the given value to the given ostream.
  9362. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
  9363. ostream* os) {
  9364. // Tells the user how big the object is.
  9365. *os << count << "-byte object <";
  9366. const size_t kThreshold = 132;
  9367. const size_t kChunkSize = 64;
  9368. // If the object size is bigger than kThreshold, we'll have to omit
  9369. // some details by printing only the first and the last kChunkSize
  9370. // bytes.
  9371. // FIXME: let the user control the threshold using a flag.
  9372. if (count < kThreshold) {
  9373. PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
  9374. } else {
  9375. PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
  9376. *os << " ... ";
  9377. // Rounds up to 2-byte boundary.
  9378. const size_t resume_pos = (count - kChunkSize + 1)/2*2;
  9379. PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
  9380. }
  9381. *os << ">";
  9382. }
  9383. } // namespace
  9384. namespace internal2 {
  9385. // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
  9386. // given object. The delegation simplifies the implementation, which
  9387. // uses the << operator and thus is easier done outside of the
  9388. // ::testing::internal namespace, which contains a << operator that
  9389. // sometimes conflicts with the one in STL.
  9390. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
  9391. ostream* os) {
  9392. PrintBytesInObjectToImpl(obj_bytes, count, os);
  9393. }
  9394. } // namespace internal2
  9395. namespace internal {
  9396. // Depending on the value of a char (or wchar_t), we print it in one
  9397. // of three formats:
  9398. // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
  9399. // - as a hexadecimal escape sequence (e.g. '\x7F'), or
  9400. // - as a special escape sequence (e.g. '\r', '\n').
  9401. enum CharFormat {
  9402. kAsIs,
  9403. kHexEscape,
  9404. kSpecialEscape
  9405. };
  9406. // Returns true if c is a printable ASCII character. We test the
  9407. // value of c directly instead of calling isprint(), which is buggy on
  9408. // Windows Mobile.
  9409. inline bool IsPrintableAscii(wchar_t c) {
  9410. return 0x20 <= c && c <= 0x7E;
  9411. }
  9412. // Prints a wide or narrow char c as a character literal without the
  9413. // quotes, escaping it when necessary; returns how c was formatted.
  9414. // The template argument UnsignedChar is the unsigned version of Char,
  9415. // which is the type of c.
  9416. template <typename UnsignedChar, typename Char>
  9417. static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
  9418. switch (static_cast<wchar_t>(c)) {
  9419. case L'\0':
  9420. *os << "\\0";
  9421. break;
  9422. case L'\'':
  9423. *os << "\\'";
  9424. break;
  9425. case L'\\':
  9426. *os << "\\\\";
  9427. break;
  9428. case L'\a':
  9429. *os << "\\a";
  9430. break;
  9431. case L'\b':
  9432. *os << "\\b";
  9433. break;
  9434. case L'\f':
  9435. *os << "\\f";
  9436. break;
  9437. case L'\n':
  9438. *os << "\\n";
  9439. break;
  9440. case L'\r':
  9441. *os << "\\r";
  9442. break;
  9443. case L'\t':
  9444. *os << "\\t";
  9445. break;
  9446. case L'\v':
  9447. *os << "\\v";
  9448. break;
  9449. default:
  9450. if (IsPrintableAscii(c)) {
  9451. *os << static_cast<char>(c);
  9452. return kAsIs;
  9453. } else {
  9454. ostream::fmtflags flags = os->flags();
  9455. *os << "\\x" << std::hex << std::uppercase
  9456. << static_cast<int>(static_cast<UnsignedChar>(c));
  9457. os->flags(flags);
  9458. return kHexEscape;
  9459. }
  9460. }
  9461. return kSpecialEscape;
  9462. }
  9463. // Prints a wchar_t c as if it's part of a string literal, escaping it when
  9464. // necessary; returns how c was formatted.
  9465. static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
  9466. switch (c) {
  9467. case L'\'':
  9468. *os << "'";
  9469. return kAsIs;
  9470. case L'"':
  9471. *os << "\\\"";
  9472. return kSpecialEscape;
  9473. default:
  9474. return PrintAsCharLiteralTo<wchar_t>(c, os);
  9475. }
  9476. }
  9477. // Prints a char c as if it's part of a string literal, escaping it when
  9478. // necessary; returns how c was formatted.
  9479. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
  9480. return PrintAsStringLiteralTo(
  9481. static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
  9482. }
  9483. // Prints a wide or narrow character c and its code. '\0' is printed
  9484. // as "'\\0'", other unprintable characters are also properly escaped
  9485. // using the standard C++ escape sequence. The template argument
  9486. // UnsignedChar is the unsigned version of Char, which is the type of c.
  9487. template <typename UnsignedChar, typename Char>
  9488. void PrintCharAndCodeTo(Char c, ostream* os) {
  9489. // First, print c as a literal in the most readable form we can find.
  9490. *os << ((sizeof(c) > 1) ? "L'" : "'");
  9491. const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
  9492. *os << "'";
  9493. // To aid user debugging, we also print c's code in decimal, unless
  9494. // it's 0 (in which case c was printed as '\\0', making the code
  9495. // obvious).
  9496. if (c == 0)
  9497. return;
  9498. *os << " (" << static_cast<int>(c);
  9499. // For more convenience, we print c's code again in hexadecimal,
  9500. // unless c was already printed in the form '\x##' or the code is in
  9501. // [1, 9].
  9502. if (format == kHexEscape || (1 <= c && c <= 9)) {
  9503. // Do nothing.
  9504. } else {
  9505. *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
  9506. }
  9507. *os << ")";
  9508. }
  9509. void PrintTo(unsigned char c, ::std::ostream* os) {
  9510. PrintCharAndCodeTo<unsigned char>(c, os);
  9511. }
  9512. void PrintTo(signed char c, ::std::ostream* os) {
  9513. PrintCharAndCodeTo<unsigned char>(c, os);
  9514. }
  9515. // Prints a wchar_t as a symbol if it is printable or as its internal
  9516. // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
  9517. void PrintTo(wchar_t wc, ostream* os) {
  9518. PrintCharAndCodeTo<wchar_t>(wc, os);
  9519. }
  9520. // Prints the given array of characters to the ostream. CharType must be either
  9521. // char or wchar_t.
  9522. // The array starts at begin, the length is len, it may include '\0' characters
  9523. // and may not be NUL-terminated.
  9524. template <typename CharType>
  9525. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  9526. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  9527. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  9528. static CharFormat PrintCharsAsStringTo(
  9529. const CharType* begin, size_t len, ostream* os) {
  9530. const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
  9531. *os << kQuoteBegin;
  9532. bool is_previous_hex = false;
  9533. CharFormat print_format = kAsIs;
  9534. for (size_t index = 0; index < len; ++index) {
  9535. const CharType cur = begin[index];
  9536. if (is_previous_hex && IsXDigit(cur)) {
  9537. // Previous character is of '\x..' form and this character can be
  9538. // interpreted as another hexadecimal digit in its number. Break string to
  9539. // disambiguate.
  9540. *os << "\" " << kQuoteBegin;
  9541. }
  9542. is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
  9543. // Remember if any characters required hex escaping.
  9544. if (is_previous_hex) {
  9545. print_format = kHexEscape;
  9546. }
  9547. }
  9548. *os << "\"";
  9549. return print_format;
  9550. }
  9551. // Prints a (const) char/wchar_t array of 'len' elements, starting at address
  9552. // 'begin'. CharType must be either char or wchar_t.
  9553. template <typename CharType>
  9554. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  9555. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  9556. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  9557. static void UniversalPrintCharArray(
  9558. const CharType* begin, size_t len, ostream* os) {
  9559. // The code
  9560. // const char kFoo[] = "foo";
  9561. // generates an array of 4, not 3, elements, with the last one being '\0'.
  9562. //
  9563. // Therefore when printing a char array, we don't print the last element if
  9564. // it's '\0', such that the output matches the string literal as it's
  9565. // written in the source code.
  9566. if (len > 0 && begin[len - 1] == '\0') {
  9567. PrintCharsAsStringTo(begin, len - 1, os);
  9568. return;
  9569. }
  9570. // If, however, the last element in the array is not '\0', e.g.
  9571. // const char kFoo[] = { 'f', 'o', 'o' };
  9572. // we must print the entire array. We also print a message to indicate
  9573. // that the array is not NUL-terminated.
  9574. PrintCharsAsStringTo(begin, len, os);
  9575. *os << " (no terminating NUL)";
  9576. }
  9577. // Prints a (const) char array of 'len' elements, starting at address 'begin'.
  9578. void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
  9579. UniversalPrintCharArray(begin, len, os);
  9580. }
  9581. // Prints a (const) wchar_t array of 'len' elements, starting at address
  9582. // 'begin'.
  9583. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
  9584. UniversalPrintCharArray(begin, len, os);
  9585. }
  9586. // Prints the given C string to the ostream.
  9587. void PrintTo(const char* s, ostream* os) {
  9588. if (s == NULL) {
  9589. *os << "NULL";
  9590. } else {
  9591. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  9592. PrintCharsAsStringTo(s, strlen(s), os);
  9593. }
  9594. }
  9595. // MSVC compiler can be configured to define whar_t as a typedef
  9596. // of unsigned short. Defining an overload for const wchar_t* in that case
  9597. // would cause pointers to unsigned shorts be printed as wide strings,
  9598. // possibly accessing more memory than intended and causing invalid
  9599. // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
  9600. // wchar_t is implemented as a native type.
  9601. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  9602. // Prints the given wide C string to the ostream.
  9603. void PrintTo(const wchar_t* s, ostream* os) {
  9604. if (s == NULL) {
  9605. *os << "NULL";
  9606. } else {
  9607. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  9608. PrintCharsAsStringTo(s, std::wcslen(s), os);
  9609. }
  9610. }
  9611. #endif // wchar_t is native
  9612. namespace {
  9613. bool ContainsUnprintableControlCodes(const char* str, size_t length) {
  9614. const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
  9615. for (size_t i = 0; i < length; i++) {
  9616. unsigned char ch = *s++;
  9617. if (std::iscntrl(ch)) {
  9618. switch (ch) {
  9619. case '\t':
  9620. case '\n':
  9621. case '\r':
  9622. break;
  9623. default:
  9624. return true;
  9625. }
  9626. }
  9627. }
  9628. return false;
  9629. }
  9630. bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
  9631. bool IsValidUTF8(const char* str, size_t length) {
  9632. const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
  9633. for (size_t i = 0; i < length;) {
  9634. unsigned char lead = s[i++];
  9635. if (lead <= 0x7f) {
  9636. continue; // single-byte character (ASCII) 0..7F
  9637. }
  9638. if (lead < 0xc2) {
  9639. return false; // trail byte or non-shortest form
  9640. } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
  9641. ++i; // 2-byte character
  9642. } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
  9643. IsUTF8TrailByte(s[i]) &&
  9644. IsUTF8TrailByte(s[i + 1]) &&
  9645. // check for non-shortest form and surrogate
  9646. (lead != 0xe0 || s[i] >= 0xa0) &&
  9647. (lead != 0xed || s[i] < 0xa0)) {
  9648. i += 2; // 3-byte character
  9649. } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
  9650. IsUTF8TrailByte(s[i]) &&
  9651. IsUTF8TrailByte(s[i + 1]) &&
  9652. IsUTF8TrailByte(s[i + 2]) &&
  9653. // check for non-shortest form
  9654. (lead != 0xf0 || s[i] >= 0x90) &&
  9655. (lead != 0xf4 || s[i] < 0x90)) {
  9656. i += 3; // 4-byte character
  9657. } else {
  9658. return false;
  9659. }
  9660. }
  9661. return true;
  9662. }
  9663. void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
  9664. if (!ContainsUnprintableControlCodes(str, length) &&
  9665. IsValidUTF8(str, length)) {
  9666. *os << "\n As Text: \"" << str << "\"";
  9667. }
  9668. }
  9669. } // anonymous namespace
  9670. // Prints a ::string object.
  9671. #if GTEST_HAS_GLOBAL_STRING
  9672. void PrintStringTo(const ::string& s, ostream* os) {
  9673. if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
  9674. if (GTEST_FLAG(print_utf8)) {
  9675. ConditionalPrintAsText(s.data(), s.size(), os);
  9676. }
  9677. }
  9678. }
  9679. #endif // GTEST_HAS_GLOBAL_STRING
  9680. void PrintStringTo(const ::std::string& s, ostream* os) {
  9681. if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
  9682. if (GTEST_FLAG(print_utf8)) {
  9683. ConditionalPrintAsText(s.data(), s.size(), os);
  9684. }
  9685. }
  9686. }
  9687. // Prints a ::wstring object.
  9688. #if GTEST_HAS_GLOBAL_WSTRING
  9689. void PrintWideStringTo(const ::wstring& s, ostream* os) {
  9690. PrintCharsAsStringTo(s.data(), s.size(), os);
  9691. }
  9692. #endif // GTEST_HAS_GLOBAL_WSTRING
  9693. #if GTEST_HAS_STD_WSTRING
  9694. void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
  9695. PrintCharsAsStringTo(s.data(), s.size(), os);
  9696. }
  9697. #endif // GTEST_HAS_STD_WSTRING
  9698. } // namespace internal
  9699. } // namespace testing
  9700. // Copyright 2008, Google Inc.
  9701. // All rights reserved.
  9702. //
  9703. // Redistribution and use in source and binary forms, with or without
  9704. // modification, are permitted provided that the following conditions are
  9705. // met:
  9706. //
  9707. // * Redistributions of source code must retain the above copyright
  9708. // notice, this list of conditions and the following disclaimer.
  9709. // * Redistributions in binary form must reproduce the above
  9710. // copyright notice, this list of conditions and the following disclaimer
  9711. // in the documentation and/or other materials provided with the
  9712. // distribution.
  9713. // * Neither the name of Google Inc. nor the names of its
  9714. // contributors may be used to endorse or promote products derived from
  9715. // this software without specific prior written permission.
  9716. //
  9717. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  9718. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  9719. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  9720. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9721. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  9722. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9723. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  9724. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9725. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  9726. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  9727. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9728. //
  9729. // The Google C++ Testing and Mocking Framework (Google Test)
  9730. namespace testing {
  9731. using internal::GetUnitTestImpl;
  9732. // Gets the summary of the failure message by omitting the stack trace
  9733. // in it.
  9734. std::string TestPartResult::ExtractSummary(const char* message) {
  9735. const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
  9736. return stack_trace == NULL ? message :
  9737. std::string(message, stack_trace);
  9738. }
  9739. // Prints a TestPartResult object.
  9740. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
  9741. return os
  9742. << result.file_name() << ":" << result.line_number() << ": "
  9743. << (result.type() == TestPartResult::kSuccess ? "Success" :
  9744. result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
  9745. "Non-fatal failure") << ":\n"
  9746. << result.message() << std::endl;
  9747. }
  9748. // Appends a TestPartResult to the array.
  9749. void TestPartResultArray::Append(const TestPartResult& result) {
  9750. array_.push_back(result);
  9751. }
  9752. // Returns the TestPartResult at the given index (0-based).
  9753. const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
  9754. if (index < 0 || index >= size()) {
  9755. printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
  9756. internal::posix::Abort();
  9757. }
  9758. return array_[index];
  9759. }
  9760. // Returns the number of TestPartResult objects in the array.
  9761. int TestPartResultArray::size() const {
  9762. return static_cast<int>(array_.size());
  9763. }
  9764. namespace internal {
  9765. HasNewFatalFailureHelper::HasNewFatalFailureHelper()
  9766. : has_new_fatal_failure_(false),
  9767. original_reporter_(GetUnitTestImpl()->
  9768. GetTestPartResultReporterForCurrentThread()) {
  9769. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
  9770. }
  9771. HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
  9772. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
  9773. original_reporter_);
  9774. }
  9775. void HasNewFatalFailureHelper::ReportTestPartResult(
  9776. const TestPartResult& result) {
  9777. if (result.fatally_failed())
  9778. has_new_fatal_failure_ = true;
  9779. original_reporter_->ReportTestPartResult(result);
  9780. }
  9781. } // namespace internal
  9782. } // namespace testing
  9783. // Copyright 2008 Google Inc.
  9784. // All Rights Reserved.
  9785. //
  9786. // Redistribution and use in source and binary forms, with or without
  9787. // modification, are permitted provided that the following conditions are
  9788. // met:
  9789. //
  9790. // * Redistributions of source code must retain the above copyright
  9791. // notice, this list of conditions and the following disclaimer.
  9792. // * Redistributions in binary form must reproduce the above
  9793. // copyright notice, this list of conditions and the following disclaimer
  9794. // in the documentation and/or other materials provided with the
  9795. // distribution.
  9796. // * Neither the name of Google Inc. nor the names of its
  9797. // contributors may be used to endorse or promote products derived from
  9798. // this software without specific prior written permission.
  9799. //
  9800. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  9801. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  9802. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  9803. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9804. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  9805. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9806. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  9807. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9808. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  9809. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  9810. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9811. namespace testing {
  9812. namespace internal {
  9813. #if GTEST_HAS_TYPED_TEST_P
  9814. // Skips to the first non-space char in str. Returns an empty string if str
  9815. // contains only whitespace characters.
  9816. static const char* SkipSpaces(const char* str) {
  9817. while (IsSpace(*str))
  9818. str++;
  9819. return str;
  9820. }
  9821. static std::vector<std::string> SplitIntoTestNames(const char* src) {
  9822. std::vector<std::string> name_vec;
  9823. src = SkipSpaces(src);
  9824. for (; src != NULL; src = SkipComma(src)) {
  9825. name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
  9826. }
  9827. return name_vec;
  9828. }
  9829. // Verifies that registered_tests match the test names in
  9830. // registered_tests_; returns registered_tests if successful, or
  9831. // aborts the program otherwise.
  9832. const char* TypedTestCasePState::VerifyRegisteredTestNames(
  9833. const char* file, int line, const char* registered_tests) {
  9834. typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
  9835. registered_ = true;
  9836. std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
  9837. Message errors;
  9838. std::set<std::string> tests;
  9839. for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
  9840. name_it != name_vec.end(); ++name_it) {
  9841. const std::string& name = *name_it;
  9842. if (tests.count(name) != 0) {
  9843. errors << "Test " << name << " is listed more than once.\n";
  9844. continue;
  9845. }
  9846. bool found = false;
  9847. for (RegisteredTestIter it = registered_tests_.begin();
  9848. it != registered_tests_.end();
  9849. ++it) {
  9850. if (name == it->first) {
  9851. found = true;
  9852. break;
  9853. }
  9854. }
  9855. if (found) {
  9856. tests.insert(name);
  9857. } else {
  9858. errors << "No test named " << name
  9859. << " can be found in this test case.\n";
  9860. }
  9861. }
  9862. for (RegisteredTestIter it = registered_tests_.begin();
  9863. it != registered_tests_.end();
  9864. ++it) {
  9865. if (tests.count(it->first) == 0) {
  9866. errors << "You forgot to list test " << it->first << ".\n";
  9867. }
  9868. }
  9869. const std::string& errors_str = errors.GetString();
  9870. if (errors_str != "") {
  9871. fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
  9872. errors_str.c_str());
  9873. fflush(stderr);
  9874. posix::Abort();
  9875. }
  9876. return registered_tests;
  9877. }
  9878. #endif // GTEST_HAS_TYPED_TEST_P
  9879. } // namespace internal
  9880. } // namespace testing