gtest.cc 213 KB

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