gtest-all.cc 329 KB

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