gtest.h 463 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377
  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. //
  32. // This header file defines the public API for Google Test. It should be
  33. // included by any test program that uses Google Test.
  34. //
  35. // IMPORTANT NOTE: Due to limitation of the C++ language, we have to
  36. // leave some internal implementation details in this header file.
  37. // They are clearly marked by comments like this:
  38. //
  39. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  40. //
  41. // Such code is NOT meant to be used by a user directly, and is subject
  42. // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
  43. // program!
  44. //
  45. // Acknowledgment: Google Test borrowed the idea of automatic test
  46. // registration from Barthelemy Dagenais' (barthelemy@prologique.com)
  47. // easyUnit framework.
  48. // GOOGLETEST_CM0001 DO NOT DELETE
  49. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_H_
  50. #define GOOGLETEST_INCLUDE_GTEST_GTEST_H_
  51. #include <cstddef>
  52. #include <limits>
  53. #include <memory>
  54. #include <ostream>
  55. #include <type_traits>
  56. #include <vector>
  57. // Copyright 2005, Google Inc.
  58. // All rights reserved.
  59. //
  60. // Redistribution and use in source and binary forms, with or without
  61. // modification, are permitted provided that the following conditions are
  62. // met:
  63. //
  64. // * Redistributions of source code must retain the above copyright
  65. // notice, this list of conditions and the following disclaimer.
  66. // * Redistributions in binary form must reproduce the above
  67. // copyright notice, this list of conditions and the following disclaimer
  68. // in the documentation and/or other materials provided with the
  69. // distribution.
  70. // * Neither the name of Google Inc. nor the names of its
  71. // contributors may be used to endorse or promote products derived from
  72. // this software without specific prior written permission.
  73. //
  74. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  75. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  76. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  77. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  78. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  79. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  80. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  81. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  82. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  83. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  84. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  85. //
  86. // The Google C++ Testing and Mocking Framework (Google Test)
  87. //
  88. // This header file declares functions and macros used internally by
  89. // Google Test. They are subject to change without notice.
  90. // GOOGLETEST_CM0001 DO NOT DELETE
  91. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
  92. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
  93. // Copyright 2005, Google Inc.
  94. // All rights reserved.
  95. //
  96. // Redistribution and use in source and binary forms, with or without
  97. // modification, are permitted provided that the following conditions are
  98. // met:
  99. //
  100. // * Redistributions of source code must retain the above copyright
  101. // notice, this list of conditions and the following disclaimer.
  102. // * Redistributions in binary form must reproduce the above
  103. // copyright notice, this list of conditions and the following disclaimer
  104. // in the documentation and/or other materials provided with the
  105. // distribution.
  106. // * Neither the name of Google Inc. nor the names of its
  107. // contributors may be used to endorse or promote products derived from
  108. // this software without specific prior written permission.
  109. //
  110. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  111. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  112. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  113. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  114. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  115. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  116. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  117. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  118. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  119. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  120. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  121. //
  122. // Low-level types and utilities for porting Google Test to various
  123. // platforms. All macros ending with _ and symbols defined in an
  124. // internal namespace are subject to change without notice. Code
  125. // outside Google Test MUST NOT USE THEM DIRECTLY. Macros that don't
  126. // end with _ are part of Google Test's public API and can be used by
  127. // code outside Google Test.
  128. //
  129. // This file is fundamental to Google Test. All other Google Test source
  130. // files are expected to #include this. Therefore, it cannot #include
  131. // any other Google Test header.
  132. // GOOGLETEST_CM0001 DO NOT DELETE
  133. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
  134. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
  135. // Environment-describing macros
  136. // -----------------------------
  137. //
  138. // Google Test can be used in many different environments. Macros in
  139. // this section tell Google Test what kind of environment it is being
  140. // used in, such that Google Test can provide environment-specific
  141. // features and implementations.
  142. //
  143. // Google Test tries to automatically detect the properties of its
  144. // environment, so users usually don't need to worry about these
  145. // macros. However, the automatic detection is not perfect.
  146. // Sometimes it's necessary for a user to define some of the following
  147. // macros in the build script to override Google Test's decisions.
  148. //
  149. // If the user doesn't define a macro in the list, Google Test will
  150. // provide a default definition. After this header is #included, all
  151. // macros in this list will be defined to either 1 or 0.
  152. //
  153. // Notes to maintainers:
  154. // - Each macro here is a user-tweakable knob; do not grow the list
  155. // lightly.
  156. // - Use #if to key off these macros. Don't use #ifdef or "#if
  157. // defined(...)", which will not work as these macros are ALWAYS
  158. // defined.
  159. //
  160. // GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2)
  161. // is/isn't available.
  162. // GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions
  163. // are enabled.
  164. // GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular
  165. // expressions are/aren't available.
  166. // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h>
  167. // is/isn't available.
  168. // GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't
  169. // enabled.
  170. // GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that
  171. // std::wstring does/doesn't work (Google Test can
  172. // be used where std::wstring is unavailable).
  173. // GTEST_HAS_SEH - Define it to 1/0 to indicate whether the
  174. // compiler supports Microsoft's "Structured
  175. // Exception Handling".
  176. // GTEST_HAS_STREAM_REDIRECTION
  177. // - Define it to 1/0 to indicate whether the
  178. // platform supports I/O stream redirection using
  179. // dup() and dup2().
  180. // GTEST_LINKED_AS_SHARED_LIBRARY
  181. // - Define to 1 when compiling tests that use
  182. // Google Test as a shared library (known as
  183. // DLL on Windows).
  184. // GTEST_CREATE_SHARED_LIBRARY
  185. // - Define to 1 when compiling Google Test itself
  186. // as a shared library.
  187. // GTEST_DEFAULT_DEATH_TEST_STYLE
  188. // - The default value of --gtest_death_test_style.
  189. // The legacy default has been "fast" in the open
  190. // source version since 2008. The recommended value
  191. // is "threadsafe", and can be set in
  192. // custom/gtest-port.h.
  193. // Platform-indicating macros
  194. // --------------------------
  195. //
  196. // Macros indicating the platform on which Google Test is being used
  197. // (a macro is defined to 1 if compiled on the given platform;
  198. // otherwise UNDEFINED -- it's never defined to 0.). Google Test
  199. // defines these macros automatically. Code outside Google Test MUST
  200. // NOT define them.
  201. //
  202. // GTEST_OS_AIX - IBM AIX
  203. // GTEST_OS_CYGWIN - Cygwin
  204. // GTEST_OS_DRAGONFLY - DragonFlyBSD
  205. // GTEST_OS_FREEBSD - FreeBSD
  206. // GTEST_OS_FUCHSIA - Fuchsia
  207. // GTEST_OS_GNU_KFREEBSD - GNU/kFreeBSD
  208. // GTEST_OS_HAIKU - Haiku
  209. // GTEST_OS_HPUX - HP-UX
  210. // GTEST_OS_LINUX - Linux
  211. // GTEST_OS_LINUX_ANDROID - Google Android
  212. // GTEST_OS_MAC - Mac OS X
  213. // GTEST_OS_IOS - iOS
  214. // GTEST_OS_NACL - Google Native Client (NaCl)
  215. // GTEST_OS_NETBSD - NetBSD
  216. // GTEST_OS_OPENBSD - OpenBSD
  217. // GTEST_OS_OS2 - OS/2
  218. // GTEST_OS_QNX - QNX
  219. // GTEST_OS_SOLARIS - Sun Solaris
  220. // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile)
  221. // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop
  222. // GTEST_OS_WINDOWS_MINGW - MinGW
  223. // GTEST_OS_WINDOWS_MOBILE - Windows Mobile
  224. // GTEST_OS_WINDOWS_PHONE - Windows Phone
  225. // GTEST_OS_WINDOWS_RT - Windows Store App/WinRT
  226. // GTEST_OS_ZOS - z/OS
  227. //
  228. // Among the platforms, Cygwin, Linux, Mac OS X, and Windows have the
  229. // most stable support. Since core members of the Google Test project
  230. // don't have access to other platforms, support for them may be less
  231. // stable. If you notice any problems on your platform, please notify
  232. // googletestframework@googlegroups.com (patches for fixing them are
  233. // even more welcome!).
  234. //
  235. // It is possible that none of the GTEST_OS_* macros are defined.
  236. // Feature-indicating macros
  237. // -------------------------
  238. //
  239. // Macros indicating which Google Test features are available (a macro
  240. // is defined to 1 if the corresponding feature is supported;
  241. // otherwise UNDEFINED -- it's never defined to 0.). Google Test
  242. // defines these macros automatically. Code outside Google Test MUST
  243. // NOT define them.
  244. //
  245. // These macros are public so that portable tests can be written.
  246. // Such tests typically surround code using a feature with an #if
  247. // which controls that code. For example:
  248. //
  249. // #if GTEST_HAS_DEATH_TEST
  250. // EXPECT_DEATH(DoSomethingDeadly());
  251. // #endif
  252. //
  253. // GTEST_HAS_DEATH_TEST - death tests
  254. // GTEST_HAS_TYPED_TEST - typed tests
  255. // GTEST_HAS_TYPED_TEST_P - type-parameterized tests
  256. // GTEST_IS_THREADSAFE - Google Test is thread-safe.
  257. // GOOGLETEST_CM0007 DO NOT DELETE
  258. // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with
  259. // GTEST_HAS_POSIX_RE (see above) which users can
  260. // define themselves.
  261. // GTEST_USES_SIMPLE_RE - our own simple regex is used;
  262. // the above RE\b(s) are mutually exclusive.
  263. // Misc public macros
  264. // ------------------
  265. //
  266. // GTEST_FLAG(flag_name) - references the variable corresponding to
  267. // the given Google Test flag.
  268. // Internal utilities
  269. // ------------------
  270. //
  271. // The following macros and utilities are for Google Test's INTERNAL
  272. // use only. Code outside Google Test MUST NOT USE THEM DIRECTLY.
  273. //
  274. // Macros for basic C++ coding:
  275. // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
  276. // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a
  277. // variable don't have to be used.
  278. // GTEST_DISALLOW_ASSIGN_ - disables copy operator=.
  279. // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
  280. // GTEST_DISALLOW_MOVE_ASSIGN_ - disables move operator=.
  281. // GTEST_DISALLOW_MOVE_AND_ASSIGN_ - disables move ctor and operator=.
  282. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used.
  283. // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is
  284. // suppressed (constant conditional).
  285. // GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127
  286. // is suppressed.
  287. // GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter<std::any> or
  288. // UniversalPrinter<absl::any> specializations.
  289. // GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional>
  290. // or
  291. // UniversalPrinter<absl::optional>
  292. // specializations.
  293. // GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or
  294. // Matcher<absl::string_view>
  295. // specializations.
  296. // GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter<std::variant> or
  297. // UniversalPrinter<absl::variant>
  298. // specializations.
  299. //
  300. // Synchronization:
  301. // Mutex, MutexLock, ThreadLocal, GetThreadCount()
  302. // - synchronization primitives.
  303. //
  304. // Regular expressions:
  305. // RE - a simple regular expression class using the POSIX
  306. // Extended Regular Expression syntax on UNIX-like platforms
  307. // GOOGLETEST_CM0008 DO NOT DELETE
  308. // or a reduced regular exception syntax on other
  309. // platforms, including Windows.
  310. // Logging:
  311. // GTEST_LOG_() - logs messages at the specified severity level.
  312. // LogToStderr() - directs all log messages to stderr.
  313. // FlushInfoLog() - flushes informational log messages.
  314. //
  315. // Stdout and stderr capturing:
  316. // CaptureStdout() - starts capturing stdout.
  317. // GetCapturedStdout() - stops capturing stdout and returns the captured
  318. // string.
  319. // CaptureStderr() - starts capturing stderr.
  320. // GetCapturedStderr() - stops capturing stderr and returns the captured
  321. // string.
  322. //
  323. // Integer types:
  324. // TypeWithSize - maps an integer to a int type.
  325. // TimeInMillis - integers of known sizes.
  326. // BiggestInt - the biggest signed integer type.
  327. //
  328. // Command-line utilities:
  329. // GTEST_DECLARE_*() - declares a flag.
  330. // GTEST_DEFINE_*() - defines a flag.
  331. // GetInjectableArgvs() - returns the command line as a vector of strings.
  332. //
  333. // Environment variable utilities:
  334. // GetEnv() - gets the value of an environment variable.
  335. // BoolFromGTestEnv() - parses a bool environment variable.
  336. // Int32FromGTestEnv() - parses an int32_t environment variable.
  337. // StringFromGTestEnv() - parses a string environment variable.
  338. //
  339. // Deprecation warnings:
  340. // GTEST_INTERNAL_DEPRECATED(message) - attribute marking a function as
  341. // deprecated; calling a marked function
  342. // should generate a compiler warning
  343. #include <ctype.h> // for isspace, etc
  344. #include <stddef.h> // for ptrdiff_t
  345. #include <stdio.h>
  346. #include <stdlib.h>
  347. #include <string.h>
  348. #include <cerrno>
  349. #include <cstdint>
  350. #include <limits>
  351. #include <type_traits>
  352. #ifndef _WIN32_WCE
  353. # include <sys/types.h>
  354. # include <sys/stat.h>
  355. #endif // !_WIN32_WCE
  356. #if defined __APPLE__
  357. # include <AvailabilityMacros.h>
  358. # include <TargetConditionals.h>
  359. #endif
  360. #include <iostream> // NOLINT
  361. #include <locale>
  362. #include <memory>
  363. #include <string> // NOLINT
  364. #include <tuple>
  365. #include <vector> // NOLINT
  366. // Copyright 2015, Google Inc.
  367. // All rights reserved.
  368. //
  369. // Redistribution and use in source and binary forms, with or without
  370. // modification, are permitted provided that the following conditions are
  371. // met:
  372. //
  373. // * Redistributions of source code must retain the above copyright
  374. // notice, this list of conditions and the following disclaimer.
  375. // * Redistributions in binary form must reproduce the above
  376. // copyright notice, this list of conditions and the following disclaimer
  377. // in the documentation and/or other materials provided with the
  378. // distribution.
  379. // * Neither the name of Google Inc. nor the names of its
  380. // contributors may be used to endorse or promote products derived from
  381. // this software without specific prior written permission.
  382. //
  383. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  384. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  385. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  386. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  387. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  388. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  389. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  390. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  391. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  392. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  393. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  394. //
  395. // Injection point for custom user configurations. See README for details
  396. //
  397. // ** Custom implementation starts here **
  398. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
  399. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
  400. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
  401. // Copyright 2015, Google Inc.
  402. // All rights reserved.
  403. //
  404. // Redistribution and use in source and binary forms, with or without
  405. // modification, are permitted provided that the following conditions are
  406. // met:
  407. //
  408. // * Redistributions of source code must retain the above copyright
  409. // notice, this list of conditions and the following disclaimer.
  410. // * Redistributions in binary form must reproduce the above
  411. // copyright notice, this list of conditions and the following disclaimer
  412. // in the documentation and/or other materials provided with the
  413. // distribution.
  414. // * Neither the name of Google Inc. nor the names of its
  415. // contributors may be used to endorse or promote products derived from
  416. // this software without specific prior written permission.
  417. //
  418. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  419. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  420. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  421. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  422. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  423. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  424. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  425. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  426. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  427. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  428. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  429. //
  430. // The Google C++ Testing and Mocking Framework (Google Test)
  431. //
  432. // This header file defines the GTEST_OS_* macro.
  433. // It is separate from gtest-port.h so that custom/gtest-port.h can include it.
  434. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
  435. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
  436. // Determines the platform on which Google Test is compiled.
  437. #ifdef __CYGWIN__
  438. # define GTEST_OS_CYGWIN 1
  439. # elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)
  440. # define GTEST_OS_WINDOWS_MINGW 1
  441. # define GTEST_OS_WINDOWS 1
  442. #elif defined _WIN32
  443. # define GTEST_OS_WINDOWS 1
  444. # ifdef _WIN32_WCE
  445. # define GTEST_OS_WINDOWS_MOBILE 1
  446. # elif defined(WINAPI_FAMILY)
  447. # include <winapifamily.h>
  448. # if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
  449. # define GTEST_OS_WINDOWS_DESKTOP 1
  450. # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
  451. # define GTEST_OS_WINDOWS_PHONE 1
  452. # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
  453. # define GTEST_OS_WINDOWS_RT 1
  454. # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
  455. # define GTEST_OS_WINDOWS_PHONE 1
  456. # define GTEST_OS_WINDOWS_TV_TITLE 1
  457. # else
  458. // WINAPI_FAMILY defined but no known partition matched.
  459. // Default to desktop.
  460. # define GTEST_OS_WINDOWS_DESKTOP 1
  461. # endif
  462. # else
  463. # define GTEST_OS_WINDOWS_DESKTOP 1
  464. # endif // _WIN32_WCE
  465. #elif defined __OS2__
  466. # define GTEST_OS_OS2 1
  467. #elif defined __APPLE__
  468. # define GTEST_OS_MAC 1
  469. # include <TargetConditionals.h>
  470. # if TARGET_OS_IPHONE
  471. # define GTEST_OS_IOS 1
  472. # endif
  473. #elif defined __DragonFly__
  474. # define GTEST_OS_DRAGONFLY 1
  475. #elif defined __FreeBSD__
  476. # define GTEST_OS_FREEBSD 1
  477. #elif defined __Fuchsia__
  478. # define GTEST_OS_FUCHSIA 1
  479. #elif defined(__GLIBC__) && defined(__FreeBSD_kernel__)
  480. # define GTEST_OS_GNU_KFREEBSD 1
  481. #elif defined __linux__
  482. # define GTEST_OS_LINUX 1
  483. # if defined __ANDROID__
  484. # define GTEST_OS_LINUX_ANDROID 1
  485. # endif
  486. #elif defined __MVS__
  487. # define GTEST_OS_ZOS 1
  488. #elif defined(__sun) && defined(__SVR4)
  489. # define GTEST_OS_SOLARIS 1
  490. #elif defined(_AIX)
  491. # define GTEST_OS_AIX 1
  492. #elif defined(__hpux)
  493. # define GTEST_OS_HPUX 1
  494. #elif defined __native_client__
  495. # define GTEST_OS_NACL 1
  496. #elif defined __NetBSD__
  497. # define GTEST_OS_NETBSD 1
  498. #elif defined __OpenBSD__
  499. # define GTEST_OS_OPENBSD 1
  500. #elif defined __QNX__
  501. # define GTEST_OS_QNX 1
  502. #elif defined(__HAIKU__)
  503. #define GTEST_OS_HAIKU 1
  504. #elif defined ESP8266
  505. #define GTEST_OS_ESP8266 1
  506. #elif defined ESP32
  507. #define GTEST_OS_ESP32 1
  508. #elif defined(__XTENSA__)
  509. #define GTEST_OS_XTENSA 1
  510. #endif // __CYGWIN__
  511. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
  512. #if !defined(GTEST_DEV_EMAIL_)
  513. # define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
  514. # define GTEST_FLAG_PREFIX_ "gtest_"
  515. # define GTEST_FLAG_PREFIX_DASH_ "gtest-"
  516. # define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
  517. # define GTEST_NAME_ "Google Test"
  518. # define GTEST_PROJECT_URL_ "https://github.com/google/googletest/"
  519. #endif // !defined(GTEST_DEV_EMAIL_)
  520. #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
  521. # define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest"
  522. #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
  523. // Determines the version of gcc that is used to compile this.
  524. #ifdef __GNUC__
  525. // 40302 means version 4.3.2.
  526. # define GTEST_GCC_VER_ \
  527. (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
  528. #endif // __GNUC__
  529. // Macros for disabling Microsoft Visual C++ warnings.
  530. //
  531. // GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385)
  532. // /* code that triggers warnings C4800 and C4385 */
  533. // GTEST_DISABLE_MSC_WARNINGS_POP_()
  534. #if defined(_MSC_VER)
  535. # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
  536. __pragma(warning(push)) \
  537. __pragma(warning(disable: warnings))
  538. # define GTEST_DISABLE_MSC_WARNINGS_POP_() \
  539. __pragma(warning(pop))
  540. #else
  541. // Not all compilers are MSVC
  542. # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
  543. # define GTEST_DISABLE_MSC_WARNINGS_POP_()
  544. #endif
  545. // Clang on Windows does not understand MSVC's pragma warning.
  546. // We need clang-specific way to disable function deprecation warning.
  547. #ifdef __clang__
  548. # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
  549. _Pragma("clang diagnostic push") \
  550. _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \
  551. _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"")
  552. #define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
  553. _Pragma("clang diagnostic pop")
  554. #else
  555. # define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
  556. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
  557. # define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
  558. GTEST_DISABLE_MSC_WARNINGS_POP_()
  559. #endif
  560. // Brings in definitions for functions used in the testing::internal::posix
  561. // namespace (read, write, close, chdir, isatty, stat). We do not currently
  562. // use them on Windows Mobile.
  563. #if GTEST_OS_WINDOWS
  564. # if !GTEST_OS_WINDOWS_MOBILE
  565. # include <direct.h>
  566. # include <io.h>
  567. # endif
  568. // In order to avoid having to include <windows.h>, use forward declaration
  569. #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
  570. // MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two
  571. // separate (equivalent) structs, instead of using typedef
  572. typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION;
  573. #else
  574. // Assume CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION.
  575. // This assumption is verified by
  576. // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
  577. typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
  578. #endif
  579. #elif GTEST_OS_XTENSA
  580. #include <unistd.h>
  581. // Xtensa toolchains define strcasecmp in the string.h header instead of
  582. // strings.h. string.h is already included.
  583. #else
  584. // This assumes that non-Windows OSes provide unistd.h. For OSes where this
  585. // is not the case, we need to include headers that provide the functions
  586. // mentioned above.
  587. # include <unistd.h>
  588. # include <strings.h>
  589. #endif // GTEST_OS_WINDOWS
  590. #if GTEST_OS_LINUX_ANDROID
  591. // Used to define __ANDROID_API__ matching the target NDK API level.
  592. # include <android/api-level.h> // NOLINT
  593. #endif
  594. // Defines this to true if and only if Google Test can use POSIX regular
  595. // expressions.
  596. #ifndef GTEST_HAS_POSIX_RE
  597. # if GTEST_OS_LINUX_ANDROID
  598. // On Android, <regex.h> is only available starting with Gingerbread.
  599. # define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
  600. # else
  601. #define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS && !GTEST_OS_XTENSA)
  602. # endif
  603. #endif
  604. #if GTEST_USES_PCRE
  605. // The appropriate headers have already been included.
  606. #elif GTEST_HAS_POSIX_RE
  607. // On some platforms, <regex.h> needs someone to define size_t, and
  608. // won't compile otherwise. We can #include it here as we already
  609. // included <stdlib.h>, which is guaranteed to define size_t through
  610. // <stddef.h>.
  611. # include <regex.h> // NOLINT
  612. # define GTEST_USES_POSIX_RE 1
  613. #elif GTEST_OS_WINDOWS
  614. // <regex.h> is not available on Windows. Use our own simple regex
  615. // implementation instead.
  616. # define GTEST_USES_SIMPLE_RE 1
  617. #else
  618. // <regex.h> may not be available on this platform. Use our own
  619. // simple regex implementation instead.
  620. # define GTEST_USES_SIMPLE_RE 1
  621. #endif // GTEST_USES_PCRE
  622. #ifndef GTEST_HAS_EXCEPTIONS
  623. // The user didn't tell us whether exceptions are enabled, so we need
  624. // to figure it out.
  625. # if defined(_MSC_VER) && defined(_CPPUNWIND)
  626. // MSVC defines _CPPUNWIND to 1 if and only if exceptions are enabled.
  627. # define GTEST_HAS_EXCEPTIONS 1
  628. # elif defined(__BORLANDC__)
  629. // C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS
  630. // macro to enable exceptions, so we'll do the same.
  631. // Assumes that exceptions are enabled by default.
  632. # ifndef _HAS_EXCEPTIONS
  633. # define _HAS_EXCEPTIONS 1
  634. # endif // _HAS_EXCEPTIONS
  635. # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
  636. # elif defined(__clang__)
  637. // clang defines __EXCEPTIONS if and only if exceptions are enabled before clang
  638. // 220714, but if and only if cleanups are enabled after that. In Obj-C++ files,
  639. // there can be cleanups for ObjC exceptions which also need cleanups, even if
  640. // C++ exceptions are disabled. clang has __has_feature(cxx_exceptions) which
  641. // checks for C++ exceptions starting at clang r206352, but which checked for
  642. // cleanups prior to that. To reliably check for C++ exception availability with
  643. // clang, check for
  644. // __EXCEPTIONS && __has_feature(cxx_exceptions).
  645. # define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
  646. # elif defined(__GNUC__) && __EXCEPTIONS
  647. // gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
  648. # define GTEST_HAS_EXCEPTIONS 1
  649. # elif defined(__SUNPRO_CC)
  650. // Sun Pro CC supports exceptions. However, there is no compile-time way of
  651. // detecting whether they are enabled or not. Therefore, we assume that
  652. // they are enabled unless the user tells us otherwise.
  653. # define GTEST_HAS_EXCEPTIONS 1
  654. # elif defined(__IBMCPP__) && __EXCEPTIONS
  655. // xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
  656. # define GTEST_HAS_EXCEPTIONS 1
  657. # elif defined(__HP_aCC)
  658. // Exception handling is in effect by default in HP aCC compiler. It has to
  659. // be turned of by +noeh compiler option if desired.
  660. # define GTEST_HAS_EXCEPTIONS 1
  661. # else
  662. // For other compilers, we assume exceptions are disabled to be
  663. // conservative.
  664. # define GTEST_HAS_EXCEPTIONS 0
  665. # endif // defined(_MSC_VER) || defined(__BORLANDC__)
  666. #endif // GTEST_HAS_EXCEPTIONS
  667. #ifndef GTEST_HAS_STD_WSTRING
  668. // The user didn't tell us whether ::std::wstring is available, so we need
  669. // to figure it out.
  670. // Cygwin 1.7 and below doesn't support ::std::wstring.
  671. // Solaris' libc++ doesn't support it either. Android has
  672. // no support for it at least as recent as Froyo (2.2).
  673. #define GTEST_HAS_STD_WSTRING \
  674. (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
  675. GTEST_OS_HAIKU || GTEST_OS_ESP32 || GTEST_OS_ESP8266 || GTEST_OS_XTENSA))
  676. #endif // GTEST_HAS_STD_WSTRING
  677. // Determines whether RTTI is available.
  678. #ifndef GTEST_HAS_RTTI
  679. // The user didn't tell us whether RTTI is enabled, so we need to
  680. // figure it out.
  681. # ifdef _MSC_VER
  682. #ifdef _CPPRTTI // MSVC defines this macro if and only if RTTI is enabled.
  683. # define GTEST_HAS_RTTI 1
  684. # else
  685. # define GTEST_HAS_RTTI 0
  686. # endif
  687. // Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is
  688. // enabled.
  689. # elif defined(__GNUC__)
  690. # ifdef __GXX_RTTI
  691. // When building against STLport with the Android NDK and with
  692. // -frtti -fno-exceptions, the build fails at link time with undefined
  693. // references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
  694. // so disable RTTI when detected.
  695. # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
  696. !defined(__EXCEPTIONS)
  697. # define GTEST_HAS_RTTI 0
  698. # else
  699. # define GTEST_HAS_RTTI 1
  700. # endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
  701. # else
  702. # define GTEST_HAS_RTTI 0
  703. # endif // __GXX_RTTI
  704. // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends
  705. // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the
  706. // first version with C++ support.
  707. # elif defined(__clang__)
  708. # define GTEST_HAS_RTTI __has_feature(cxx_rtti)
  709. // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
  710. // both the typeid and dynamic_cast features are present.
  711. # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
  712. # ifdef __RTTI_ALL__
  713. # define GTEST_HAS_RTTI 1
  714. # else
  715. # define GTEST_HAS_RTTI 0
  716. # endif
  717. # else
  718. // For all other compilers, we assume RTTI is enabled.
  719. # define GTEST_HAS_RTTI 1
  720. # endif // _MSC_VER
  721. #endif // GTEST_HAS_RTTI
  722. // It's this header's responsibility to #include <typeinfo> when RTTI
  723. // is enabled.
  724. #if GTEST_HAS_RTTI
  725. # include <typeinfo>
  726. #endif
  727. // Determines whether Google Test can use the pthreads library.
  728. #ifndef GTEST_HAS_PTHREAD
  729. // The user didn't tell us explicitly, so we make reasonable assumptions about
  730. // which platforms have pthreads support.
  731. //
  732. // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
  733. // to your compiler flags.
  734. #define GTEST_HAS_PTHREAD \
  735. (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \
  736. GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
  737. GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD || \
  738. GTEST_OS_HAIKU)
  739. #endif // GTEST_HAS_PTHREAD
  740. #if GTEST_HAS_PTHREAD
  741. // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
  742. // true.
  743. # include <pthread.h> // NOLINT
  744. // For timespec and nanosleep, used below.
  745. # include <time.h> // NOLINT
  746. #endif
  747. // Determines whether clone(2) is supported.
  748. // Usually it will only be available on Linux, excluding
  749. // Linux on the Itanium architecture.
  750. // Also see http://linux.die.net/man/2/clone.
  751. #ifndef GTEST_HAS_CLONE
  752. // The user didn't tell us, so we need to figure it out.
  753. # if GTEST_OS_LINUX && !defined(__ia64__)
  754. # if GTEST_OS_LINUX_ANDROID
  755. // On Android, clone() became available at different API levels for each 32-bit
  756. // architecture.
  757. # if defined(__LP64__) || \
  758. (defined(__arm__) && __ANDROID_API__ >= 9) || \
  759. (defined(__mips__) && __ANDROID_API__ >= 12) || \
  760. (defined(__i386__) && __ANDROID_API__ >= 17)
  761. # define GTEST_HAS_CLONE 1
  762. # else
  763. # define GTEST_HAS_CLONE 0
  764. # endif
  765. # else
  766. # define GTEST_HAS_CLONE 1
  767. # endif
  768. # else
  769. # define GTEST_HAS_CLONE 0
  770. # endif // GTEST_OS_LINUX && !defined(__ia64__)
  771. #endif // GTEST_HAS_CLONE
  772. // Determines whether to support stream redirection. This is used to test
  773. // output correctness and to implement death tests.
  774. #ifndef GTEST_HAS_STREAM_REDIRECTION
  775. // By default, we assume that stream redirection is supported on all
  776. // platforms except known mobile ones.
  777. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
  778. GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
  779. # define GTEST_HAS_STREAM_REDIRECTION 0
  780. # else
  781. # define GTEST_HAS_STREAM_REDIRECTION 1
  782. # endif // !GTEST_OS_WINDOWS_MOBILE
  783. #endif // GTEST_HAS_STREAM_REDIRECTION
  784. // Determines whether to support death tests.
  785. // pops up a dialog window that cannot be suppressed programmatically.
  786. #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
  787. (GTEST_OS_MAC && !GTEST_OS_IOS) || \
  788. (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW || \
  789. GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \
  790. GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
  791. GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU)
  792. # define GTEST_HAS_DEATH_TEST 1
  793. #endif
  794. // Determines whether to support type-driven tests.
  795. // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
  796. // Sun Pro CC, IBM Visual Age, and HP aCC support.
  797. #if defined(__GNUC__) || defined(_MSC_VER) || defined(__SUNPRO_CC) || \
  798. defined(__IBMCPP__) || defined(__HP_aCC)
  799. # define GTEST_HAS_TYPED_TEST 1
  800. # define GTEST_HAS_TYPED_TEST_P 1
  801. #endif
  802. // Determines whether the system compiler uses UTF-16 for encoding wide strings.
  803. #define GTEST_WIDE_STRING_USES_UTF16_ \
  804. (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2)
  805. // Determines whether test results can be streamed to a socket.
  806. #if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \
  807. GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD
  808. # define GTEST_CAN_STREAM_RESULTS_ 1
  809. #endif
  810. // Defines some utility macros.
  811. // The GNU compiler emits a warning if nested "if" statements are followed by
  812. // an "else" statement and braces are not used to explicitly disambiguate the
  813. // "else" binding. This leads to problems with code like:
  814. //
  815. // if (gate)
  816. // ASSERT_*(condition) << "Some message";
  817. //
  818. // The "switch (0) case 0:" idiom is used to suppress this.
  819. #ifdef __INTEL_COMPILER
  820. # define GTEST_AMBIGUOUS_ELSE_BLOCKER_
  821. #else
  822. # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT
  823. #endif
  824. // Use this annotation at the end of a struct/class definition to
  825. // prevent the compiler from optimizing away instances that are never
  826. // used. This is useful when all interesting logic happens inside the
  827. // c'tor and / or d'tor. Example:
  828. //
  829. // struct Foo {
  830. // Foo() { ... }
  831. // } GTEST_ATTRIBUTE_UNUSED_;
  832. //
  833. // Also use it after a variable or parameter declaration to tell the
  834. // compiler the variable/parameter does not have to be used.
  835. #if defined(__GNUC__) && !defined(COMPILER_ICC)
  836. # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
  837. #elif defined(__clang__)
  838. # if __has_attribute(unused)
  839. # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
  840. # endif
  841. #endif
  842. #ifndef GTEST_ATTRIBUTE_UNUSED_
  843. # define GTEST_ATTRIBUTE_UNUSED_
  844. #endif
  845. // Use this annotation before a function that takes a printf format string.
  846. #if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC)
  847. # if defined(__MINGW_PRINTF_FORMAT)
  848. // MinGW has two different printf implementations. Ensure the format macro
  849. // matches the selected implementation. See
  850. // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/.
  851. # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
  852. __attribute__((__format__(__MINGW_PRINTF_FORMAT, string_index, \
  853. first_to_check)))
  854. # else
  855. # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
  856. __attribute__((__format__(__printf__, string_index, first_to_check)))
  857. # endif
  858. #else
  859. # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
  860. #endif
  861. // A macro to disallow copy operator=
  862. // This should be used in the private: declarations for a class.
  863. #define GTEST_DISALLOW_ASSIGN_(type) \
  864. type& operator=(type const &) = delete
  865. // A macro to disallow copy constructor and operator=
  866. // This should be used in the private: declarations for a class.
  867. #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \
  868. type(type const&) = delete; \
  869. type& operator=(type const&) = delete
  870. // A macro to disallow move operator=
  871. // This should be used in the private: declarations for a class.
  872. #define GTEST_DISALLOW_MOVE_ASSIGN_(type) \
  873. type& operator=(type &&) noexcept = delete
  874. // A macro to disallow move constructor and operator=
  875. // This should be used in the private: declarations for a class.
  876. #define GTEST_DISALLOW_MOVE_AND_ASSIGN_(type) \
  877. type(type&&) noexcept = delete; \
  878. type& operator=(type&&) noexcept = delete
  879. // Tell the compiler to warn about unused return values for functions declared
  880. // with this macro. The macro should be used on function declarations
  881. // following the argument list:
  882. //
  883. // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
  884. #if defined(__GNUC__) && !defined(COMPILER_ICC)
  885. # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
  886. #else
  887. # define GTEST_MUST_USE_RESULT_
  888. #endif // __GNUC__ && !COMPILER_ICC
  889. // MS C++ compiler emits warning when a conditional expression is compile time
  890. // constant. In some contexts this warning is false positive and needs to be
  891. // suppressed. Use the following two macros in such cases:
  892. //
  893. // GTEST_INTENTIONAL_CONST_COND_PUSH_()
  894. // while (true) {
  895. // GTEST_INTENTIONAL_CONST_COND_POP_()
  896. // }
  897. # define GTEST_INTENTIONAL_CONST_COND_PUSH_() \
  898. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)
  899. # define GTEST_INTENTIONAL_CONST_COND_POP_() \
  900. GTEST_DISABLE_MSC_WARNINGS_POP_()
  901. // Determine whether the compiler supports Microsoft's Structured Exception
  902. // Handling. This is supported by several Windows compilers but generally
  903. // does not exist on any other system.
  904. #ifndef GTEST_HAS_SEH
  905. // The user didn't tell us, so we need to figure it out.
  906. # if defined(_MSC_VER) || defined(__BORLANDC__)
  907. // These two compilers are known to support SEH.
  908. # define GTEST_HAS_SEH 1
  909. # else
  910. // Assume no SEH.
  911. # define GTEST_HAS_SEH 0
  912. # endif
  913. #endif // GTEST_HAS_SEH
  914. #ifndef GTEST_IS_THREADSAFE
  915. #define GTEST_IS_THREADSAFE \
  916. (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \
  917. (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) || \
  918. GTEST_HAS_PTHREAD)
  919. #endif // GTEST_IS_THREADSAFE
  920. // GTEST_API_ qualifies all symbols that must be exported. The definitions below
  921. // are guarded by #ifndef to give embedders a chance to define GTEST_API_ in
  922. // gtest/internal/custom/gtest-port.h
  923. #ifndef GTEST_API_
  924. #ifdef _MSC_VER
  925. # if GTEST_LINKED_AS_SHARED_LIBRARY
  926. # define GTEST_API_ __declspec(dllimport)
  927. # elif GTEST_CREATE_SHARED_LIBRARY
  928. # define GTEST_API_ __declspec(dllexport)
  929. # endif
  930. #elif __GNUC__ >= 4 || defined(__clang__)
  931. # define GTEST_API_ __attribute__((visibility ("default")))
  932. #endif // _MSC_VER
  933. #endif // GTEST_API_
  934. #ifndef GTEST_API_
  935. # define GTEST_API_
  936. #endif // GTEST_API_
  937. #ifndef GTEST_DEFAULT_DEATH_TEST_STYLE
  938. # define GTEST_DEFAULT_DEATH_TEST_STYLE "fast"
  939. #endif // GTEST_DEFAULT_DEATH_TEST_STYLE
  940. #ifdef __GNUC__
  941. // Ask the compiler to never inline a given function.
  942. # define GTEST_NO_INLINE_ __attribute__((noinline))
  943. #else
  944. # define GTEST_NO_INLINE_
  945. #endif
  946. // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
  947. #if !defined(GTEST_HAS_CXXABI_H_)
  948. # if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER))
  949. # define GTEST_HAS_CXXABI_H_ 1
  950. # else
  951. # define GTEST_HAS_CXXABI_H_ 0
  952. # endif
  953. #endif
  954. // A function level attribute to disable checking for use of uninitialized
  955. // memory when built with MemorySanitizer.
  956. #if defined(__clang__)
  957. # if __has_feature(memory_sanitizer)
  958. # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
  959. __attribute__((no_sanitize_memory))
  960. # else
  961. # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  962. # endif // __has_feature(memory_sanitizer)
  963. #else
  964. # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  965. #endif // __clang__
  966. // A function level attribute to disable AddressSanitizer instrumentation.
  967. #if defined(__clang__)
  968. # if __has_feature(address_sanitizer)
  969. # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
  970. __attribute__((no_sanitize_address))
  971. # else
  972. # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  973. # endif // __has_feature(address_sanitizer)
  974. #else
  975. # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  976. #endif // __clang__
  977. // A function level attribute to disable HWAddressSanitizer instrumentation.
  978. #if defined(__clang__)
  979. # if __has_feature(hwaddress_sanitizer)
  980. # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \
  981. __attribute__((no_sanitize("hwaddress")))
  982. # else
  983. # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  984. # endif // __has_feature(hwaddress_sanitizer)
  985. #else
  986. # define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  987. #endif // __clang__
  988. // A function level attribute to disable ThreadSanitizer instrumentation.
  989. #if defined(__clang__)
  990. # if __has_feature(thread_sanitizer)
  991. # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
  992. __attribute__((no_sanitize_thread))
  993. # else
  994. # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  995. # endif // __has_feature(thread_sanitizer)
  996. #else
  997. # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  998. #endif // __clang__
  999. namespace testing {
  1000. class Message;
  1001. // Legacy imports for backwards compatibility.
  1002. // New code should use std:: names directly.
  1003. using std::get;
  1004. using std::make_tuple;
  1005. using std::tuple;
  1006. using std::tuple_element;
  1007. using std::tuple_size;
  1008. namespace internal {
  1009. // A secret type that Google Test users don't know about. It has no
  1010. // definition on purpose. Therefore it's impossible to create a
  1011. // Secret object, which is what we want.
  1012. class Secret;
  1013. // The GTEST_COMPILE_ASSERT_ is a legacy macro used to verify that a compile
  1014. // time expression is true (in new code, use static_assert instead). For
  1015. // example, you could use it to verify the size of a static array:
  1016. //
  1017. // GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
  1018. // names_incorrect_size);
  1019. //
  1020. // The second argument to the macro must be a valid C++ identifier. If the
  1021. // expression is false, compiler will issue an error containing this identifier.
  1022. #define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg)
  1023. // A helper for suppressing warnings on constant condition. It just
  1024. // returns 'condition'.
  1025. GTEST_API_ bool IsTrue(bool condition);
  1026. // Defines RE.
  1027. #if GTEST_USES_PCRE
  1028. // if used, PCRE is injected by custom/gtest-port.h
  1029. #elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE
  1030. // A simple C++ wrapper for <regex.h>. It uses the POSIX Extended
  1031. // Regular Expression syntax.
  1032. class GTEST_API_ RE {
  1033. public:
  1034. // A copy constructor is required by the Standard to initialize object
  1035. // references from r-values.
  1036. RE(const RE& other) { Init(other.pattern()); }
  1037. // Constructs an RE from a string.
  1038. RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT
  1039. RE(const char* regex) { Init(regex); } // NOLINT
  1040. ~RE();
  1041. // Returns the string representation of the regex.
  1042. const char* pattern() const { return pattern_; }
  1043. // FullMatch(str, re) returns true if and only if regular expression re
  1044. // matches the entire str.
  1045. // PartialMatch(str, re) returns true if and only if regular expression re
  1046. // matches a substring of str (including str itself).
  1047. static bool FullMatch(const ::std::string& str, const RE& re) {
  1048. return FullMatch(str.c_str(), re);
  1049. }
  1050. static bool PartialMatch(const ::std::string& str, const RE& re) {
  1051. return PartialMatch(str.c_str(), re);
  1052. }
  1053. static bool FullMatch(const char* str, const RE& re);
  1054. static bool PartialMatch(const char* str, const RE& re);
  1055. private:
  1056. void Init(const char* regex);
  1057. const char* pattern_;
  1058. bool is_valid_;
  1059. # if GTEST_USES_POSIX_RE
  1060. regex_t full_regex_; // For FullMatch().
  1061. regex_t partial_regex_; // For PartialMatch().
  1062. # else // GTEST_USES_SIMPLE_RE
  1063. const char* full_pattern_; // For FullMatch();
  1064. # endif
  1065. };
  1066. #endif // GTEST_USES_PCRE
  1067. // Formats a source file path and a line number as they would appear
  1068. // in an error message from the compiler used to compile this code.
  1069. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
  1070. // Formats a file location for compiler-independent XML output.
  1071. // Although this function is not platform dependent, we put it next to
  1072. // FormatFileLocation in order to contrast the two functions.
  1073. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
  1074. int line);
  1075. // Defines logging utilities:
  1076. // GTEST_LOG_(severity) - logs messages at the specified severity level. The
  1077. // message itself is streamed into the macro.
  1078. // LogToStderr() - directs all log messages to stderr.
  1079. // FlushInfoLog() - flushes informational log messages.
  1080. enum GTestLogSeverity {
  1081. GTEST_INFO,
  1082. GTEST_WARNING,
  1083. GTEST_ERROR,
  1084. GTEST_FATAL
  1085. };
  1086. // Formats log entry severity, provides a stream object for streaming the
  1087. // log message, and terminates the message with a newline when going out of
  1088. // scope.
  1089. class GTEST_API_ GTestLog {
  1090. public:
  1091. GTestLog(GTestLogSeverity severity, const char* file, int line);
  1092. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  1093. ~GTestLog();
  1094. ::std::ostream& GetStream() { return ::std::cerr; }
  1095. private:
  1096. const GTestLogSeverity severity_;
  1097. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
  1098. };
  1099. #if !defined(GTEST_LOG_)
  1100. # define GTEST_LOG_(severity) \
  1101. ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
  1102. __FILE__, __LINE__).GetStream()
  1103. inline void LogToStderr() {}
  1104. inline void FlushInfoLog() { fflush(nullptr); }
  1105. #endif // !defined(GTEST_LOG_)
  1106. #if !defined(GTEST_CHECK_)
  1107. // INTERNAL IMPLEMENTATION - DO NOT USE.
  1108. //
  1109. // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
  1110. // is not satisfied.
  1111. // Synopsys:
  1112. // GTEST_CHECK_(boolean_condition);
  1113. // or
  1114. // GTEST_CHECK_(boolean_condition) << "Additional message";
  1115. //
  1116. // This checks the condition and if the condition is not satisfied
  1117. // it prints message about the condition violation, including the
  1118. // condition itself, plus additional message streamed into it, if any,
  1119. // and then it aborts the program. It aborts the program irrespective of
  1120. // whether it is built in the debug mode or not.
  1121. # define GTEST_CHECK_(condition) \
  1122. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  1123. if (::testing::internal::IsTrue(condition)) \
  1124. ; \
  1125. else \
  1126. GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
  1127. #endif // !defined(GTEST_CHECK_)
  1128. // An all-mode assert to verify that the given POSIX-style function
  1129. // call returns 0 (indicating success). Known limitation: this
  1130. // doesn't expand to a balanced 'if' statement, so enclose the macro
  1131. // in {} if you need to use it as the only statement in an 'if'
  1132. // branch.
  1133. #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
  1134. if (const int gtest_error = (posix_call)) \
  1135. GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
  1136. << gtest_error
  1137. // Transforms "T" into "const T&" according to standard reference collapsing
  1138. // rules (this is only needed as a backport for C++98 compilers that do not
  1139. // support reference collapsing). Specifically, it transforms:
  1140. //
  1141. // char ==> const char&
  1142. // const char ==> const char&
  1143. // char& ==> char&
  1144. // const char& ==> const char&
  1145. //
  1146. // Note that the non-const reference will not have "const" added. This is
  1147. // standard, and necessary so that "T" can always bind to "const T&".
  1148. template <typename T>
  1149. struct ConstRef { typedef const T& type; };
  1150. template <typename T>
  1151. struct ConstRef<T&> { typedef T& type; };
  1152. // The argument T must depend on some template parameters.
  1153. #define GTEST_REFERENCE_TO_CONST_(T) \
  1154. typename ::testing::internal::ConstRef<T>::type
  1155. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  1156. //
  1157. // Use ImplicitCast_ as a safe version of static_cast for upcasting in
  1158. // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a
  1159. // const Foo*). When you use ImplicitCast_, the compiler checks that
  1160. // the cast is safe. Such explicit ImplicitCast_s are necessary in
  1161. // surprisingly many situations where C++ demands an exact type match
  1162. // instead of an argument type convertable to a target type.
  1163. //
  1164. // The syntax for using ImplicitCast_ is the same as for static_cast:
  1165. //
  1166. // ImplicitCast_<ToType>(expr)
  1167. //
  1168. // ImplicitCast_ would have been part of the C++ standard library,
  1169. // but the proposal was submitted too late. It will probably make
  1170. // its way into the language in the future.
  1171. //
  1172. // This relatively ugly name is intentional. It prevents clashes with
  1173. // similar functions users may have (e.g., implicit_cast). The internal
  1174. // namespace alone is not enough because the function can be found by ADL.
  1175. template<typename To>
  1176. inline To ImplicitCast_(To x) { return x; }
  1177. // When you upcast (that is, cast a pointer from type Foo to type
  1178. // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
  1179. // always succeed. When you downcast (that is, cast a pointer from
  1180. // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
  1181. // how do you know the pointer is really of type SubclassOfFoo? It
  1182. // could be a bare Foo, or of type DifferentSubclassOfFoo. Thus,
  1183. // when you downcast, you should use this macro. In debug mode, we
  1184. // use dynamic_cast<> to double-check the downcast is legal (we die
  1185. // if it's not). In normal mode, we do the efficient static_cast<>
  1186. // instead. Thus, it's important to test in debug mode to make sure
  1187. // the cast is legal!
  1188. // This is the only place in the code we should use dynamic_cast<>.
  1189. // In particular, you SHOULDN'T be using dynamic_cast<> in order to
  1190. // do RTTI (eg code like this:
  1191. // if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
  1192. // if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
  1193. // You should design the code some other way not to need this.
  1194. //
  1195. // This relatively ugly name is intentional. It prevents clashes with
  1196. // similar functions users may have (e.g., down_cast). The internal
  1197. // namespace alone is not enough because the function can be found by ADL.
  1198. template<typename To, typename From> // use like this: DownCast_<T*>(foo);
  1199. inline To DownCast_(From* f) { // so we only accept pointers
  1200. // Ensures that To is a sub-type of From *. This test is here only
  1201. // for compile-time type checking, and has no overhead in an
  1202. // optimized build at run-time, as it will be optimized away
  1203. // completely.
  1204. GTEST_INTENTIONAL_CONST_COND_PUSH_()
  1205. if (false) {
  1206. GTEST_INTENTIONAL_CONST_COND_POP_()
  1207. const To to = nullptr;
  1208. ::testing::internal::ImplicitCast_<From*>(to);
  1209. }
  1210. #if GTEST_HAS_RTTI
  1211. // RTTI: debug mode only!
  1212. GTEST_CHECK_(f == nullptr || dynamic_cast<To>(f) != nullptr);
  1213. #endif
  1214. return static_cast<To>(f);
  1215. }
  1216. // Downcasts the pointer of type Base to Derived.
  1217. // Derived must be a subclass of Base. The parameter MUST
  1218. // point to a class of type Derived, not any subclass of it.
  1219. // When RTTI is available, the function performs a runtime
  1220. // check to enforce this.
  1221. template <class Derived, class Base>
  1222. Derived* CheckedDowncastToActualType(Base* base) {
  1223. #if GTEST_HAS_RTTI
  1224. GTEST_CHECK_(typeid(*base) == typeid(Derived));
  1225. #endif
  1226. #if GTEST_HAS_DOWNCAST_
  1227. return ::down_cast<Derived*>(base);
  1228. #elif GTEST_HAS_RTTI
  1229. return dynamic_cast<Derived*>(base); // NOLINT
  1230. #else
  1231. return static_cast<Derived*>(base); // Poor man's downcast.
  1232. #endif
  1233. }
  1234. #if GTEST_HAS_STREAM_REDIRECTION
  1235. // Defines the stderr capturer:
  1236. // CaptureStdout - starts capturing stdout.
  1237. // GetCapturedStdout - stops capturing stdout and returns the captured string.
  1238. // CaptureStderr - starts capturing stderr.
  1239. // GetCapturedStderr - stops capturing stderr and returns the captured string.
  1240. //
  1241. GTEST_API_ void CaptureStdout();
  1242. GTEST_API_ std::string GetCapturedStdout();
  1243. GTEST_API_ void CaptureStderr();
  1244. GTEST_API_ std::string GetCapturedStderr();
  1245. #endif // GTEST_HAS_STREAM_REDIRECTION
  1246. // Returns the size (in bytes) of a file.
  1247. GTEST_API_ size_t GetFileSize(FILE* file);
  1248. // Reads the entire content of a file as a string.
  1249. GTEST_API_ std::string ReadEntireFile(FILE* file);
  1250. // All command line arguments.
  1251. GTEST_API_ std::vector<std::string> GetArgvs();
  1252. #if GTEST_HAS_DEATH_TEST
  1253. std::vector<std::string> GetInjectableArgvs();
  1254. // Deprecated: pass the args vector by value instead.
  1255. void SetInjectableArgvs(const std::vector<std::string>* new_argvs);
  1256. void SetInjectableArgvs(const std::vector<std::string>& new_argvs);
  1257. void ClearInjectableArgvs();
  1258. #endif // GTEST_HAS_DEATH_TEST
  1259. // Defines synchronization primitives.
  1260. #if GTEST_IS_THREADSAFE
  1261. # if GTEST_HAS_PTHREAD
  1262. // Sleeps for (roughly) n milliseconds. This function is only for testing
  1263. // Google Test's own constructs. Don't use it in user tests, either
  1264. // directly or indirectly.
  1265. inline void SleepMilliseconds(int n) {
  1266. const timespec time = {
  1267. 0, // 0 seconds.
  1268. n * 1000L * 1000L, // And n ms.
  1269. };
  1270. nanosleep(&time, nullptr);
  1271. }
  1272. # endif // GTEST_HAS_PTHREAD
  1273. # if GTEST_HAS_NOTIFICATION_
  1274. // Notification has already been imported into the namespace.
  1275. // Nothing to do here.
  1276. # elif GTEST_HAS_PTHREAD
  1277. // Allows a controller thread to pause execution of newly created
  1278. // threads until notified. Instances of this class must be created
  1279. // and destroyed in the controller thread.
  1280. //
  1281. // This class is only for testing Google Test's own constructs. Do not
  1282. // use it in user tests, either directly or indirectly.
  1283. class Notification {
  1284. public:
  1285. Notification() : notified_(false) {
  1286. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
  1287. }
  1288. ~Notification() {
  1289. pthread_mutex_destroy(&mutex_);
  1290. }
  1291. // Notifies all threads created with this notification to start. Must
  1292. // be called from the controller thread.
  1293. void Notify() {
  1294. pthread_mutex_lock(&mutex_);
  1295. notified_ = true;
  1296. pthread_mutex_unlock(&mutex_);
  1297. }
  1298. // Blocks until the controller thread notifies. Must be called from a test
  1299. // thread.
  1300. void WaitForNotification() {
  1301. for (;;) {
  1302. pthread_mutex_lock(&mutex_);
  1303. const bool notified = notified_;
  1304. pthread_mutex_unlock(&mutex_);
  1305. if (notified)
  1306. break;
  1307. SleepMilliseconds(10);
  1308. }
  1309. }
  1310. private:
  1311. pthread_mutex_t mutex_;
  1312. bool notified_;
  1313. GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
  1314. };
  1315. # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  1316. GTEST_API_ void SleepMilliseconds(int n);
  1317. // Provides leak-safe Windows kernel handle ownership.
  1318. // Used in death tests and in threading support.
  1319. class GTEST_API_ AutoHandle {
  1320. public:
  1321. // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to
  1322. // avoid including <windows.h> in this header file. Including <windows.h> is
  1323. // undesirable because it defines a lot of symbols and macros that tend to
  1324. // conflict with client code. This assumption is verified by
  1325. // WindowsTypesTest.HANDLEIsVoidStar.
  1326. typedef void* Handle;
  1327. AutoHandle();
  1328. explicit AutoHandle(Handle handle);
  1329. ~AutoHandle();
  1330. Handle Get() const;
  1331. void Reset();
  1332. void Reset(Handle handle);
  1333. private:
  1334. // Returns true if and only if the handle is a valid handle object that can be
  1335. // closed.
  1336. bool IsCloseable() const;
  1337. Handle handle_;
  1338. GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
  1339. };
  1340. // Allows a controller thread to pause execution of newly created
  1341. // threads until notified. Instances of this class must be created
  1342. // and destroyed in the controller thread.
  1343. //
  1344. // This class is only for testing Google Test's own constructs. Do not
  1345. // use it in user tests, either directly or indirectly.
  1346. class GTEST_API_ Notification {
  1347. public:
  1348. Notification();
  1349. void Notify();
  1350. void WaitForNotification();
  1351. private:
  1352. AutoHandle event_;
  1353. GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
  1354. };
  1355. # endif // GTEST_HAS_NOTIFICATION_
  1356. // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
  1357. // defined, but we don't want to use MinGW's pthreads implementation, which
  1358. // has conformance problems with some versions of the POSIX standard.
  1359. # if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
  1360. // As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
  1361. // Consequently, it cannot select a correct instantiation of ThreadWithParam
  1362. // in order to call its Run(). Introducing ThreadWithParamBase as a
  1363. // non-templated base class for ThreadWithParam allows us to bypass this
  1364. // problem.
  1365. class ThreadWithParamBase {
  1366. public:
  1367. virtual ~ThreadWithParamBase() {}
  1368. virtual void Run() = 0;
  1369. };
  1370. // pthread_create() accepts a pointer to a function type with the C linkage.
  1371. // According to the Standard (7.5/1), function types with different linkages
  1372. // are different even if they are otherwise identical. Some compilers (for
  1373. // example, SunStudio) treat them as different types. Since class methods
  1374. // cannot be defined with C-linkage we need to define a free C-function to
  1375. // pass into pthread_create().
  1376. extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
  1377. static_cast<ThreadWithParamBase*>(thread)->Run();
  1378. return nullptr;
  1379. }
  1380. // Helper class for testing Google Test's multi-threading constructs.
  1381. // To use it, write:
  1382. //
  1383. // void ThreadFunc(int param) { /* Do things with param */ }
  1384. // Notification thread_can_start;
  1385. // ...
  1386. // // The thread_can_start parameter is optional; you can supply NULL.
  1387. // ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
  1388. // thread_can_start.Notify();
  1389. //
  1390. // These classes are only for testing Google Test's own constructs. Do
  1391. // not use them in user tests, either directly or indirectly.
  1392. template <typename T>
  1393. class ThreadWithParam : public ThreadWithParamBase {
  1394. public:
  1395. typedef void UserThreadFunc(T);
  1396. ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
  1397. : func_(func),
  1398. param_(param),
  1399. thread_can_start_(thread_can_start),
  1400. finished_(false) {
  1401. ThreadWithParamBase* const base = this;
  1402. // The thread can be created only after all fields except thread_
  1403. // have been initialized.
  1404. GTEST_CHECK_POSIX_SUCCESS_(
  1405. pthread_create(&thread_, nullptr, &ThreadFuncWithCLinkage, base));
  1406. }
  1407. ~ThreadWithParam() override { Join(); }
  1408. void Join() {
  1409. if (!finished_) {
  1410. GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, nullptr));
  1411. finished_ = true;
  1412. }
  1413. }
  1414. void Run() override {
  1415. if (thread_can_start_ != nullptr) thread_can_start_->WaitForNotification();
  1416. func_(param_);
  1417. }
  1418. private:
  1419. UserThreadFunc* const func_; // User-supplied thread function.
  1420. const T param_; // User-supplied parameter to the thread function.
  1421. // When non-NULL, used to block execution until the controller thread
  1422. // notifies.
  1423. Notification* const thread_can_start_;
  1424. bool finished_; // true if and only if we know that the thread function has
  1425. // finished.
  1426. pthread_t thread_; // The native thread object.
  1427. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
  1428. };
  1429. # endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD ||
  1430. // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
  1431. # if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
  1432. // Mutex and ThreadLocal have already been imported into the namespace.
  1433. // Nothing to do here.
  1434. # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  1435. // Mutex implements mutex on Windows platforms. It is used in conjunction
  1436. // with class MutexLock:
  1437. //
  1438. // Mutex mutex;
  1439. // ...
  1440. // MutexLock lock(&mutex); // Acquires the mutex and releases it at the
  1441. // // end of the current scope.
  1442. //
  1443. // A static Mutex *must* be defined or declared using one of the following
  1444. // macros:
  1445. // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
  1446. // GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
  1447. //
  1448. // (A non-static Mutex is defined/declared in the usual way).
  1449. class GTEST_API_ Mutex {
  1450. public:
  1451. enum MutexType { kStatic = 0, kDynamic = 1 };
  1452. // We rely on kStaticMutex being 0 as it is to what the linker initializes
  1453. // type_ in static mutexes. critical_section_ will be initialized lazily
  1454. // in ThreadSafeLazyInit().
  1455. enum StaticConstructorSelector { kStaticMutex = 0 };
  1456. // This constructor intentionally does nothing. It relies on type_ being
  1457. // statically initialized to 0 (effectively setting it to kStatic) and on
  1458. // ThreadSafeLazyInit() to lazily initialize the rest of the members.
  1459. explicit Mutex(StaticConstructorSelector /*dummy*/) {}
  1460. Mutex();
  1461. ~Mutex();
  1462. void Lock();
  1463. void Unlock();
  1464. // Does nothing if the current thread holds the mutex. Otherwise, crashes
  1465. // with high probability.
  1466. void AssertHeld();
  1467. private:
  1468. // Initializes owner_thread_id_ and critical_section_ in static mutexes.
  1469. void ThreadSafeLazyInit();
  1470. // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503,
  1471. // we assume that 0 is an invalid value for thread IDs.
  1472. unsigned int owner_thread_id_;
  1473. // For static mutexes, we rely on these members being initialized to zeros
  1474. // by the linker.
  1475. MutexType type_;
  1476. long critical_section_init_phase_; // NOLINT
  1477. GTEST_CRITICAL_SECTION* critical_section_;
  1478. GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
  1479. };
  1480. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
  1481. extern ::testing::internal::Mutex mutex
  1482. # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
  1483. ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)
  1484. // We cannot name this class MutexLock because the ctor declaration would
  1485. // conflict with a macro named MutexLock, which is defined on some
  1486. // platforms. That macro is used as a defensive measure to prevent against
  1487. // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
  1488. // "MutexLock l(&mu)". Hence the typedef trick below.
  1489. class GTestMutexLock {
  1490. public:
  1491. explicit GTestMutexLock(Mutex* mutex)
  1492. : mutex_(mutex) { mutex_->Lock(); }
  1493. ~GTestMutexLock() { mutex_->Unlock(); }
  1494. private:
  1495. Mutex* const mutex_;
  1496. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
  1497. };
  1498. typedef GTestMutexLock MutexLock;
  1499. // Base class for ValueHolder<T>. Allows a caller to hold and delete a value
  1500. // without knowing its type.
  1501. class ThreadLocalValueHolderBase {
  1502. public:
  1503. virtual ~ThreadLocalValueHolderBase() {}
  1504. };
  1505. // Provides a way for a thread to send notifications to a ThreadLocal
  1506. // regardless of its parameter type.
  1507. class ThreadLocalBase {
  1508. public:
  1509. // Creates a new ValueHolder<T> object holding a default value passed to
  1510. // this ThreadLocal<T>'s constructor and returns it. It is the caller's
  1511. // responsibility not to call this when the ThreadLocal<T> instance already
  1512. // has a value on the current thread.
  1513. virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0;
  1514. protected:
  1515. ThreadLocalBase() {}
  1516. virtual ~ThreadLocalBase() {}
  1517. private:
  1518. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase);
  1519. };
  1520. // Maps a thread to a set of ThreadLocals that have values instantiated on that
  1521. // thread and notifies them when the thread exits. A ThreadLocal instance is
  1522. // expected to persist until all threads it has values on have terminated.
  1523. class GTEST_API_ ThreadLocalRegistry {
  1524. public:
  1525. // Registers thread_local_instance as having value on the current thread.
  1526. // Returns a value that can be used to identify the thread from other threads.
  1527. static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
  1528. const ThreadLocalBase* thread_local_instance);
  1529. // Invoked when a ThreadLocal instance is destroyed.
  1530. static void OnThreadLocalDestroyed(
  1531. const ThreadLocalBase* thread_local_instance);
  1532. };
  1533. class GTEST_API_ ThreadWithParamBase {
  1534. public:
  1535. void Join();
  1536. protected:
  1537. class Runnable {
  1538. public:
  1539. virtual ~Runnable() {}
  1540. virtual void Run() = 0;
  1541. };
  1542. ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start);
  1543. virtual ~ThreadWithParamBase();
  1544. private:
  1545. AutoHandle thread_;
  1546. };
  1547. // Helper class for testing Google Test's multi-threading constructs.
  1548. template <typename T>
  1549. class ThreadWithParam : public ThreadWithParamBase {
  1550. public:
  1551. typedef void UserThreadFunc(T);
  1552. ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
  1553. : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {
  1554. }
  1555. virtual ~ThreadWithParam() {}
  1556. private:
  1557. class RunnableImpl : public Runnable {
  1558. public:
  1559. RunnableImpl(UserThreadFunc* func, T param)
  1560. : func_(func),
  1561. param_(param) {
  1562. }
  1563. virtual ~RunnableImpl() {}
  1564. virtual void Run() {
  1565. func_(param_);
  1566. }
  1567. private:
  1568. UserThreadFunc* const func_;
  1569. const T param_;
  1570. GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl);
  1571. };
  1572. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
  1573. };
  1574. // Implements thread-local storage on Windows systems.
  1575. //
  1576. // // Thread 1
  1577. // ThreadLocal<int> tl(100); // 100 is the default value for each thread.
  1578. //
  1579. // // Thread 2
  1580. // tl.set(150); // Changes the value for thread 2 only.
  1581. // EXPECT_EQ(150, tl.get());
  1582. //
  1583. // // Thread 1
  1584. // EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value.
  1585. // tl.set(200);
  1586. // EXPECT_EQ(200, tl.get());
  1587. //
  1588. // The template type argument T must have a public copy constructor.
  1589. // In addition, the default ThreadLocal constructor requires T to have
  1590. // a public default constructor.
  1591. //
  1592. // The users of a TheadLocal instance have to make sure that all but one
  1593. // threads (including the main one) using that instance have exited before
  1594. // destroying it. Otherwise, the per-thread objects managed for them by the
  1595. // ThreadLocal instance are not guaranteed to be destroyed on all platforms.
  1596. //
  1597. // Google Test only uses global ThreadLocal objects. That means they
  1598. // will die after main() has returned. Therefore, no per-thread
  1599. // object managed by Google Test will be leaked as long as all threads
  1600. // using Google Test have exited when main() returns.
  1601. template <typename T>
  1602. class ThreadLocal : public ThreadLocalBase {
  1603. public:
  1604. ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {}
  1605. explicit ThreadLocal(const T& value)
  1606. : default_factory_(new InstanceValueHolderFactory(value)) {}
  1607. ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }
  1608. T* pointer() { return GetOrCreateValue(); }
  1609. const T* pointer() const { return GetOrCreateValue(); }
  1610. const T& get() const { return *pointer(); }
  1611. void set(const T& value) { *pointer() = value; }
  1612. private:
  1613. // Holds a value of T. Can be deleted via its base class without the caller
  1614. // knowing the type of T.
  1615. class ValueHolder : public ThreadLocalValueHolderBase {
  1616. public:
  1617. ValueHolder() : value_() {}
  1618. explicit ValueHolder(const T& value) : value_(value) {}
  1619. T* pointer() { return &value_; }
  1620. private:
  1621. T value_;
  1622. GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
  1623. };
  1624. T* GetOrCreateValue() const {
  1625. return static_cast<ValueHolder*>(
  1626. ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer();
  1627. }
  1628. virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const {
  1629. return default_factory_->MakeNewHolder();
  1630. }
  1631. class ValueHolderFactory {
  1632. public:
  1633. ValueHolderFactory() {}
  1634. virtual ~ValueHolderFactory() {}
  1635. virtual ValueHolder* MakeNewHolder() const = 0;
  1636. private:
  1637. GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
  1638. };
  1639. class DefaultValueHolderFactory : public ValueHolderFactory {
  1640. public:
  1641. DefaultValueHolderFactory() {}
  1642. ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
  1643. private:
  1644. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
  1645. };
  1646. class InstanceValueHolderFactory : public ValueHolderFactory {
  1647. public:
  1648. explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
  1649. ValueHolder* MakeNewHolder() const override {
  1650. return new ValueHolder(value_);
  1651. }
  1652. private:
  1653. const T value_; // The value for each thread.
  1654. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
  1655. };
  1656. std::unique_ptr<ValueHolderFactory> default_factory_;
  1657. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
  1658. };
  1659. # elif GTEST_HAS_PTHREAD
  1660. // MutexBase and Mutex implement mutex on pthreads-based platforms.
  1661. class MutexBase {
  1662. public:
  1663. // Acquires this mutex.
  1664. void Lock() {
  1665. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
  1666. owner_ = pthread_self();
  1667. has_owner_ = true;
  1668. }
  1669. // Releases this mutex.
  1670. void Unlock() {
  1671. // Since the lock is being released the owner_ field should no longer be
  1672. // considered valid. We don't protect writing to has_owner_ here, as it's
  1673. // the caller's responsibility to ensure that the current thread holds the
  1674. // mutex when this is called.
  1675. has_owner_ = false;
  1676. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
  1677. }
  1678. // Does nothing if the current thread holds the mutex. Otherwise, crashes
  1679. // with high probability.
  1680. void AssertHeld() const {
  1681. GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))
  1682. << "The current thread is not holding the mutex @" << this;
  1683. }
  1684. // A static mutex may be used before main() is entered. It may even
  1685. // be used before the dynamic initialization stage. Therefore we
  1686. // must be able to initialize a static mutex object at link time.
  1687. // This means MutexBase has to be a POD and its member variables
  1688. // have to be public.
  1689. public:
  1690. pthread_mutex_t mutex_; // The underlying pthread mutex.
  1691. // has_owner_ indicates whether the owner_ field below contains a valid thread
  1692. // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All
  1693. // accesses to the owner_ field should be protected by a check of this field.
  1694. // An alternative might be to memset() owner_ to all zeros, but there's no
  1695. // guarantee that a zero'd pthread_t is necessarily invalid or even different
  1696. // from pthread_self().
  1697. bool has_owner_;
  1698. pthread_t owner_; // The thread holding the mutex.
  1699. };
  1700. // Forward-declares a static mutex.
  1701. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
  1702. extern ::testing::internal::MutexBase mutex
  1703. // Defines and statically (i.e. at link time) initializes a static mutex.
  1704. // The initialization list here does not explicitly initialize each field,
  1705. // instead relying on default initialization for the unspecified fields. In
  1706. // particular, the owner_ field (a pthread_t) is not explicitly initialized.
  1707. // This allows initialization to work whether pthread_t is a scalar or struct.
  1708. // The flag -Wmissing-field-initializers must not be specified for this to work.
  1709. #define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
  1710. ::testing::internal::MutexBase mutex = {PTHREAD_MUTEX_INITIALIZER, false, 0}
  1711. // The Mutex class can only be used for mutexes created at runtime. It
  1712. // shares its API with MutexBase otherwise.
  1713. class Mutex : public MutexBase {
  1714. public:
  1715. Mutex() {
  1716. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
  1717. has_owner_ = false;
  1718. }
  1719. ~Mutex() {
  1720. GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
  1721. }
  1722. private:
  1723. GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
  1724. };
  1725. // We cannot name this class MutexLock because the ctor declaration would
  1726. // conflict with a macro named MutexLock, which is defined on some
  1727. // platforms. That macro is used as a defensive measure to prevent against
  1728. // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
  1729. // "MutexLock l(&mu)". Hence the typedef trick below.
  1730. class GTestMutexLock {
  1731. public:
  1732. explicit GTestMutexLock(MutexBase* mutex)
  1733. : mutex_(mutex) { mutex_->Lock(); }
  1734. ~GTestMutexLock() { mutex_->Unlock(); }
  1735. private:
  1736. MutexBase* const mutex_;
  1737. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
  1738. };
  1739. typedef GTestMutexLock MutexLock;
  1740. // Helpers for ThreadLocal.
  1741. // pthread_key_create() requires DeleteThreadLocalValue() to have
  1742. // C-linkage. Therefore it cannot be templatized to access
  1743. // ThreadLocal<T>. Hence the need for class
  1744. // ThreadLocalValueHolderBase.
  1745. class ThreadLocalValueHolderBase {
  1746. public:
  1747. virtual ~ThreadLocalValueHolderBase() {}
  1748. };
  1749. // Called by pthread to delete thread-local data stored by
  1750. // pthread_setspecific().
  1751. extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
  1752. delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
  1753. }
  1754. // Implements thread-local storage on pthreads-based systems.
  1755. template <typename T>
  1756. class GTEST_API_ ThreadLocal {
  1757. public:
  1758. ThreadLocal()
  1759. : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {}
  1760. explicit ThreadLocal(const T& value)
  1761. : key_(CreateKey()),
  1762. default_factory_(new InstanceValueHolderFactory(value)) {}
  1763. ~ThreadLocal() {
  1764. // Destroys the managed object for the current thread, if any.
  1765. DeleteThreadLocalValue(pthread_getspecific(key_));
  1766. // Releases resources associated with the key. This will *not*
  1767. // delete managed objects for other threads.
  1768. GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));
  1769. }
  1770. T* pointer() { return GetOrCreateValue(); }
  1771. const T* pointer() const { return GetOrCreateValue(); }
  1772. const T& get() const { return *pointer(); }
  1773. void set(const T& value) { *pointer() = value; }
  1774. private:
  1775. // Holds a value of type T.
  1776. class ValueHolder : public ThreadLocalValueHolderBase {
  1777. public:
  1778. ValueHolder() : value_() {}
  1779. explicit ValueHolder(const T& value) : value_(value) {}
  1780. T* pointer() { return &value_; }
  1781. private:
  1782. T value_;
  1783. GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
  1784. };
  1785. static pthread_key_t CreateKey() {
  1786. pthread_key_t key;
  1787. // When a thread exits, DeleteThreadLocalValue() will be called on
  1788. // the object managed for that thread.
  1789. GTEST_CHECK_POSIX_SUCCESS_(
  1790. pthread_key_create(&key, &DeleteThreadLocalValue));
  1791. return key;
  1792. }
  1793. T* GetOrCreateValue() const {
  1794. ThreadLocalValueHolderBase* const holder =
  1795. static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));
  1796. if (holder != nullptr) {
  1797. return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();
  1798. }
  1799. ValueHolder* const new_holder = default_factory_->MakeNewHolder();
  1800. ThreadLocalValueHolderBase* const holder_base = new_holder;
  1801. GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));
  1802. return new_holder->pointer();
  1803. }
  1804. class ValueHolderFactory {
  1805. public:
  1806. ValueHolderFactory() {}
  1807. virtual ~ValueHolderFactory() {}
  1808. virtual ValueHolder* MakeNewHolder() const = 0;
  1809. private:
  1810. GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
  1811. };
  1812. class DefaultValueHolderFactory : public ValueHolderFactory {
  1813. public:
  1814. DefaultValueHolderFactory() {}
  1815. ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
  1816. private:
  1817. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
  1818. };
  1819. class InstanceValueHolderFactory : public ValueHolderFactory {
  1820. public:
  1821. explicit InstanceValueHolderFactory(const T& value) : value_(value) {}
  1822. ValueHolder* MakeNewHolder() const override {
  1823. return new ValueHolder(value_);
  1824. }
  1825. private:
  1826. const T value_; // The value for each thread.
  1827. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
  1828. };
  1829. // A key pthreads uses for looking up per-thread values.
  1830. const pthread_key_t key_;
  1831. std::unique_ptr<ValueHolderFactory> default_factory_;
  1832. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
  1833. };
  1834. # endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
  1835. #else // GTEST_IS_THREADSAFE
  1836. // A dummy implementation of synchronization primitives (mutex, lock,
  1837. // and thread-local variable). Necessary for compiling Google Test where
  1838. // mutex is not supported - using Google Test in multiple threads is not
  1839. // supported on such platforms.
  1840. class Mutex {
  1841. public:
  1842. Mutex() {}
  1843. void Lock() {}
  1844. void Unlock() {}
  1845. void AssertHeld() const {}
  1846. };
  1847. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
  1848. extern ::testing::internal::Mutex mutex
  1849. # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
  1850. // We cannot name this class MutexLock because the ctor declaration would
  1851. // conflict with a macro named MutexLock, which is defined on some
  1852. // platforms. That macro is used as a defensive measure to prevent against
  1853. // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
  1854. // "MutexLock l(&mu)". Hence the typedef trick below.
  1855. class GTestMutexLock {
  1856. public:
  1857. explicit GTestMutexLock(Mutex*) {} // NOLINT
  1858. };
  1859. typedef GTestMutexLock MutexLock;
  1860. template <typename T>
  1861. class GTEST_API_ ThreadLocal {
  1862. public:
  1863. ThreadLocal() : value_() {}
  1864. explicit ThreadLocal(const T& value) : value_(value) {}
  1865. T* pointer() { return &value_; }
  1866. const T* pointer() const { return &value_; }
  1867. const T& get() const { return value_; }
  1868. void set(const T& value) { value_ = value; }
  1869. private:
  1870. T value_;
  1871. };
  1872. #endif // GTEST_IS_THREADSAFE
  1873. // Returns the number of threads running in the process, or 0 to indicate that
  1874. // we cannot detect it.
  1875. GTEST_API_ size_t GetThreadCount();
  1876. #if GTEST_OS_WINDOWS
  1877. # define GTEST_PATH_SEP_ "\\"
  1878. # define GTEST_HAS_ALT_PATH_SEP_ 1
  1879. #else
  1880. # define GTEST_PATH_SEP_ "/"
  1881. # define GTEST_HAS_ALT_PATH_SEP_ 0
  1882. #endif // GTEST_OS_WINDOWS
  1883. // Utilities for char.
  1884. // isspace(int ch) and friends accept an unsigned char or EOF. char
  1885. // may be signed, depending on the compiler (or compiler flags).
  1886. // Therefore we need to cast a char to unsigned char before calling
  1887. // isspace(), etc.
  1888. inline bool IsAlpha(char ch) {
  1889. return isalpha(static_cast<unsigned char>(ch)) != 0;
  1890. }
  1891. inline bool IsAlNum(char ch) {
  1892. return isalnum(static_cast<unsigned char>(ch)) != 0;
  1893. }
  1894. inline bool IsDigit(char ch) {
  1895. return isdigit(static_cast<unsigned char>(ch)) != 0;
  1896. }
  1897. inline bool IsLower(char ch) {
  1898. return islower(static_cast<unsigned char>(ch)) != 0;
  1899. }
  1900. inline bool IsSpace(char ch) {
  1901. return isspace(static_cast<unsigned char>(ch)) != 0;
  1902. }
  1903. inline bool IsUpper(char ch) {
  1904. return isupper(static_cast<unsigned char>(ch)) != 0;
  1905. }
  1906. inline bool IsXDigit(char ch) {
  1907. return isxdigit(static_cast<unsigned char>(ch)) != 0;
  1908. }
  1909. #ifdef __cpp_char8_t
  1910. inline bool IsXDigit(char8_t ch) {
  1911. return isxdigit(static_cast<unsigned char>(ch)) != 0;
  1912. }
  1913. #endif
  1914. inline bool IsXDigit(char16_t ch) {
  1915. const unsigned char low_byte = static_cast<unsigned char>(ch);
  1916. return ch == low_byte && isxdigit(low_byte) != 0;
  1917. }
  1918. inline bool IsXDigit(char32_t ch) {
  1919. const unsigned char low_byte = static_cast<unsigned char>(ch);
  1920. return ch == low_byte && isxdigit(low_byte) != 0;
  1921. }
  1922. inline bool IsXDigit(wchar_t ch) {
  1923. const unsigned char low_byte = static_cast<unsigned char>(ch);
  1924. return ch == low_byte && isxdigit(low_byte) != 0;
  1925. }
  1926. inline char ToLower(char ch) {
  1927. return static_cast<char>(tolower(static_cast<unsigned char>(ch)));
  1928. }
  1929. inline char ToUpper(char ch) {
  1930. return static_cast<char>(toupper(static_cast<unsigned char>(ch)));
  1931. }
  1932. inline std::string StripTrailingSpaces(std::string str) {
  1933. std::string::iterator it = str.end();
  1934. while (it != str.begin() && IsSpace(*--it))
  1935. it = str.erase(it);
  1936. return str;
  1937. }
  1938. // The testing::internal::posix namespace holds wrappers for common
  1939. // POSIX functions. These wrappers hide the differences between
  1940. // Windows/MSVC and POSIX systems. Since some compilers define these
  1941. // standard functions as macros, the wrapper cannot have the same name
  1942. // as the wrapped function.
  1943. namespace posix {
  1944. // Functions with a different name on Windows.
  1945. #if GTEST_OS_WINDOWS
  1946. typedef struct _stat StatStruct;
  1947. # ifdef __BORLANDC__
  1948. inline int DoIsATTY(int fd) { return isatty(fd); }
  1949. inline int StrCaseCmp(const char* s1, const char* s2) {
  1950. return stricmp(s1, s2);
  1951. }
  1952. inline char* StrDup(const char* src) { return strdup(src); }
  1953. # else // !__BORLANDC__
  1954. # if GTEST_OS_WINDOWS_MOBILE
  1955. inline int DoIsATTY(int /* fd */) { return 0; }
  1956. # else
  1957. inline int DoIsATTY(int fd) { return _isatty(fd); }
  1958. # endif // GTEST_OS_WINDOWS_MOBILE
  1959. inline int StrCaseCmp(const char* s1, const char* s2) {
  1960. return _stricmp(s1, s2);
  1961. }
  1962. inline char* StrDup(const char* src) { return _strdup(src); }
  1963. # endif // __BORLANDC__
  1964. # if GTEST_OS_WINDOWS_MOBILE
  1965. inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
  1966. // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
  1967. // time and thus not defined there.
  1968. # else
  1969. inline int FileNo(FILE* file) { return _fileno(file); }
  1970. inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
  1971. inline int RmDir(const char* dir) { return _rmdir(dir); }
  1972. inline bool IsDir(const StatStruct& st) {
  1973. return (_S_IFDIR & st.st_mode) != 0;
  1974. }
  1975. # endif // GTEST_OS_WINDOWS_MOBILE
  1976. #elif GTEST_OS_ESP8266
  1977. typedef struct stat StatStruct;
  1978. inline int FileNo(FILE* file) { return fileno(file); }
  1979. inline int DoIsATTY(int fd) { return isatty(fd); }
  1980. inline int Stat(const char* path, StatStruct* buf) {
  1981. // stat function not implemented on ESP8266
  1982. return 0;
  1983. }
  1984. inline int StrCaseCmp(const char* s1, const char* s2) {
  1985. return strcasecmp(s1, s2);
  1986. }
  1987. inline char* StrDup(const char* src) { return strdup(src); }
  1988. inline int RmDir(const char* dir) { return rmdir(dir); }
  1989. inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
  1990. #else
  1991. typedef struct stat StatStruct;
  1992. inline int FileNo(FILE* file) { return fileno(file); }
  1993. inline int DoIsATTY(int fd) { return isatty(fd); }
  1994. inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
  1995. inline int StrCaseCmp(const char* s1, const char* s2) {
  1996. return strcasecmp(s1, s2);
  1997. }
  1998. inline char* StrDup(const char* src) { return strdup(src); }
  1999. inline int RmDir(const char* dir) { return rmdir(dir); }
  2000. inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
  2001. #endif // GTEST_OS_WINDOWS
  2002. inline int IsATTY(int fd) {
  2003. // DoIsATTY might change errno (for example ENOTTY in case you redirect stdout
  2004. // to a file on Linux), which is unexpected, so save the previous value, and
  2005. // restore it after the call.
  2006. int savedErrno = errno;
  2007. int isAttyValue = DoIsATTY(fd);
  2008. errno = savedErrno;
  2009. return isAttyValue;
  2010. }
  2011. // Functions deprecated by MSVC 8.0.
  2012. GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
  2013. // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
  2014. // StrError() aren't needed on Windows CE at this time and thus not
  2015. // defined there.
  2016. #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
  2017. !GTEST_OS_WINDOWS_RT && !GTEST_OS_ESP8266 && !GTEST_OS_XTENSA
  2018. inline int ChDir(const char* dir) { return chdir(dir); }
  2019. #endif
  2020. inline FILE* FOpen(const char* path, const char* mode) {
  2021. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
  2022. struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {};
  2023. std::wstring_convert<wchar_codecvt> converter;
  2024. std::wstring wide_path = converter.from_bytes(path);
  2025. std::wstring wide_mode = converter.from_bytes(mode);
  2026. return _wfopen(wide_path.c_str(), wide_mode.c_str());
  2027. #else // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
  2028. return fopen(path, mode);
  2029. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
  2030. }
  2031. #if !GTEST_OS_WINDOWS_MOBILE
  2032. inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
  2033. return freopen(path, mode, stream);
  2034. }
  2035. inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
  2036. #endif
  2037. inline int FClose(FILE* fp) { return fclose(fp); }
  2038. #if !GTEST_OS_WINDOWS_MOBILE
  2039. inline int Read(int fd, void* buf, unsigned int count) {
  2040. return static_cast<int>(read(fd, buf, count));
  2041. }
  2042. inline int Write(int fd, const void* buf, unsigned int count) {
  2043. return static_cast<int>(write(fd, buf, count));
  2044. }
  2045. inline int Close(int fd) { return close(fd); }
  2046. inline const char* StrError(int errnum) { return strerror(errnum); }
  2047. #endif
  2048. inline const char* GetEnv(const char* name) {
  2049. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
  2050. GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
  2051. // We are on an embedded platform, which has no environment variables.
  2052. static_cast<void>(name); // To prevent 'unused argument' warning.
  2053. return nullptr;
  2054. #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
  2055. // Environment variables which we programmatically clear will be set to the
  2056. // empty string rather than unset (NULL). Handle that case.
  2057. const char* const env = getenv(name);
  2058. return (env != nullptr && env[0] != '\0') ? env : nullptr;
  2059. #else
  2060. return getenv(name);
  2061. #endif
  2062. }
  2063. GTEST_DISABLE_MSC_DEPRECATED_POP_()
  2064. #if GTEST_OS_WINDOWS_MOBILE
  2065. // Windows CE has no C library. The abort() function is used in
  2066. // several places in Google Test. This implementation provides a reasonable
  2067. // imitation of standard behaviour.
  2068. [[noreturn]] void Abort();
  2069. #else
  2070. [[noreturn]] inline void Abort() { abort(); }
  2071. #endif // GTEST_OS_WINDOWS_MOBILE
  2072. } // namespace posix
  2073. // MSVC "deprecates" snprintf and issues warnings wherever it is used. In
  2074. // order to avoid these warnings, we need to use _snprintf or _snprintf_s on
  2075. // MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate
  2076. // function in order to achieve that. We use macro definition here because
  2077. // snprintf is a variadic function.
  2078. #if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE
  2079. // MSVC 2005 and above support variadic macros.
  2080. # define GTEST_SNPRINTF_(buffer, size, format, ...) \
  2081. _snprintf_s(buffer, size, size, format, __VA_ARGS__)
  2082. #elif defined(_MSC_VER)
  2083. // Windows CE does not define _snprintf_s
  2084. # define GTEST_SNPRINTF_ _snprintf
  2085. #else
  2086. # define GTEST_SNPRINTF_ snprintf
  2087. #endif
  2088. // The biggest signed integer type the compiler supports.
  2089. //
  2090. // long long is guaranteed to be at least 64-bits in C++11.
  2091. using BiggestInt = long long; // NOLINT
  2092. // The maximum number a BiggestInt can represent.
  2093. constexpr BiggestInt kMaxBiggestInt = (std::numeric_limits<BiggestInt>::max)();
  2094. // This template class serves as a compile-time function from size to
  2095. // type. It maps a size in bytes to a primitive type with that
  2096. // size. e.g.
  2097. //
  2098. // TypeWithSize<4>::UInt
  2099. //
  2100. // is typedef-ed to be unsigned int (unsigned integer made up of 4
  2101. // bytes).
  2102. //
  2103. // Such functionality should belong to STL, but I cannot find it
  2104. // there.
  2105. //
  2106. // Google Test uses this class in the implementation of floating-point
  2107. // comparison.
  2108. //
  2109. // For now it only handles UInt (unsigned int) as that's all Google Test
  2110. // needs. Other types can be easily added in the future if need
  2111. // arises.
  2112. template <size_t size>
  2113. class TypeWithSize {
  2114. public:
  2115. // This prevents the user from using TypeWithSize<N> with incorrect
  2116. // values of N.
  2117. using UInt = void;
  2118. };
  2119. // The specialization for size 4.
  2120. template <>
  2121. class TypeWithSize<4> {
  2122. public:
  2123. using Int = std::int32_t;
  2124. using UInt = std::uint32_t;
  2125. };
  2126. // The specialization for size 8.
  2127. template <>
  2128. class TypeWithSize<8> {
  2129. public:
  2130. using Int = std::int64_t;
  2131. using UInt = std::uint64_t;
  2132. };
  2133. // Integer types of known sizes.
  2134. using TimeInMillis = int64_t; // Represents time in milliseconds.
  2135. // Utilities for command line flags and environment variables.
  2136. // Macro for referencing flags.
  2137. #if !defined(GTEST_FLAG)
  2138. # define GTEST_FLAG(name) FLAGS_gtest_##name
  2139. #endif // !defined(GTEST_FLAG)
  2140. #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
  2141. # define GTEST_USE_OWN_FLAGFILE_FLAG_ 1
  2142. #endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
  2143. #if !defined(GTEST_DECLARE_bool_)
  2144. # define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver
  2145. // Macros for declaring flags.
  2146. # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
  2147. # define GTEST_DECLARE_int32_(name) \
  2148. GTEST_API_ extern std::int32_t GTEST_FLAG(name)
  2149. # define GTEST_DECLARE_string_(name) \
  2150. GTEST_API_ extern ::std::string GTEST_FLAG(name)
  2151. // Macros for defining flags.
  2152. # define GTEST_DEFINE_bool_(name, default_val, doc) \
  2153. GTEST_API_ bool GTEST_FLAG(name) = (default_val)
  2154. # define GTEST_DEFINE_int32_(name, default_val, doc) \
  2155. GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val)
  2156. # define GTEST_DEFINE_string_(name, default_val, doc) \
  2157. GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
  2158. #endif // !defined(GTEST_DECLARE_bool_)
  2159. // Thread annotations
  2160. #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
  2161. # define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
  2162. # define GTEST_LOCK_EXCLUDED_(locks)
  2163. #endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
  2164. // Parses 'str' for a 32-bit signed integer. If successful, writes the result
  2165. // to *value and returns true; otherwise leaves *value unchanged and returns
  2166. // false.
  2167. GTEST_API_ bool ParseInt32(const Message& src_text, const char* str,
  2168. int32_t* value);
  2169. // Parses a bool/int32_t/string from the environment variable
  2170. // corresponding to the given Google Test flag.
  2171. bool BoolFromGTestEnv(const char* flag, bool default_val);
  2172. GTEST_API_ int32_t Int32FromGTestEnv(const char* flag, int32_t default_val);
  2173. std::string OutputFlagAlsoCheckEnvVar();
  2174. const char* StringFromGTestEnv(const char* flag, const char* default_val);
  2175. } // namespace internal
  2176. } // namespace testing
  2177. #if !defined(GTEST_INTERNAL_DEPRECATED)
  2178. // Internal Macro to mark an API deprecated, for googletest usage only
  2179. // Usage: class GTEST_INTERNAL_DEPRECATED(message) MyClass or
  2180. // GTEST_INTERNAL_DEPRECATED(message) <return_type> myFunction(); Every usage of
  2181. // a deprecated entity will trigger a warning when compiled with
  2182. // `-Wdeprecated-declarations` option (clang, gcc, any __GNUC__ compiler).
  2183. // For msvc /W3 option will need to be used
  2184. // Note that for 'other' compilers this macro evaluates to nothing to prevent
  2185. // compilations errors.
  2186. #if defined(_MSC_VER)
  2187. #define GTEST_INTERNAL_DEPRECATED(message) __declspec(deprecated(message))
  2188. #elif defined(__GNUC__)
  2189. #define GTEST_INTERNAL_DEPRECATED(message) __attribute__((deprecated(message)))
  2190. #else
  2191. #define GTEST_INTERNAL_DEPRECATED(message)
  2192. #endif
  2193. #endif // !defined(GTEST_INTERNAL_DEPRECATED)
  2194. #if GTEST_HAS_ABSL
  2195. // Always use absl::any for UniversalPrinter<> specializations if googletest
  2196. // is built with absl support.
  2197. #define GTEST_INTERNAL_HAS_ANY 1
  2198. #include "absl/types/any.h"
  2199. namespace testing {
  2200. namespace internal {
  2201. using Any = ::absl::any;
  2202. } // namespace internal
  2203. } // namespace testing
  2204. #else
  2205. #ifdef __has_include
  2206. #if __has_include(<any>) && __cplusplus >= 201703L
  2207. // Otherwise for C++17 and higher use std::any for UniversalPrinter<>
  2208. // specializations.
  2209. #define GTEST_INTERNAL_HAS_ANY 1
  2210. #include <any>
  2211. namespace testing {
  2212. namespace internal {
  2213. using Any = ::std::any;
  2214. } // namespace internal
  2215. } // namespace testing
  2216. // The case where absl is configured NOT to alias std::any is not
  2217. // supported.
  2218. #endif // __has_include(<any>) && __cplusplus >= 201703L
  2219. #endif // __has_include
  2220. #endif // GTEST_HAS_ABSL
  2221. #if GTEST_HAS_ABSL
  2222. // Always use absl::optional for UniversalPrinter<> specializations if
  2223. // googletest is built with absl support.
  2224. #define GTEST_INTERNAL_HAS_OPTIONAL 1
  2225. #include "absl/types/optional.h"
  2226. namespace testing {
  2227. namespace internal {
  2228. template <typename T>
  2229. using Optional = ::absl::optional<T>;
  2230. } // namespace internal
  2231. } // namespace testing
  2232. #else
  2233. #ifdef __has_include
  2234. #if __has_include(<optional>) && __cplusplus >= 201703L
  2235. // Otherwise for C++17 and higher use std::optional for UniversalPrinter<>
  2236. // specializations.
  2237. #define GTEST_INTERNAL_HAS_OPTIONAL 1
  2238. #include <optional>
  2239. namespace testing {
  2240. namespace internal {
  2241. template <typename T>
  2242. using Optional = ::std::optional<T>;
  2243. } // namespace internal
  2244. } // namespace testing
  2245. // The case where absl is configured NOT to alias std::optional is not
  2246. // supported.
  2247. #endif // __has_include(<optional>) && __cplusplus >= 201703L
  2248. #endif // __has_include
  2249. #endif // GTEST_HAS_ABSL
  2250. #if GTEST_HAS_ABSL
  2251. // Always use absl::string_view for Matcher<> specializations if googletest
  2252. // is built with absl support.
  2253. # define GTEST_INTERNAL_HAS_STRING_VIEW 1
  2254. #include "absl/strings/string_view.h"
  2255. namespace testing {
  2256. namespace internal {
  2257. using StringView = ::absl::string_view;
  2258. } // namespace internal
  2259. } // namespace testing
  2260. #else
  2261. # ifdef __has_include
  2262. # if __has_include(<string_view>) && __cplusplus >= 201703L
  2263. // Otherwise for C++17 and higher use std::string_view for Matcher<>
  2264. // specializations.
  2265. # define GTEST_INTERNAL_HAS_STRING_VIEW 1
  2266. #include <string_view>
  2267. namespace testing {
  2268. namespace internal {
  2269. using StringView = ::std::string_view;
  2270. } // namespace internal
  2271. } // namespace testing
  2272. // The case where absl is configured NOT to alias std::string_view is not
  2273. // supported.
  2274. # endif // __has_include(<string_view>) && __cplusplus >= 201703L
  2275. # endif // __has_include
  2276. #endif // GTEST_HAS_ABSL
  2277. #if GTEST_HAS_ABSL
  2278. // Always use absl::variant for UniversalPrinter<> specializations if googletest
  2279. // is built with absl support.
  2280. #define GTEST_INTERNAL_HAS_VARIANT 1
  2281. #include "absl/types/variant.h"
  2282. namespace testing {
  2283. namespace internal {
  2284. template <typename... T>
  2285. using Variant = ::absl::variant<T...>;
  2286. } // namespace internal
  2287. } // namespace testing
  2288. #else
  2289. #ifdef __has_include
  2290. #if __has_include(<variant>) && __cplusplus >= 201703L
  2291. // Otherwise for C++17 and higher use std::variant for UniversalPrinter<>
  2292. // specializations.
  2293. #define GTEST_INTERNAL_HAS_VARIANT 1
  2294. #include <variant>
  2295. namespace testing {
  2296. namespace internal {
  2297. template <typename... T>
  2298. using Variant = ::std::variant<T...>;
  2299. } // namespace internal
  2300. } // namespace testing
  2301. // The case where absl is configured NOT to alias std::variant is not supported.
  2302. #endif // __has_include(<variant>) && __cplusplus >= 201703L
  2303. #endif // __has_include
  2304. #endif // GTEST_HAS_ABSL
  2305. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
  2306. #if GTEST_OS_LINUX
  2307. # include <stdlib.h>
  2308. # include <sys/types.h>
  2309. # include <sys/wait.h>
  2310. # include <unistd.h>
  2311. #endif // GTEST_OS_LINUX
  2312. #if GTEST_HAS_EXCEPTIONS
  2313. # include <stdexcept>
  2314. #endif
  2315. #include <ctype.h>
  2316. #include <float.h>
  2317. #include <string.h>
  2318. #include <cstdint>
  2319. #include <iomanip>
  2320. #include <limits>
  2321. #include <map>
  2322. #include <set>
  2323. #include <string>
  2324. #include <type_traits>
  2325. #include <vector>
  2326. // Copyright 2005, Google Inc.
  2327. // All rights reserved.
  2328. //
  2329. // Redistribution and use in source and binary forms, with or without
  2330. // modification, are permitted provided that the following conditions are
  2331. // met:
  2332. //
  2333. // * Redistributions of source code must retain the above copyright
  2334. // notice, this list of conditions and the following disclaimer.
  2335. // * Redistributions in binary form must reproduce the above
  2336. // copyright notice, this list of conditions and the following disclaimer
  2337. // in the documentation and/or other materials provided with the
  2338. // distribution.
  2339. // * Neither the name of Google Inc. nor the names of its
  2340. // contributors may be used to endorse or promote products derived from
  2341. // this software without specific prior written permission.
  2342. //
  2343. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2344. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2345. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2346. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2347. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2348. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2349. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2350. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2351. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2352. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2353. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2354. //
  2355. // The Google C++ Testing and Mocking Framework (Google Test)
  2356. //
  2357. // This header file defines the Message class.
  2358. //
  2359. // IMPORTANT NOTE: Due to limitation of the C++ language, we have to
  2360. // leave some internal implementation details in this header file.
  2361. // They are clearly marked by comments like this:
  2362. //
  2363. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  2364. //
  2365. // Such code is NOT meant to be used by a user directly, and is subject
  2366. // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
  2367. // program!
  2368. // GOOGLETEST_CM0001 DO NOT DELETE
  2369. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
  2370. #define GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
  2371. #include <limits>
  2372. #include <memory>
  2373. #include <sstream>
  2374. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  2375. /* class A needs to have dll-interface to be used by clients of class B */)
  2376. // Ensures that there is at least one operator<< in the global namespace.
  2377. // See Message& operator<<(...) below for why.
  2378. void operator<<(const testing::internal::Secret&, int);
  2379. namespace testing {
  2380. // The Message class works like an ostream repeater.
  2381. //
  2382. // Typical usage:
  2383. //
  2384. // 1. You stream a bunch of values to a Message object.
  2385. // It will remember the text in a stringstream.
  2386. // 2. Then you stream the Message object to an ostream.
  2387. // This causes the text in the Message to be streamed
  2388. // to the ostream.
  2389. //
  2390. // For example;
  2391. //
  2392. // testing::Message foo;
  2393. // foo << 1 << " != " << 2;
  2394. // std::cout << foo;
  2395. //
  2396. // will print "1 != 2".
  2397. //
  2398. // Message is not intended to be inherited from. In particular, its
  2399. // destructor is not virtual.
  2400. //
  2401. // Note that stringstream behaves differently in gcc and in MSVC. You
  2402. // can stream a NULL char pointer to it in the former, but not in the
  2403. // latter (it causes an access violation if you do). The Message
  2404. // class hides this difference by treating a NULL char pointer as
  2405. // "(null)".
  2406. class GTEST_API_ Message {
  2407. private:
  2408. // The type of basic IO manipulators (endl, ends, and flush) for
  2409. // narrow streams.
  2410. typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&);
  2411. public:
  2412. // Constructs an empty Message.
  2413. Message();
  2414. // Copy constructor.
  2415. Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT
  2416. *ss_ << msg.GetString();
  2417. }
  2418. // Constructs a Message from a C-string.
  2419. explicit Message(const char* str) : ss_(new ::std::stringstream) {
  2420. *ss_ << str;
  2421. }
  2422. // Streams a non-pointer value to this object.
  2423. template <typename T>
  2424. inline Message& operator <<(const T& val) {
  2425. // Some libraries overload << for STL containers. These
  2426. // overloads are defined in the global namespace instead of ::std.
  2427. //
  2428. // C++'s symbol lookup rule (i.e. Koenig lookup) says that these
  2429. // overloads are visible in either the std namespace or the global
  2430. // namespace, but not other namespaces, including the testing
  2431. // namespace which Google Test's Message class is in.
  2432. //
  2433. // To allow STL containers (and other types that has a << operator
  2434. // defined in the global namespace) to be used in Google Test
  2435. // assertions, testing::Message must access the custom << operator
  2436. // from the global namespace. With this using declaration,
  2437. // overloads of << defined in the global namespace and those
  2438. // visible via Koenig lookup are both exposed in this function.
  2439. using ::operator <<;
  2440. *ss_ << val;
  2441. return *this;
  2442. }
  2443. // Streams a pointer value to this object.
  2444. //
  2445. // This function is an overload of the previous one. When you
  2446. // stream a pointer to a Message, this definition will be used as it
  2447. // is more specialized. (The C++ Standard, section
  2448. // [temp.func.order].) If you stream a non-pointer, then the
  2449. // previous definition will be used.
  2450. //
  2451. // The reason for this overload is that streaming a NULL pointer to
  2452. // ostream is undefined behavior. Depending on the compiler, you
  2453. // may get "0", "(nil)", "(null)", or an access violation. To
  2454. // ensure consistent result across compilers, we always treat NULL
  2455. // as "(null)".
  2456. template <typename T>
  2457. inline Message& operator <<(T* const& pointer) { // NOLINT
  2458. if (pointer == nullptr) {
  2459. *ss_ << "(null)";
  2460. } else {
  2461. *ss_ << pointer;
  2462. }
  2463. return *this;
  2464. }
  2465. // Since the basic IO manipulators are overloaded for both narrow
  2466. // and wide streams, we have to provide this specialized definition
  2467. // of operator <<, even though its body is the same as the
  2468. // templatized version above. Without this definition, streaming
  2469. // endl or other basic IO manipulators to Message will confuse the
  2470. // compiler.
  2471. Message& operator <<(BasicNarrowIoManip val) {
  2472. *ss_ << val;
  2473. return *this;
  2474. }
  2475. // Instead of 1/0, we want to see true/false for bool values.
  2476. Message& operator <<(bool b) {
  2477. return *this << (b ? "true" : "false");
  2478. }
  2479. // These two overloads allow streaming a wide C string to a Message
  2480. // using the UTF-8 encoding.
  2481. Message& operator <<(const wchar_t* wide_c_str);
  2482. Message& operator <<(wchar_t* wide_c_str);
  2483. #if GTEST_HAS_STD_WSTRING
  2484. // Converts the given wide string to a narrow string using the UTF-8
  2485. // encoding, and streams the result to this Message object.
  2486. Message& operator <<(const ::std::wstring& wstr);
  2487. #endif // GTEST_HAS_STD_WSTRING
  2488. // Gets the text streamed to this object so far as an std::string.
  2489. // Each '\0' character in the buffer is replaced with "\\0".
  2490. //
  2491. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  2492. std::string GetString() const;
  2493. private:
  2494. // We'll hold the text streamed to this object here.
  2495. const std::unique_ptr< ::std::stringstream> ss_;
  2496. // We declare (but don't implement) this to prevent the compiler
  2497. // from implementing the assignment operator.
  2498. void operator=(const Message&);
  2499. };
  2500. // Streams a Message to an ostream.
  2501. inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
  2502. return os << sb.GetString();
  2503. }
  2504. namespace internal {
  2505. // Converts a streamable value to an std::string. A NULL pointer is
  2506. // converted to "(null)". When the input value is a ::string,
  2507. // ::std::string, ::wstring, or ::std::wstring object, each NUL
  2508. // character in it is replaced with "\\0".
  2509. template <typename T>
  2510. std::string StreamableToString(const T& streamable) {
  2511. return (Message() << streamable).GetString();
  2512. }
  2513. } // namespace internal
  2514. } // namespace testing
  2515. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  2516. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
  2517. // Copyright 2008, Google Inc.
  2518. // All rights reserved.
  2519. //
  2520. // Redistribution and use in source and binary forms, with or without
  2521. // modification, are permitted provided that the following conditions are
  2522. // met:
  2523. //
  2524. // * Redistributions of source code must retain the above copyright
  2525. // notice, this list of conditions and the following disclaimer.
  2526. // * Redistributions in binary form must reproduce the above
  2527. // copyright notice, this list of conditions and the following disclaimer
  2528. // in the documentation and/or other materials provided with the
  2529. // distribution.
  2530. // * Neither the name of Google Inc. nor the names of its
  2531. // contributors may be used to endorse or promote products derived from
  2532. // this software without specific prior written permission.
  2533. //
  2534. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2535. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2536. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2537. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2538. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2539. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2540. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2541. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2542. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2543. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2544. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2545. //
  2546. // Google Test filepath utilities
  2547. //
  2548. // This header file declares classes and functions used internally by
  2549. // Google Test. They are subject to change without notice.
  2550. //
  2551. // This file is #included in gtest/internal/gtest-internal.h.
  2552. // Do not include this header file separately!
  2553. // GOOGLETEST_CM0001 DO NOT DELETE
  2554. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
  2555. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
  2556. // Copyright 2005, Google Inc.
  2557. // All rights reserved.
  2558. //
  2559. // Redistribution and use in source and binary forms, with or without
  2560. // modification, are permitted provided that the following conditions are
  2561. // met:
  2562. //
  2563. // * Redistributions of source code must retain the above copyright
  2564. // notice, this list of conditions and the following disclaimer.
  2565. // * Redistributions in binary form must reproduce the above
  2566. // copyright notice, this list of conditions and the following disclaimer
  2567. // in the documentation and/or other materials provided with the
  2568. // distribution.
  2569. // * Neither the name of Google Inc. nor the names of its
  2570. // contributors may be used to endorse or promote products derived from
  2571. // this software without specific prior written permission.
  2572. //
  2573. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2574. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2575. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2576. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2577. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2578. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2579. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2580. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2581. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2582. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2583. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2584. //
  2585. // The Google C++ Testing and Mocking Framework (Google Test)
  2586. //
  2587. // This header file declares the String class and functions used internally by
  2588. // Google Test. They are subject to change without notice. They should not used
  2589. // by code external to Google Test.
  2590. //
  2591. // This header file is #included by gtest-internal.h.
  2592. // It should not be #included by other files.
  2593. // GOOGLETEST_CM0001 DO NOT DELETE
  2594. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
  2595. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
  2596. #ifdef __BORLANDC__
  2597. // string.h is not guaranteed to provide strcpy on C++ Builder.
  2598. # include <mem.h>
  2599. #endif
  2600. #include <string.h>
  2601. #include <cstdint>
  2602. #include <string>
  2603. namespace testing {
  2604. namespace internal {
  2605. // String - an abstract class holding static string utilities.
  2606. class GTEST_API_ String {
  2607. public:
  2608. // Static utility methods
  2609. // Clones a 0-terminated C string, allocating memory using new. The
  2610. // caller is responsible for deleting the return value using
  2611. // delete[]. Returns the cloned string, or NULL if the input is
  2612. // NULL.
  2613. //
  2614. // This is different from strdup() in string.h, which allocates
  2615. // memory using malloc().
  2616. static const char* CloneCString(const char* c_str);
  2617. #if GTEST_OS_WINDOWS_MOBILE
  2618. // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
  2619. // able to pass strings to Win32 APIs on CE we need to convert them
  2620. // to 'Unicode', UTF-16.
  2621. // Creates a UTF-16 wide string from the given ANSI string, allocating
  2622. // memory using new. The caller is responsible for deleting the return
  2623. // value using delete[]. Returns the wide string, or NULL if the
  2624. // input is NULL.
  2625. //
  2626. // The wide string is created using the ANSI codepage (CP_ACP) to
  2627. // match the behaviour of the ANSI versions of Win32 calls and the
  2628. // C runtime.
  2629. static LPCWSTR AnsiToUtf16(const char* c_str);
  2630. // Creates an ANSI string from the given wide string, allocating
  2631. // memory using new. The caller is responsible for deleting the return
  2632. // value using delete[]. Returns the ANSI string, or NULL if the
  2633. // input is NULL.
  2634. //
  2635. // The returned string is created using the ANSI codepage (CP_ACP) to
  2636. // match the behaviour of the ANSI versions of Win32 calls and the
  2637. // C runtime.
  2638. static const char* Utf16ToAnsi(LPCWSTR utf16_str);
  2639. #endif
  2640. // Compares two C strings. Returns true if and only if they have the same
  2641. // content.
  2642. //
  2643. // Unlike strcmp(), this function can handle NULL argument(s). A
  2644. // NULL C string is considered different to any non-NULL C string,
  2645. // including the empty string.
  2646. static bool CStringEquals(const char* lhs, const char* rhs);
  2647. // Converts a wide C string to a String using the UTF-8 encoding.
  2648. // NULL will be converted to "(null)". If an error occurred during
  2649. // the conversion, "(failed to convert from wide string)" is
  2650. // returned.
  2651. static std::string ShowWideCString(const wchar_t* wide_c_str);
  2652. // Compares two wide C strings. Returns true if and only if they have the
  2653. // same content.
  2654. //
  2655. // Unlike wcscmp(), this function can handle NULL argument(s). A
  2656. // NULL C string is considered different to any non-NULL C string,
  2657. // including the empty string.
  2658. static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
  2659. // Compares two C strings, ignoring case. Returns true if and only if
  2660. // they have the same content.
  2661. //
  2662. // Unlike strcasecmp(), this function can handle NULL argument(s).
  2663. // A NULL C string is considered different to any non-NULL C string,
  2664. // including the empty string.
  2665. static bool CaseInsensitiveCStringEquals(const char* lhs,
  2666. const char* rhs);
  2667. // Compares two wide C strings, ignoring case. Returns true if and only if
  2668. // they have the same content.
  2669. //
  2670. // Unlike wcscasecmp(), this function can handle NULL argument(s).
  2671. // A NULL C string is considered different to any non-NULL wide C string,
  2672. // including the empty string.
  2673. // NB: The implementations on different platforms slightly differ.
  2674. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  2675. // environment variable. On GNU platform this method uses wcscasecmp
  2676. // which compares according to LC_CTYPE category of the current locale.
  2677. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  2678. // current locale.
  2679. static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  2680. const wchar_t* rhs);
  2681. // Returns true if and only if the given string ends with the given suffix,
  2682. // ignoring case. Any string is considered to end with an empty suffix.
  2683. static bool EndsWithCaseInsensitive(
  2684. const std::string& str, const std::string& suffix);
  2685. // Formats an int value as "%02d".
  2686. static std::string FormatIntWidth2(int value); // "%02d" for width == 2
  2687. // Formats an int value to given width with leading zeros.
  2688. static std::string FormatIntWidthN(int value, int width);
  2689. // Formats an int value as "%X".
  2690. static std::string FormatHexInt(int value);
  2691. // Formats an int value as "%X".
  2692. static std::string FormatHexUInt32(uint32_t value);
  2693. // Formats a byte as "%02X".
  2694. static std::string FormatByte(unsigned char value);
  2695. private:
  2696. String(); // Not meant to be instantiated.
  2697. }; // class String
  2698. // Gets the content of the stringstream's buffer as an std::string. Each '\0'
  2699. // character in the buffer is replaced with "\\0".
  2700. GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
  2701. } // namespace internal
  2702. } // namespace testing
  2703. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
  2704. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  2705. /* class A needs to have dll-interface to be used by clients of class B */)
  2706. namespace testing {
  2707. namespace internal {
  2708. // FilePath - a class for file and directory pathname manipulation which
  2709. // handles platform-specific conventions (like the pathname separator).
  2710. // Used for helper functions for naming files in a directory for xml output.
  2711. // Except for Set methods, all methods are const or static, which provides an
  2712. // "immutable value object" -- useful for peace of mind.
  2713. // A FilePath with a value ending in a path separator ("like/this/") represents
  2714. // a directory, otherwise it is assumed to represent a file. In either case,
  2715. // it may or may not represent an actual file or directory in the file system.
  2716. // Names are NOT checked for syntax correctness -- no checking for illegal
  2717. // characters, malformed paths, etc.
  2718. class GTEST_API_ FilePath {
  2719. public:
  2720. FilePath() : pathname_("") { }
  2721. FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
  2722. explicit FilePath(const std::string& pathname) : pathname_(pathname) {
  2723. Normalize();
  2724. }
  2725. FilePath& operator=(const FilePath& rhs) {
  2726. Set(rhs);
  2727. return *this;
  2728. }
  2729. void Set(const FilePath& rhs) {
  2730. pathname_ = rhs.pathname_;
  2731. }
  2732. const std::string& string() const { return pathname_; }
  2733. const char* c_str() const { return pathname_.c_str(); }
  2734. // Returns the current working directory, or "" if unsuccessful.
  2735. static FilePath GetCurrentDir();
  2736. // Given directory = "dir", base_name = "test", number = 0,
  2737. // extension = "xml", returns "dir/test.xml". If number is greater
  2738. // than zero (e.g., 12), returns "dir/test_12.xml".
  2739. // On Windows platform, uses \ as the separator rather than /.
  2740. static FilePath MakeFileName(const FilePath& directory,
  2741. const FilePath& base_name,
  2742. int number,
  2743. const char* extension);
  2744. // Given directory = "dir", relative_path = "test.xml",
  2745. // returns "dir/test.xml".
  2746. // On Windows, uses \ as the separator rather than /.
  2747. static FilePath ConcatPaths(const FilePath& directory,
  2748. const FilePath& relative_path);
  2749. // Returns a pathname for a file that does not currently exist. The pathname
  2750. // will be directory/base_name.extension or
  2751. // directory/base_name_<number>.extension if directory/base_name.extension
  2752. // already exists. The number will be incremented until a pathname is found
  2753. // that does not already exist.
  2754. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
  2755. // There could be a race condition if two or more processes are calling this
  2756. // function at the same time -- they could both pick the same filename.
  2757. static FilePath GenerateUniqueFileName(const FilePath& directory,
  2758. const FilePath& base_name,
  2759. const char* extension);
  2760. // Returns true if and only if the path is "".
  2761. bool IsEmpty() const { return pathname_.empty(); }
  2762. // If input name has a trailing separator character, removes it and returns
  2763. // the name, otherwise return the name string unmodified.
  2764. // On Windows platform, uses \ as the separator, other platforms use /.
  2765. FilePath RemoveTrailingPathSeparator() const;
  2766. // Returns a copy of the FilePath with the directory part removed.
  2767. // Example: FilePath("path/to/file").RemoveDirectoryName() returns
  2768. // FilePath("file"). If there is no directory part ("just_a_file"), it returns
  2769. // the FilePath unmodified. If there is no file part ("just_a_dir/") it
  2770. // returns an empty FilePath ("").
  2771. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  2772. FilePath RemoveDirectoryName() const;
  2773. // RemoveFileName returns the directory path with the filename removed.
  2774. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
  2775. // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
  2776. // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
  2777. // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
  2778. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  2779. FilePath RemoveFileName() const;
  2780. // Returns a copy of the FilePath with the case-insensitive extension removed.
  2781. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
  2782. // FilePath("dir/file"). If a case-insensitive extension is not
  2783. // found, returns a copy of the original FilePath.
  2784. FilePath RemoveExtension(const char* extension) const;
  2785. // Creates directories so that path exists. Returns true if successful or if
  2786. // the directories already exist; returns false if unable to create
  2787. // directories for any reason. Will also return false if the FilePath does
  2788. // not represent a directory (that is, it doesn't end with a path separator).
  2789. bool CreateDirectoriesRecursively() const;
  2790. // Create the directory so that path exists. Returns true if successful or
  2791. // if the directory already exists; returns false if unable to create the
  2792. // directory for any reason, including if the parent directory does not
  2793. // exist. Not named "CreateDirectory" because that's a macro on Windows.
  2794. bool CreateFolder() const;
  2795. // Returns true if FilePath describes something in the file-system,
  2796. // either a file, directory, or whatever, and that something exists.
  2797. bool FileOrDirectoryExists() const;
  2798. // Returns true if pathname describes a directory in the file-system
  2799. // that exists.
  2800. bool DirectoryExists() const;
  2801. // Returns true if FilePath ends with a path separator, which indicates that
  2802. // it is intended to represent a directory. Returns false otherwise.
  2803. // This does NOT check that a directory (or file) actually exists.
  2804. bool IsDirectory() const;
  2805. // Returns true if pathname describes a root directory. (Windows has one
  2806. // root directory per disk drive.)
  2807. bool IsRootDirectory() const;
  2808. // Returns true if pathname describes an absolute path.
  2809. bool IsAbsolutePath() const;
  2810. private:
  2811. // Replaces multiple consecutive separators with a single separator.
  2812. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
  2813. // redundancies that might be in a pathname involving "." or "..".
  2814. //
  2815. // A pathname with multiple consecutive separators may occur either through
  2816. // user error or as a result of some scripts or APIs that generate a pathname
  2817. // with a trailing separator. On other platforms the same API or script
  2818. // may NOT generate a pathname with a trailing "/". Then elsewhere that
  2819. // pathname may have another "/" and pathname components added to it,
  2820. // without checking for the separator already being there.
  2821. // The script language and operating system may allow paths like "foo//bar"
  2822. // but some of the functions in FilePath will not handle that correctly. In
  2823. // particular, RemoveTrailingPathSeparator() only removes one separator, and
  2824. // it is called in CreateDirectoriesRecursively() assuming that it will change
  2825. // a pathname from directory syntax (trailing separator) to filename syntax.
  2826. //
  2827. // On Windows this method also replaces the alternate path separator '/' with
  2828. // the primary path separator '\\', so that for example "bar\\/\\foo" becomes
  2829. // "bar\\foo".
  2830. void Normalize();
  2831. // Returns a pointer to the last occurrence of a valid path separator in
  2832. // the FilePath. On Windows, for example, both '/' and '\' are valid path
  2833. // separators. Returns NULL if no path separator was found.
  2834. const char* FindLastPathSeparator() const;
  2835. std::string pathname_;
  2836. }; // class FilePath
  2837. } // namespace internal
  2838. } // namespace testing
  2839. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  2840. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
  2841. // Copyright 2008 Google Inc.
  2842. // All Rights Reserved.
  2843. //
  2844. // Redistribution and use in source and binary forms, with or without
  2845. // modification, are permitted provided that the following conditions are
  2846. // met:
  2847. //
  2848. // * Redistributions of source code must retain the above copyright
  2849. // notice, this list of conditions and the following disclaimer.
  2850. // * Redistributions in binary form must reproduce the above
  2851. // copyright notice, this list of conditions and the following disclaimer
  2852. // in the documentation and/or other materials provided with the
  2853. // distribution.
  2854. // * Neither the name of Google Inc. nor the names of its
  2855. // contributors may be used to endorse or promote products derived from
  2856. // this software without specific prior written permission.
  2857. //
  2858. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2859. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2860. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2861. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2862. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2863. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2864. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2865. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2866. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2867. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2868. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2869. // Type utilities needed for implementing typed and type-parameterized
  2870. // tests.
  2871. // GOOGLETEST_CM0001 DO NOT DELETE
  2872. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
  2873. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
  2874. // #ifdef __GNUC__ is too general here. It is possible to use gcc without using
  2875. // libstdc++ (which is where cxxabi.h comes from).
  2876. # if GTEST_HAS_CXXABI_H_
  2877. # include <cxxabi.h>
  2878. # elif defined(__HP_aCC)
  2879. # include <acxx_demangle.h>
  2880. # endif // GTEST_HASH_CXXABI_H_
  2881. namespace testing {
  2882. namespace internal {
  2883. // Canonicalizes a given name with respect to the Standard C++ Library.
  2884. // This handles removing the inline namespace within `std` that is
  2885. // used by various standard libraries (e.g., `std::__1`). Names outside
  2886. // of namespace std are returned unmodified.
  2887. inline std::string CanonicalizeForStdLibVersioning(std::string s) {
  2888. static const char prefix[] = "std::__";
  2889. if (s.compare(0, strlen(prefix), prefix) == 0) {
  2890. std::string::size_type end = s.find("::", strlen(prefix));
  2891. if (end != s.npos) {
  2892. // Erase everything between the initial `std` and the second `::`.
  2893. s.erase(strlen("std"), end - strlen("std"));
  2894. }
  2895. }
  2896. return s;
  2897. }
  2898. #if GTEST_HAS_RTTI
  2899. // GetTypeName(const std::type_info&) returns a human-readable name of type T.
  2900. inline std::string GetTypeName(const std::type_info& type) {
  2901. const char* const name = type.name();
  2902. #if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
  2903. int status = 0;
  2904. // gcc's implementation of typeid(T).name() mangles the type name,
  2905. // so we have to demangle it.
  2906. #if GTEST_HAS_CXXABI_H_
  2907. using abi::__cxa_demangle;
  2908. #endif // GTEST_HAS_CXXABI_H_
  2909. char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status);
  2910. const std::string name_str(status == 0 ? readable_name : name);
  2911. free(readable_name);
  2912. return CanonicalizeForStdLibVersioning(name_str);
  2913. #else
  2914. return name;
  2915. #endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
  2916. }
  2917. #endif // GTEST_HAS_RTTI
  2918. // GetTypeName<T>() returns a human-readable name of type T if and only if
  2919. // RTTI is enabled, otherwise it returns a dummy type name.
  2920. // NB: This function is also used in Google Mock, so don't move it inside of
  2921. // the typed-test-only section below.
  2922. template <typename T>
  2923. std::string GetTypeName() {
  2924. #if GTEST_HAS_RTTI
  2925. return GetTypeName(typeid(T));
  2926. #else
  2927. return "<type>";
  2928. #endif // GTEST_HAS_RTTI
  2929. }
  2930. // A unique type indicating an empty node
  2931. struct None {};
  2932. # define GTEST_TEMPLATE_ template <typename T> class
  2933. // The template "selector" struct TemplateSel<Tmpl> is used to
  2934. // represent Tmpl, which must be a class template with one type
  2935. // parameter, as a type. TemplateSel<Tmpl>::Bind<T>::type is defined
  2936. // as the type Tmpl<T>. This allows us to actually instantiate the
  2937. // template "selected" by TemplateSel<Tmpl>.
  2938. //
  2939. // This trick is necessary for simulating typedef for class templates,
  2940. // which C++ doesn't support directly.
  2941. template <GTEST_TEMPLATE_ Tmpl>
  2942. struct TemplateSel {
  2943. template <typename T>
  2944. struct Bind {
  2945. typedef Tmpl<T> type;
  2946. };
  2947. };
  2948. # define GTEST_BIND_(TmplSel, T) \
  2949. TmplSel::template Bind<T>::type
  2950. template <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_>
  2951. struct Templates {
  2952. using Head = TemplateSel<Head_>;
  2953. using Tail = Templates<Tail_...>;
  2954. };
  2955. template <GTEST_TEMPLATE_ Head_>
  2956. struct Templates<Head_> {
  2957. using Head = TemplateSel<Head_>;
  2958. using Tail = None;
  2959. };
  2960. // Tuple-like type lists
  2961. template <typename Head_, typename... Tail_>
  2962. struct Types {
  2963. using Head = Head_;
  2964. using Tail = Types<Tail_...>;
  2965. };
  2966. template <typename Head_>
  2967. struct Types<Head_> {
  2968. using Head = Head_;
  2969. using Tail = None;
  2970. };
  2971. // Helper metafunctions to tell apart a single type from types
  2972. // generated by ::testing::Types
  2973. template <typename... Ts>
  2974. struct ProxyTypeList {
  2975. using type = Types<Ts...>;
  2976. };
  2977. template <typename>
  2978. struct is_proxy_type_list : std::false_type {};
  2979. template <typename... Ts>
  2980. struct is_proxy_type_list<ProxyTypeList<Ts...>> : std::true_type {};
  2981. // Generator which conditionally creates type lists.
  2982. // It recognizes if a requested type list should be created
  2983. // and prevents creating a new type list nested within another one.
  2984. template <typename T>
  2985. struct GenerateTypeList {
  2986. private:
  2987. using proxy = typename std::conditional<is_proxy_type_list<T>::value, T,
  2988. ProxyTypeList<T>>::type;
  2989. public:
  2990. using type = typename proxy::type;
  2991. };
  2992. } // namespace internal
  2993. template <typename... Ts>
  2994. using Types = internal::ProxyTypeList<Ts...>;
  2995. } // namespace testing
  2996. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
  2997. // Due to C++ preprocessor weirdness, we need double indirection to
  2998. // concatenate two tokens when one of them is __LINE__. Writing
  2999. //
  3000. // foo ## __LINE__
  3001. //
  3002. // will result in the token foo__LINE__, instead of foo followed by
  3003. // the current line number. For more details, see
  3004. // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
  3005. #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
  3006. #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
  3007. // Stringifies its argument.
  3008. // Work around a bug in visual studio which doesn't accept code like this:
  3009. //
  3010. // #define GTEST_STRINGIFY_(name) #name
  3011. // #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...
  3012. // MACRO(, x, y)
  3013. //
  3014. // Complaining about the argument to GTEST_STRINGIFY_ being empty.
  3015. // This is allowed by the spec.
  3016. #define GTEST_STRINGIFY_HELPER_(name, ...) #name
  3017. #define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
  3018. namespace proto2 {
  3019. class MessageLite;
  3020. }
  3021. namespace testing {
  3022. // Forward declarations.
  3023. class AssertionResult; // Result of an assertion.
  3024. class Message; // Represents a failure message.
  3025. class Test; // Represents a test.
  3026. class TestInfo; // Information about a test.
  3027. class TestPartResult; // Result of a test part.
  3028. class UnitTest; // A collection of test suites.
  3029. template <typename T>
  3030. ::std::string PrintToString(const T& value);
  3031. namespace internal {
  3032. struct TraceInfo; // Information about a trace point.
  3033. class TestInfoImpl; // Opaque implementation of TestInfo
  3034. class UnitTestImpl; // Opaque implementation of UnitTest
  3035. // The text used in failure messages to indicate the start of the
  3036. // stack trace.
  3037. GTEST_API_ extern const char kStackTraceMarker[];
  3038. // An IgnoredValue object can be implicitly constructed from ANY value.
  3039. class IgnoredValue {
  3040. struct Sink {};
  3041. public:
  3042. // This constructor template allows any value to be implicitly
  3043. // converted to IgnoredValue. The object has no data member and
  3044. // doesn't try to remember anything about the argument. We
  3045. // deliberately omit the 'explicit' keyword in order to allow the
  3046. // conversion to be implicit.
  3047. // Disable the conversion if T already has a magical conversion operator.
  3048. // Otherwise we get ambiguity.
  3049. template <typename T,
  3050. typename std::enable_if<!std::is_convertible<T, Sink>::value,
  3051. int>::type = 0>
  3052. IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)
  3053. };
  3054. // Appends the user-supplied message to the Google-Test-generated message.
  3055. GTEST_API_ std::string AppendUserMessage(
  3056. const std::string& gtest_msg, const Message& user_msg);
  3057. #if GTEST_HAS_EXCEPTIONS
  3058. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
  3059. /* an exported class was derived from a class that was not exported */)
  3060. // This exception is thrown by (and only by) a failed Google Test
  3061. // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
  3062. // are enabled). We derive it from std::runtime_error, which is for
  3063. // errors presumably detectable only at run time. Since
  3064. // std::runtime_error inherits from std::exception, many testing
  3065. // frameworks know how to extract and print the message inside it.
  3066. class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
  3067. public:
  3068. explicit GoogleTestFailureException(const TestPartResult& failure);
  3069. };
  3070. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275
  3071. #endif // GTEST_HAS_EXCEPTIONS
  3072. namespace edit_distance {
  3073. // Returns the optimal edits to go from 'left' to 'right'.
  3074. // All edits cost the same, with replace having lower priority than
  3075. // add/remove.
  3076. // Simple implementation of the Wagner-Fischer algorithm.
  3077. // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
  3078. enum EditType { kMatch, kAdd, kRemove, kReplace };
  3079. GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
  3080. const std::vector<size_t>& left, const std::vector<size_t>& right);
  3081. // Same as above, but the input is represented as strings.
  3082. GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
  3083. const std::vector<std::string>& left,
  3084. const std::vector<std::string>& right);
  3085. // Create a diff of the input strings in Unified diff format.
  3086. GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
  3087. const std::vector<std::string>& right,
  3088. size_t context = 2);
  3089. } // namespace edit_distance
  3090. // Calculate the diff between 'left' and 'right' and return it in unified diff
  3091. // format.
  3092. // If not null, stores in 'total_line_count' the total number of lines found
  3093. // in left + right.
  3094. GTEST_API_ std::string DiffStrings(const std::string& left,
  3095. const std::string& right,
  3096. size_t* total_line_count);
  3097. // Constructs and returns the message for an equality assertion
  3098. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  3099. //
  3100. // The first four parameters are the expressions used in the assertion
  3101. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  3102. // where foo is 5 and bar is 6, we have:
  3103. //
  3104. // expected_expression: "foo"
  3105. // actual_expression: "bar"
  3106. // expected_value: "5"
  3107. // actual_value: "6"
  3108. //
  3109. // The ignoring_case parameter is true if and only if the assertion is a
  3110. // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
  3111. // be inserted into the message.
  3112. GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
  3113. const char* actual_expression,
  3114. const std::string& expected_value,
  3115. const std::string& actual_value,
  3116. bool ignoring_case);
  3117. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  3118. GTEST_API_ std::string GetBoolAssertionFailureMessage(
  3119. const AssertionResult& assertion_result,
  3120. const char* expression_text,
  3121. const char* actual_predicate_value,
  3122. const char* expected_predicate_value);
  3123. // This template class represents an IEEE floating-point number
  3124. // (either single-precision or double-precision, depending on the
  3125. // template parameters).
  3126. //
  3127. // The purpose of this class is to do more sophisticated number
  3128. // comparison. (Due to round-off error, etc, it's very unlikely that
  3129. // two floating-points will be equal exactly. Hence a naive
  3130. // comparison by the == operation often doesn't work.)
  3131. //
  3132. // Format of IEEE floating-point:
  3133. //
  3134. // The most-significant bit being the leftmost, an IEEE
  3135. // floating-point looks like
  3136. //
  3137. // sign_bit exponent_bits fraction_bits
  3138. //
  3139. // Here, sign_bit is a single bit that designates the sign of the
  3140. // number.
  3141. //
  3142. // For float, there are 8 exponent bits and 23 fraction bits.
  3143. //
  3144. // For double, there are 11 exponent bits and 52 fraction bits.
  3145. //
  3146. // More details can be found at
  3147. // http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
  3148. //
  3149. // Template parameter:
  3150. //
  3151. // RawType: the raw floating-point type (either float or double)
  3152. template <typename RawType>
  3153. class FloatingPoint {
  3154. public:
  3155. // Defines the unsigned integer type that has the same size as the
  3156. // floating point number.
  3157. typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
  3158. // Constants.
  3159. // # of bits in a number.
  3160. static const size_t kBitCount = 8*sizeof(RawType);
  3161. // # of fraction bits in a number.
  3162. static const size_t kFractionBitCount =
  3163. std::numeric_limits<RawType>::digits - 1;
  3164. // # of exponent bits in a number.
  3165. static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
  3166. // The mask for the sign bit.
  3167. static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
  3168. // The mask for the fraction bits.
  3169. static const Bits kFractionBitMask =
  3170. ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
  3171. // The mask for the exponent bits.
  3172. static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
  3173. // How many ULP's (Units in the Last Place) we want to tolerate when
  3174. // comparing two numbers. The larger the value, the more error we
  3175. // allow. A 0 value means that two numbers must be exactly the same
  3176. // to be considered equal.
  3177. //
  3178. // The maximum error of a single floating-point operation is 0.5
  3179. // units in the last place. On Intel CPU's, all floating-point
  3180. // calculations are done with 80-bit precision, while double has 64
  3181. // bits. Therefore, 4 should be enough for ordinary use.
  3182. //
  3183. // See the following article for more details on ULP:
  3184. // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
  3185. static const uint32_t kMaxUlps = 4;
  3186. // Constructs a FloatingPoint from a raw floating-point number.
  3187. //
  3188. // On an Intel CPU, passing a non-normalized NAN (Not a Number)
  3189. // around may change its bits, although the new value is guaranteed
  3190. // to be also a NAN. Therefore, don't expect this constructor to
  3191. // preserve the bits in x when x is a NAN.
  3192. explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
  3193. // Static methods
  3194. // Reinterprets a bit pattern as a floating-point number.
  3195. //
  3196. // This function is needed to test the AlmostEquals() method.
  3197. static RawType ReinterpretBits(const Bits bits) {
  3198. FloatingPoint fp(0);
  3199. fp.u_.bits_ = bits;
  3200. return fp.u_.value_;
  3201. }
  3202. // Returns the floating-point number that represent positive infinity.
  3203. static RawType Infinity() {
  3204. return ReinterpretBits(kExponentBitMask);
  3205. }
  3206. // Returns the maximum representable finite floating-point number.
  3207. static RawType Max();
  3208. // Non-static methods
  3209. // Returns the bits that represents this number.
  3210. const Bits &bits() const { return u_.bits_; }
  3211. // Returns the exponent bits of this number.
  3212. Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
  3213. // Returns the fraction bits of this number.
  3214. Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
  3215. // Returns the sign bit of this number.
  3216. Bits sign_bit() const { return kSignBitMask & u_.bits_; }
  3217. // Returns true if and only if this is NAN (not a number).
  3218. bool is_nan() const {
  3219. // It's a NAN if the exponent bits are all ones and the fraction
  3220. // bits are not entirely zeros.
  3221. return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
  3222. }
  3223. // Returns true if and only if this number is at most kMaxUlps ULP's away
  3224. // from rhs. In particular, this function:
  3225. //
  3226. // - returns false if either number is (or both are) NAN.
  3227. // - treats really large numbers as almost equal to infinity.
  3228. // - thinks +0.0 and -0.0 are 0 DLP's apart.
  3229. bool AlmostEquals(const FloatingPoint& rhs) const {
  3230. // The IEEE standard says that any comparison operation involving
  3231. // a NAN must return false.
  3232. if (is_nan() || rhs.is_nan()) return false;
  3233. return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
  3234. <= kMaxUlps;
  3235. }
  3236. private:
  3237. // The data type used to store the actual floating-point number.
  3238. union FloatingPointUnion {
  3239. RawType value_; // The raw floating-point number.
  3240. Bits bits_; // The bits that represent the number.
  3241. };
  3242. // Converts an integer from the sign-and-magnitude representation to
  3243. // the biased representation. More precisely, let N be 2 to the
  3244. // power of (kBitCount - 1), an integer x is represented by the
  3245. // unsigned number x + N.
  3246. //
  3247. // For instance,
  3248. //
  3249. // -N + 1 (the most negative number representable using
  3250. // sign-and-magnitude) is represented by 1;
  3251. // 0 is represented by N; and
  3252. // N - 1 (the biggest number representable using
  3253. // sign-and-magnitude) is represented by 2N - 1.
  3254. //
  3255. // Read http://en.wikipedia.org/wiki/Signed_number_representations
  3256. // for more details on signed number representations.
  3257. static Bits SignAndMagnitudeToBiased(const Bits &sam) {
  3258. if (kSignBitMask & sam) {
  3259. // sam represents a negative number.
  3260. return ~sam + 1;
  3261. } else {
  3262. // sam represents a positive number.
  3263. return kSignBitMask | sam;
  3264. }
  3265. }
  3266. // Given two numbers in the sign-and-magnitude representation,
  3267. // returns the distance between them as an unsigned number.
  3268. static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
  3269. const Bits &sam2) {
  3270. const Bits biased1 = SignAndMagnitudeToBiased(sam1);
  3271. const Bits biased2 = SignAndMagnitudeToBiased(sam2);
  3272. return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
  3273. }
  3274. FloatingPointUnion u_;
  3275. };
  3276. // We cannot use std::numeric_limits<T>::max() as it clashes with the max()
  3277. // macro defined by <windows.h>.
  3278. template <>
  3279. inline float FloatingPoint<float>::Max() { return FLT_MAX; }
  3280. template <>
  3281. inline double FloatingPoint<double>::Max() { return DBL_MAX; }
  3282. // Typedefs the instances of the FloatingPoint template class that we
  3283. // care to use.
  3284. typedef FloatingPoint<float> Float;
  3285. typedef FloatingPoint<double> Double;
  3286. // In order to catch the mistake of putting tests that use different
  3287. // test fixture classes in the same test suite, we need to assign
  3288. // unique IDs to fixture classes and compare them. The TypeId type is
  3289. // used to hold such IDs. The user should treat TypeId as an opaque
  3290. // type: the only operation allowed on TypeId values is to compare
  3291. // them for equality using the == operator.
  3292. typedef const void* TypeId;
  3293. template <typename T>
  3294. class TypeIdHelper {
  3295. public:
  3296. // dummy_ must not have a const type. Otherwise an overly eager
  3297. // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
  3298. // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
  3299. static bool dummy_;
  3300. };
  3301. template <typename T>
  3302. bool TypeIdHelper<T>::dummy_ = false;
  3303. // GetTypeId<T>() returns the ID of type T. Different values will be
  3304. // returned for different types. Calling the function twice with the
  3305. // same type argument is guaranteed to return the same ID.
  3306. template <typename T>
  3307. TypeId GetTypeId() {
  3308. // The compiler is required to allocate a different
  3309. // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
  3310. // the template. Therefore, the address of dummy_ is guaranteed to
  3311. // be unique.
  3312. return &(TypeIdHelper<T>::dummy_);
  3313. }
  3314. // Returns the type ID of ::testing::Test. Always call this instead
  3315. // of GetTypeId< ::testing::Test>() to get the type ID of
  3316. // ::testing::Test, as the latter may give the wrong result due to a
  3317. // suspected linker bug when compiling Google Test as a Mac OS X
  3318. // framework.
  3319. GTEST_API_ TypeId GetTestTypeId();
  3320. // Defines the abstract factory interface that creates instances
  3321. // of a Test object.
  3322. class TestFactoryBase {
  3323. public:
  3324. virtual ~TestFactoryBase() {}
  3325. // Creates a test instance to run. The instance is both created and destroyed
  3326. // within TestInfoImpl::Run()
  3327. virtual Test* CreateTest() = 0;
  3328. protected:
  3329. TestFactoryBase() {}
  3330. private:
  3331. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
  3332. };
  3333. // This class provides implementation of TeastFactoryBase interface.
  3334. // It is used in TEST and TEST_F macros.
  3335. template <class TestClass>
  3336. class TestFactoryImpl : public TestFactoryBase {
  3337. public:
  3338. Test* CreateTest() override { return new TestClass; }
  3339. };
  3340. #if GTEST_OS_WINDOWS
  3341. // Predicate-formatters for implementing the HRESULT checking macros
  3342. // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
  3343. // We pass a long instead of HRESULT to avoid causing an
  3344. // include dependency for the HRESULT type.
  3345. GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
  3346. long hr); // NOLINT
  3347. GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
  3348. long hr); // NOLINT
  3349. #endif // GTEST_OS_WINDOWS
  3350. // Types of SetUpTestSuite() and TearDownTestSuite() functions.
  3351. using SetUpTestSuiteFunc = void (*)();
  3352. using TearDownTestSuiteFunc = void (*)();
  3353. struct CodeLocation {
  3354. CodeLocation(const std::string& a_file, int a_line)
  3355. : file(a_file), line(a_line) {}
  3356. std::string file;
  3357. int line;
  3358. };
  3359. // Helper to identify which setup function for TestCase / TestSuite to call.
  3360. // Only one function is allowed, either TestCase or TestSute but not both.
  3361. // Utility functions to help SuiteApiResolver
  3362. using SetUpTearDownSuiteFuncType = void (*)();
  3363. inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(
  3364. SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) {
  3365. return a == def ? nullptr : a;
  3366. }
  3367. template <typename T>
  3368. // Note that SuiteApiResolver inherits from T because
  3369. // SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way
  3370. // SuiteApiResolver can access them.
  3371. struct SuiteApiResolver : T {
  3372. // testing::Test is only forward declared at this point. So we make it a
  3373. // dependend class for the compiler to be OK with it.
  3374. using Test =
  3375. typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;
  3376. static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,
  3377. int line_num) {
  3378. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3379. SetUpTearDownSuiteFuncType test_case_fp =
  3380. GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);
  3381. SetUpTearDownSuiteFuncType test_suite_fp =
  3382. GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite);
  3383. GTEST_CHECK_(!test_case_fp || !test_suite_fp)
  3384. << "Test can not provide both SetUpTestSuite and SetUpTestCase, please "
  3385. "make sure there is only one present at "
  3386. << filename << ":" << line_num;
  3387. return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
  3388. #else
  3389. (void)(filename);
  3390. (void)(line_num);
  3391. return &T::SetUpTestSuite;
  3392. #endif
  3393. }
  3394. static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,
  3395. int line_num) {
  3396. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3397. SetUpTearDownSuiteFuncType test_case_fp =
  3398. GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);
  3399. SetUpTearDownSuiteFuncType test_suite_fp =
  3400. GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite);
  3401. GTEST_CHECK_(!test_case_fp || !test_suite_fp)
  3402. << "Test can not provide both TearDownTestSuite and TearDownTestCase,"
  3403. " please make sure there is only one present at"
  3404. << filename << ":" << line_num;
  3405. return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
  3406. #else
  3407. (void)(filename);
  3408. (void)(line_num);
  3409. return &T::TearDownTestSuite;
  3410. #endif
  3411. }
  3412. };
  3413. // Creates a new TestInfo object and registers it with Google Test;
  3414. // returns the created object.
  3415. //
  3416. // Arguments:
  3417. //
  3418. // test_suite_name: name of the test suite
  3419. // name: name of the test
  3420. // type_param: the name of the test's type parameter, or NULL if
  3421. // this is not a typed or a type-parameterized test.
  3422. // value_param: text representation of the test's value parameter,
  3423. // or NULL if this is not a type-parameterized test.
  3424. // code_location: code location where the test is defined
  3425. // fixture_class_id: ID of the test fixture class
  3426. // set_up_tc: pointer to the function that sets up the test suite
  3427. // tear_down_tc: pointer to the function that tears down the test suite
  3428. // factory: pointer to the factory that creates a test object.
  3429. // The newly created TestInfo instance will assume
  3430. // ownership of the factory object.
  3431. GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
  3432. const char* test_suite_name, const char* name, const char* type_param,
  3433. const char* value_param, CodeLocation code_location,
  3434. TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
  3435. TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);
  3436. // If *pstr starts with the given prefix, modifies *pstr to be right
  3437. // past the prefix and returns true; otherwise leaves *pstr unchanged
  3438. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  3439. GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
  3440. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  3441. /* class A needs to have dll-interface to be used by clients of class B */)
  3442. // State of the definition of a type-parameterized test suite.
  3443. class GTEST_API_ TypedTestSuitePState {
  3444. public:
  3445. TypedTestSuitePState() : registered_(false) {}
  3446. // Adds the given test name to defined_test_names_ and return true
  3447. // if the test suite hasn't been registered; otherwise aborts the
  3448. // program.
  3449. bool AddTestName(const char* file, int line, const char* case_name,
  3450. const char* test_name) {
  3451. if (registered_) {
  3452. fprintf(stderr,
  3453. "%s Test %s must be defined before "
  3454. "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",
  3455. FormatFileLocation(file, line).c_str(), test_name, case_name);
  3456. fflush(stderr);
  3457. posix::Abort();
  3458. }
  3459. registered_tests_.insert(
  3460. ::std::make_pair(test_name, CodeLocation(file, line)));
  3461. return true;
  3462. }
  3463. bool TestExists(const std::string& test_name) const {
  3464. return registered_tests_.count(test_name) > 0;
  3465. }
  3466. const CodeLocation& GetCodeLocation(const std::string& test_name) const {
  3467. RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);
  3468. GTEST_CHECK_(it != registered_tests_.end());
  3469. return it->second;
  3470. }
  3471. // Verifies that registered_tests match the test names in
  3472. // defined_test_names_; returns registered_tests if successful, or
  3473. // aborts the program otherwise.
  3474. const char* VerifyRegisteredTestNames(const char* test_suite_name,
  3475. const char* file, int line,
  3476. const char* registered_tests);
  3477. private:
  3478. typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;
  3479. bool registered_;
  3480. RegisteredTestsMap registered_tests_;
  3481. };
  3482. // Legacy API is deprecated but still available
  3483. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3484. using TypedTestCasePState = TypedTestSuitePState;
  3485. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  3486. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  3487. // Skips to the first non-space char after the first comma in 'str';
  3488. // returns NULL if no comma is found in 'str'.
  3489. inline const char* SkipComma(const char* str) {
  3490. const char* comma = strchr(str, ',');
  3491. if (comma == nullptr) {
  3492. return nullptr;
  3493. }
  3494. while (IsSpace(*(++comma))) {}
  3495. return comma;
  3496. }
  3497. // Returns the prefix of 'str' before the first comma in it; returns
  3498. // the entire string if it contains no comma.
  3499. inline std::string GetPrefixUntilComma(const char* str) {
  3500. const char* comma = strchr(str, ',');
  3501. return comma == nullptr ? str : std::string(str, comma);
  3502. }
  3503. // Splits a given string on a given delimiter, populating a given
  3504. // vector with the fields.
  3505. void SplitString(const ::std::string& str, char delimiter,
  3506. ::std::vector< ::std::string>* dest);
  3507. // The default argument to the template below for the case when the user does
  3508. // not provide a name generator.
  3509. struct DefaultNameGenerator {
  3510. template <typename T>
  3511. static std::string GetName(int i) {
  3512. return StreamableToString(i);
  3513. }
  3514. };
  3515. template <typename Provided = DefaultNameGenerator>
  3516. struct NameGeneratorSelector {
  3517. typedef Provided type;
  3518. };
  3519. template <typename NameGenerator>
  3520. void GenerateNamesRecursively(internal::None, std::vector<std::string>*, int) {}
  3521. template <typename NameGenerator, typename Types>
  3522. void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {
  3523. result->push_back(NameGenerator::template GetName<typename Types::Head>(i));
  3524. GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,
  3525. i + 1);
  3526. }
  3527. template <typename NameGenerator, typename Types>
  3528. std::vector<std::string> GenerateNames() {
  3529. std::vector<std::string> result;
  3530. GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);
  3531. return result;
  3532. }
  3533. // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
  3534. // registers a list of type-parameterized tests with Google Test. The
  3535. // return value is insignificant - we just need to return something
  3536. // such that we can call this function in a namespace scope.
  3537. //
  3538. // Implementation note: The GTEST_TEMPLATE_ macro declares a template
  3539. // template parameter. It's defined in gtest-type-util.h.
  3540. template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
  3541. class TypeParameterizedTest {
  3542. public:
  3543. // 'index' is the index of the test in the type list 'Types'
  3544. // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
  3545. // Types). Valid values for 'index' are [0, N - 1] where N is the
  3546. // length of Types.
  3547. static bool Register(const char* prefix, const CodeLocation& code_location,
  3548. const char* case_name, const char* test_names, int index,
  3549. const std::vector<std::string>& type_names =
  3550. GenerateNames<DefaultNameGenerator, Types>()) {
  3551. typedef typename Types::Head Type;
  3552. typedef Fixture<Type> FixtureClass;
  3553. typedef typename GTEST_BIND_(TestSel, Type) TestClass;
  3554. // First, registers the first type-parameterized test in the type
  3555. // list.
  3556. MakeAndRegisterTestInfo(
  3557. (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +
  3558. "/" + type_names[static_cast<size_t>(index)])
  3559. .c_str(),
  3560. StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
  3561. GetTypeName<Type>().c_str(),
  3562. nullptr, // No value parameter.
  3563. code_location, GetTypeId<FixtureClass>(),
  3564. SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite(
  3565. code_location.file.c_str(), code_location.line),
  3566. SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite(
  3567. code_location.file.c_str(), code_location.line),
  3568. new TestFactoryImpl<TestClass>);
  3569. // Next, recurses (at compile time) with the tail of the type list.
  3570. return TypeParameterizedTest<Fixture, TestSel,
  3571. typename Types::Tail>::Register(prefix,
  3572. code_location,
  3573. case_name,
  3574. test_names,
  3575. index + 1,
  3576. type_names);
  3577. }
  3578. };
  3579. // The base case for the compile time recursion.
  3580. template <GTEST_TEMPLATE_ Fixture, class TestSel>
  3581. class TypeParameterizedTest<Fixture, TestSel, internal::None> {
  3582. public:
  3583. static bool Register(const char* /*prefix*/, const CodeLocation&,
  3584. const char* /*case_name*/, const char* /*test_names*/,
  3585. int /*index*/,
  3586. const std::vector<std::string>& =
  3587. std::vector<std::string>() /*type_names*/) {
  3588. return true;
  3589. }
  3590. };
  3591. GTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
  3592. CodeLocation code_location);
  3593. GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(
  3594. const char* case_name);
  3595. // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
  3596. // registers *all combinations* of 'Tests' and 'Types' with Google
  3597. // Test. The return value is insignificant - we just need to return
  3598. // something such that we can call this function in a namespace scope.
  3599. template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
  3600. class TypeParameterizedTestSuite {
  3601. public:
  3602. static bool Register(const char* prefix, CodeLocation code_location,
  3603. const TypedTestSuitePState* state, const char* case_name,
  3604. const char* test_names,
  3605. const std::vector<std::string>& type_names =
  3606. GenerateNames<DefaultNameGenerator, Types>()) {
  3607. RegisterTypeParameterizedTestSuiteInstantiation(case_name);
  3608. std::string test_name = StripTrailingSpaces(
  3609. GetPrefixUntilComma(test_names));
  3610. if (!state->TestExists(test_name)) {
  3611. fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
  3612. case_name, test_name.c_str(),
  3613. FormatFileLocation(code_location.file.c_str(),
  3614. code_location.line).c_str());
  3615. fflush(stderr);
  3616. posix::Abort();
  3617. }
  3618. const CodeLocation& test_location = state->GetCodeLocation(test_name);
  3619. typedef typename Tests::Head Head;
  3620. // First, register the first test in 'Test' for each type in 'Types'.
  3621. TypeParameterizedTest<Fixture, Head, Types>::Register(
  3622. prefix, test_location, case_name, test_names, 0, type_names);
  3623. // Next, recurses (at compile time) with the tail of the test list.
  3624. return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,
  3625. Types>::Register(prefix, code_location,
  3626. state, case_name,
  3627. SkipComma(test_names),
  3628. type_names);
  3629. }
  3630. };
  3631. // The base case for the compile time recursion.
  3632. template <GTEST_TEMPLATE_ Fixture, typename Types>
  3633. class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
  3634. public:
  3635. static bool Register(const char* /*prefix*/, const CodeLocation&,
  3636. const TypedTestSuitePState* /*state*/,
  3637. const char* /*case_name*/, const char* /*test_names*/,
  3638. const std::vector<std::string>& =
  3639. std::vector<std::string>() /*type_names*/) {
  3640. return true;
  3641. }
  3642. };
  3643. // Returns the current OS stack trace as an std::string.
  3644. //
  3645. // The maximum number of stack frames to be included is specified by
  3646. // the gtest_stack_trace_depth flag. The skip_count parameter
  3647. // specifies the number of top frames to be skipped, which doesn't
  3648. // count against the number of frames to be included.
  3649. //
  3650. // For example, if Foo() calls Bar(), which in turn calls
  3651. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  3652. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  3653. GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
  3654. UnitTest* unit_test, int skip_count);
  3655. // Helpers for suppressing warnings on unreachable code or constant
  3656. // condition.
  3657. // Always returns true.
  3658. GTEST_API_ bool AlwaysTrue();
  3659. // Always returns false.
  3660. inline bool AlwaysFalse() { return !AlwaysTrue(); }
  3661. // Helper for suppressing false warning from Clang on a const char*
  3662. // variable declared in a conditional expression always being NULL in
  3663. // the else branch.
  3664. struct GTEST_API_ ConstCharPtr {
  3665. ConstCharPtr(const char* str) : value(str) {}
  3666. operator bool() const { return true; }
  3667. const char* value;
  3668. };
  3669. // Helper for declaring std::string within 'if' statement
  3670. // in pre C++17 build environment.
  3671. struct TrueWithString {
  3672. TrueWithString() = default;
  3673. explicit TrueWithString(const char* str) : value(str) {}
  3674. explicit TrueWithString(const std::string& str) : value(str) {}
  3675. explicit operator bool() const { return true; }
  3676. std::string value;
  3677. };
  3678. // A simple Linear Congruential Generator for generating random
  3679. // numbers with a uniform distribution. Unlike rand() and srand(), it
  3680. // doesn't use global state (and therefore can't interfere with user
  3681. // code). Unlike rand_r(), it's portable. An LCG isn't very random,
  3682. // but it's good enough for our purposes.
  3683. class GTEST_API_ Random {
  3684. public:
  3685. static const uint32_t kMaxRange = 1u << 31;
  3686. explicit Random(uint32_t seed) : state_(seed) {}
  3687. void Reseed(uint32_t seed) { state_ = seed; }
  3688. // Generates a random number from [0, range). Crashes if 'range' is
  3689. // 0 or greater than kMaxRange.
  3690. uint32_t Generate(uint32_t range);
  3691. private:
  3692. uint32_t state_;
  3693. GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
  3694. };
  3695. // Turns const U&, U&, const U, and U all into U.
  3696. #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
  3697. typename std::remove_const<typename std::remove_reference<T>::type>::type
  3698. // HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant
  3699. // that's true if and only if T has methods DebugString() and ShortDebugString()
  3700. // that return std::string.
  3701. template <typename T>
  3702. class HasDebugStringAndShortDebugString {
  3703. private:
  3704. template <typename C>
  3705. static auto CheckDebugString(C*) -> typename std::is_same<
  3706. std::string, decltype(std::declval<const C>().DebugString())>::type;
  3707. template <typename>
  3708. static std::false_type CheckDebugString(...);
  3709. template <typename C>
  3710. static auto CheckShortDebugString(C*) -> typename std::is_same<
  3711. std::string, decltype(std::declval<const C>().ShortDebugString())>::type;
  3712. template <typename>
  3713. static std::false_type CheckShortDebugString(...);
  3714. using HasDebugStringType = decltype(CheckDebugString<T>(nullptr));
  3715. using HasShortDebugStringType = decltype(CheckShortDebugString<T>(nullptr));
  3716. public:
  3717. static constexpr bool value =
  3718. HasDebugStringType::value && HasShortDebugStringType::value;
  3719. };
  3720. template <typename T>
  3721. constexpr bool HasDebugStringAndShortDebugString<T>::value;
  3722. // When the compiler sees expression IsContainerTest<C>(0), if C is an
  3723. // STL-style container class, the first overload of IsContainerTest
  3724. // will be viable (since both C::iterator* and C::const_iterator* are
  3725. // valid types and NULL can be implicitly converted to them). It will
  3726. // be picked over the second overload as 'int' is a perfect match for
  3727. // the type of argument 0. If C::iterator or C::const_iterator is not
  3728. // a valid type, the first overload is not viable, and the second
  3729. // overload will be picked. Therefore, we can determine whether C is
  3730. // a container class by checking the type of IsContainerTest<C>(0).
  3731. // The value of the expression is insignificant.
  3732. //
  3733. // In C++11 mode we check the existence of a const_iterator and that an
  3734. // iterator is properly implemented for the container.
  3735. //
  3736. // For pre-C++11 that we look for both C::iterator and C::const_iterator.
  3737. // The reason is that C++ injects the name of a class as a member of the
  3738. // class itself (e.g. you can refer to class iterator as either
  3739. // 'iterator' or 'iterator::iterator'). If we look for C::iterator
  3740. // only, for example, we would mistakenly think that a class named
  3741. // iterator is an STL container.
  3742. //
  3743. // Also note that the simpler approach of overloading
  3744. // IsContainerTest(typename C::const_iterator*) and
  3745. // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
  3746. typedef int IsContainer;
  3747. template <class C,
  3748. class Iterator = decltype(::std::declval<const C&>().begin()),
  3749. class = decltype(::std::declval<const C&>().end()),
  3750. class = decltype(++::std::declval<Iterator&>()),
  3751. class = decltype(*::std::declval<Iterator>()),
  3752. class = typename C::const_iterator>
  3753. IsContainer IsContainerTest(int /* dummy */) {
  3754. return 0;
  3755. }
  3756. typedef char IsNotContainer;
  3757. template <class C>
  3758. IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
  3759. // Trait to detect whether a type T is a hash table.
  3760. // The heuristic used is that the type contains an inner type `hasher` and does
  3761. // not contain an inner type `reverse_iterator`.
  3762. // If the container is iterable in reverse, then order might actually matter.
  3763. template <typename T>
  3764. struct IsHashTable {
  3765. private:
  3766. template <typename U>
  3767. static char test(typename U::hasher*, typename U::reverse_iterator*);
  3768. template <typename U>
  3769. static int test(typename U::hasher*, ...);
  3770. template <typename U>
  3771. static char test(...);
  3772. public:
  3773. static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int);
  3774. };
  3775. template <typename T>
  3776. const bool IsHashTable<T>::value;
  3777. template <typename C,
  3778. bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)>
  3779. struct IsRecursiveContainerImpl;
  3780. template <typename C>
  3781. struct IsRecursiveContainerImpl<C, false> : public std::false_type {};
  3782. // Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to
  3783. // obey the same inconsistencies as the IsContainerTest, namely check if
  3784. // something is a container is relying on only const_iterator in C++11 and
  3785. // is relying on both const_iterator and iterator otherwise
  3786. template <typename C>
  3787. struct IsRecursiveContainerImpl<C, true> {
  3788. using value_type = decltype(*std::declval<typename C::const_iterator>());
  3789. using type =
  3790. std::is_same<typename std::remove_const<
  3791. typename std::remove_reference<value_type>::type>::type,
  3792. C>;
  3793. };
  3794. // IsRecursiveContainer<Type> is a unary compile-time predicate that
  3795. // evaluates whether C is a recursive container type. A recursive container
  3796. // type is a container type whose value_type is equal to the container type
  3797. // itself. An example for a recursive container type is
  3798. // boost::filesystem::path, whose iterator has a value_type that is equal to
  3799. // boost::filesystem::path.
  3800. template <typename C>
  3801. struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};
  3802. // Utilities for native arrays.
  3803. // ArrayEq() compares two k-dimensional native arrays using the
  3804. // elements' operator==, where k can be any integer >= 0. When k is
  3805. // 0, ArrayEq() degenerates into comparing a single pair of values.
  3806. template <typename T, typename U>
  3807. bool ArrayEq(const T* lhs, size_t size, const U* rhs);
  3808. // This generic version is used when k is 0.
  3809. template <typename T, typename U>
  3810. inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
  3811. // This overload is used when k >= 1.
  3812. template <typename T, typename U, size_t N>
  3813. inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
  3814. return internal::ArrayEq(lhs, N, rhs);
  3815. }
  3816. // This helper reduces code bloat. If we instead put its logic inside
  3817. // the previous ArrayEq() function, arrays with different sizes would
  3818. // lead to different copies of the template code.
  3819. template <typename T, typename U>
  3820. bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
  3821. for (size_t i = 0; i != size; i++) {
  3822. if (!internal::ArrayEq(lhs[i], rhs[i]))
  3823. return false;
  3824. }
  3825. return true;
  3826. }
  3827. // Finds the first element in the iterator range [begin, end) that
  3828. // equals elem. Element may be a native array type itself.
  3829. template <typename Iter, typename Element>
  3830. Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
  3831. for (Iter it = begin; it != end; ++it) {
  3832. if (internal::ArrayEq(*it, elem))
  3833. return it;
  3834. }
  3835. return end;
  3836. }
  3837. // CopyArray() copies a k-dimensional native array using the elements'
  3838. // operator=, where k can be any integer >= 0. When k is 0,
  3839. // CopyArray() degenerates into copying a single value.
  3840. template <typename T, typename U>
  3841. void CopyArray(const T* from, size_t size, U* to);
  3842. // This generic version is used when k is 0.
  3843. template <typename T, typename U>
  3844. inline void CopyArray(const T& from, U* to) { *to = from; }
  3845. // This overload is used when k >= 1.
  3846. template <typename T, typename U, size_t N>
  3847. inline void CopyArray(const T(&from)[N], U(*to)[N]) {
  3848. internal::CopyArray(from, N, *to);
  3849. }
  3850. // This helper reduces code bloat. If we instead put its logic inside
  3851. // the previous CopyArray() function, arrays with different sizes
  3852. // would lead to different copies of the template code.
  3853. template <typename T, typename U>
  3854. void CopyArray(const T* from, size_t size, U* to) {
  3855. for (size_t i = 0; i != size; i++) {
  3856. internal::CopyArray(from[i], to + i);
  3857. }
  3858. }
  3859. // The relation between an NativeArray object (see below) and the
  3860. // native array it represents.
  3861. // We use 2 different structs to allow non-copyable types to be used, as long
  3862. // as RelationToSourceReference() is passed.
  3863. struct RelationToSourceReference {};
  3864. struct RelationToSourceCopy {};
  3865. // Adapts a native array to a read-only STL-style container. Instead
  3866. // of the complete STL container concept, this adaptor only implements
  3867. // members useful for Google Mock's container matchers. New members
  3868. // should be added as needed. To simplify the implementation, we only
  3869. // support Element being a raw type (i.e. having no top-level const or
  3870. // reference modifier). It's the client's responsibility to satisfy
  3871. // this requirement. Element can be an array type itself (hence
  3872. // multi-dimensional arrays are supported).
  3873. template <typename Element>
  3874. class NativeArray {
  3875. public:
  3876. // STL-style container typedefs.
  3877. typedef Element value_type;
  3878. typedef Element* iterator;
  3879. typedef const Element* const_iterator;
  3880. // Constructs from a native array. References the source.
  3881. NativeArray(const Element* array, size_t count, RelationToSourceReference) {
  3882. InitRef(array, count);
  3883. }
  3884. // Constructs from a native array. Copies the source.
  3885. NativeArray(const Element* array, size_t count, RelationToSourceCopy) {
  3886. InitCopy(array, count);
  3887. }
  3888. // Copy constructor.
  3889. NativeArray(const NativeArray& rhs) {
  3890. (this->*rhs.clone_)(rhs.array_, rhs.size_);
  3891. }
  3892. ~NativeArray() {
  3893. if (clone_ != &NativeArray::InitRef)
  3894. delete[] array_;
  3895. }
  3896. // STL-style container methods.
  3897. size_t size() const { return size_; }
  3898. const_iterator begin() const { return array_; }
  3899. const_iterator end() const { return array_ + size_; }
  3900. bool operator==(const NativeArray& rhs) const {
  3901. return size() == rhs.size() &&
  3902. ArrayEq(begin(), size(), rhs.begin());
  3903. }
  3904. private:
  3905. static_assert(!std::is_const<Element>::value, "Type must not be const");
  3906. static_assert(!std::is_reference<Element>::value,
  3907. "Type must not be a reference");
  3908. // Initializes this object with a copy of the input.
  3909. void InitCopy(const Element* array, size_t a_size) {
  3910. Element* const copy = new Element[a_size];
  3911. CopyArray(array, a_size, copy);
  3912. array_ = copy;
  3913. size_ = a_size;
  3914. clone_ = &NativeArray::InitCopy;
  3915. }
  3916. // Initializes this object with a reference of the input.
  3917. void InitRef(const Element* array, size_t a_size) {
  3918. array_ = array;
  3919. size_ = a_size;
  3920. clone_ = &NativeArray::InitRef;
  3921. }
  3922. const Element* array_;
  3923. size_t size_;
  3924. void (NativeArray::*clone_)(const Element*, size_t);
  3925. };
  3926. // Backport of std::index_sequence.
  3927. template <size_t... Is>
  3928. struct IndexSequence {
  3929. using type = IndexSequence;
  3930. };
  3931. // Double the IndexSequence, and one if plus_one is true.
  3932. template <bool plus_one, typename T, size_t sizeofT>
  3933. struct DoubleSequence;
  3934. template <size_t... I, size_t sizeofT>
  3935. struct DoubleSequence<true, IndexSequence<I...>, sizeofT> {
  3936. using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>;
  3937. };
  3938. template <size_t... I, size_t sizeofT>
  3939. struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
  3940. using type = IndexSequence<I..., (sizeofT + I)...>;
  3941. };
  3942. // Backport of std::make_index_sequence.
  3943. // It uses O(ln(N)) instantiation depth.
  3944. template <size_t N>
  3945. struct MakeIndexSequenceImpl
  3946. : DoubleSequence<N % 2 == 1, typename MakeIndexSequenceImpl<N / 2>::type,
  3947. N / 2>::type {};
  3948. template <>
  3949. struct MakeIndexSequenceImpl<0> : IndexSequence<> {};
  3950. template <size_t N>
  3951. using MakeIndexSequence = typename MakeIndexSequenceImpl<N>::type;
  3952. template <typename... T>
  3953. using IndexSequenceFor = typename MakeIndexSequence<sizeof...(T)>::type;
  3954. template <size_t>
  3955. struct Ignore {
  3956. Ignore(...); // NOLINT
  3957. };
  3958. template <typename>
  3959. struct ElemFromListImpl;
  3960. template <size_t... I>
  3961. struct ElemFromListImpl<IndexSequence<I...>> {
  3962. // We make Ignore a template to solve a problem with MSVC.
  3963. // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but
  3964. // MSVC doesn't understand how to deal with that pack expansion.
  3965. // Use `0 * I` to have a single instantiation of Ignore.
  3966. template <typename R>
  3967. static R Apply(Ignore<0 * I>..., R (*)(), ...);
  3968. };
  3969. template <size_t N, typename... T>
  3970. struct ElemFromList {
  3971. using type =
  3972. decltype(ElemFromListImpl<typename MakeIndexSequence<N>::type>::Apply(
  3973. static_cast<T (*)()>(nullptr)...));
  3974. };
  3975. struct FlatTupleConstructTag {};
  3976. template <typename... T>
  3977. class FlatTuple;
  3978. template <typename Derived, size_t I>
  3979. struct FlatTupleElemBase;
  3980. template <typename... T, size_t I>
  3981. struct FlatTupleElemBase<FlatTuple<T...>, I> {
  3982. using value_type = typename ElemFromList<I, T...>::type;
  3983. FlatTupleElemBase() = default;
  3984. template <typename Arg>
  3985. explicit FlatTupleElemBase(FlatTupleConstructTag, Arg&& t)
  3986. : value(std::forward<Arg>(t)) {}
  3987. value_type value;
  3988. };
  3989. template <typename Derived, typename Idx>
  3990. struct FlatTupleBase;
  3991. template <size_t... Idx, typename... T>
  3992. struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
  3993. : FlatTupleElemBase<FlatTuple<T...>, Idx>... {
  3994. using Indices = IndexSequence<Idx...>;
  3995. FlatTupleBase() = default;
  3996. template <typename... Args>
  3997. explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args)
  3998. : FlatTupleElemBase<FlatTuple<T...>, Idx>(FlatTupleConstructTag{},
  3999. std::forward<Args>(args))... {}
  4000. template <size_t I>
  4001. const typename ElemFromList<I, T...>::type& Get() const {
  4002. return FlatTupleElemBase<FlatTuple<T...>, I>::value;
  4003. }
  4004. template <size_t I>
  4005. typename ElemFromList<I, T...>::type& Get() {
  4006. return FlatTupleElemBase<FlatTuple<T...>, I>::value;
  4007. }
  4008. template <typename F>
  4009. auto Apply(F&& f) -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
  4010. return std::forward<F>(f)(Get<Idx>()...);
  4011. }
  4012. template <typename F>
  4013. auto Apply(F&& f) const -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
  4014. return std::forward<F>(f)(Get<Idx>()...);
  4015. }
  4016. };
  4017. // Analog to std::tuple but with different tradeoffs.
  4018. // This class minimizes the template instantiation depth, thus allowing more
  4019. // elements than std::tuple would. std::tuple has been seen to require an
  4020. // instantiation depth of more than 10x the number of elements in some
  4021. // implementations.
  4022. // FlatTuple and ElemFromList are not recursive and have a fixed depth
  4023. // regardless of T...
  4024. // MakeIndexSequence, on the other hand, it is recursive but with an
  4025. // instantiation depth of O(ln(N)).
  4026. template <typename... T>
  4027. class FlatTuple
  4028. : private FlatTupleBase<FlatTuple<T...>,
  4029. typename MakeIndexSequence<sizeof...(T)>::type> {
  4030. using Indices = typename FlatTupleBase<
  4031. FlatTuple<T...>, typename MakeIndexSequence<sizeof...(T)>::type>::Indices;
  4032. public:
  4033. FlatTuple() = default;
  4034. template <typename... Args>
  4035. explicit FlatTuple(FlatTupleConstructTag tag, Args&&... args)
  4036. : FlatTuple::FlatTupleBase(tag, std::forward<Args>(args)...) {}
  4037. using FlatTuple::FlatTupleBase::Apply;
  4038. using FlatTuple::FlatTupleBase::Get;
  4039. };
  4040. // Utility functions to be called with static_assert to induce deprecation
  4041. // warnings.
  4042. GTEST_INTERNAL_DEPRECATED(
  4043. "INSTANTIATE_TEST_CASE_P is deprecated, please use "
  4044. "INSTANTIATE_TEST_SUITE_P")
  4045. constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
  4046. GTEST_INTERNAL_DEPRECATED(
  4047. "TYPED_TEST_CASE_P is deprecated, please use "
  4048. "TYPED_TEST_SUITE_P")
  4049. constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
  4050. GTEST_INTERNAL_DEPRECATED(
  4051. "TYPED_TEST_CASE is deprecated, please use "
  4052. "TYPED_TEST_SUITE")
  4053. constexpr bool TypedTestCaseIsDeprecated() { return true; }
  4054. GTEST_INTERNAL_DEPRECATED(
  4055. "REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
  4056. "REGISTER_TYPED_TEST_SUITE_P")
  4057. constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
  4058. GTEST_INTERNAL_DEPRECATED(
  4059. "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
  4060. "INSTANTIATE_TYPED_TEST_SUITE_P")
  4061. constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
  4062. } // namespace internal
  4063. } // namespace testing
  4064. namespace std {
  4065. // Some standard library implementations use `struct tuple_size` and some use
  4066. // `class tuple_size`. Clang warns about the mismatch.
  4067. // https://reviews.llvm.org/D55466
  4068. #ifdef __clang__
  4069. #pragma clang diagnostic push
  4070. #pragma clang diagnostic ignored "-Wmismatched-tags"
  4071. #endif
  4072. template <typename... Ts>
  4073. struct tuple_size<testing::internal::FlatTuple<Ts...>>
  4074. : std::integral_constant<size_t, sizeof...(Ts)> {};
  4075. #ifdef __clang__
  4076. #pragma clang diagnostic pop
  4077. #endif
  4078. } // namespace std
  4079. #define GTEST_MESSAGE_AT_(file, line, message, result_type) \
  4080. ::testing::internal::AssertHelper(result_type, file, line, message) \
  4081. = ::testing::Message()
  4082. #define GTEST_MESSAGE_(message, result_type) \
  4083. GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
  4084. #define GTEST_FATAL_FAILURE_(message) \
  4085. return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
  4086. #define GTEST_NONFATAL_FAILURE_(message) \
  4087. GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
  4088. #define GTEST_SUCCESS_(message) \
  4089. GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
  4090. #define GTEST_SKIP_(message) \
  4091. return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)
  4092. // Suppress MSVC warning 4072 (unreachable code) for the code following
  4093. // statement if it returns or throws (or doesn't return or throw in some
  4094. // situations).
  4095. // NOTE: The "else" is important to keep this expansion to prevent a top-level
  4096. // "else" from attaching to our "if".
  4097. #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
  4098. if (::testing::internal::AlwaysTrue()) { \
  4099. statement; \
  4100. } else /* NOLINT */ \
  4101. static_assert(true, "") // User must have a semicolon after expansion.
  4102. #if GTEST_HAS_EXCEPTIONS
  4103. namespace testing {
  4104. namespace internal {
  4105. class NeverThrown {
  4106. public:
  4107. const char* what() const noexcept {
  4108. return "this exception should never be thrown";
  4109. }
  4110. };
  4111. } // namespace internal
  4112. } // namespace testing
  4113. #if GTEST_HAS_RTTI
  4114. #define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))
  4115. #else // GTEST_HAS_RTTI
  4116. #define GTEST_EXCEPTION_TYPE_(e) \
  4117. std::string { "an std::exception-derived error" }
  4118. #endif // GTEST_HAS_RTTI
  4119. #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
  4120. catch (typename std::conditional< \
  4121. std::is_same<typename std::remove_cv<typename std::remove_reference< \
  4122. expected_exception>::type>::type, \
  4123. std::exception>::value, \
  4124. const ::testing::internal::NeverThrown&, const std::exception&>::type \
  4125. e) { \
  4126. gtest_msg.value = "Expected: " #statement \
  4127. " throws an exception of type " #expected_exception \
  4128. ".\n Actual: it throws "; \
  4129. gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
  4130. gtest_msg.value += " with description \""; \
  4131. gtest_msg.value += e.what(); \
  4132. gtest_msg.value += "\"."; \
  4133. goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
  4134. }
  4135. #else // GTEST_HAS_EXCEPTIONS
  4136. #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)
  4137. #endif // GTEST_HAS_EXCEPTIONS
  4138. #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
  4139. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  4140. if (::testing::internal::TrueWithString gtest_msg{}) { \
  4141. bool gtest_caught_expected = false; \
  4142. try { \
  4143. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  4144. } catch (expected_exception const&) { \
  4145. gtest_caught_expected = true; \
  4146. } \
  4147. GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
  4148. catch (...) { \
  4149. gtest_msg.value = "Expected: " #statement \
  4150. " throws an exception of type " #expected_exception \
  4151. ".\n Actual: it throws a different type."; \
  4152. goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
  4153. } \
  4154. if (!gtest_caught_expected) { \
  4155. gtest_msg.value = "Expected: " #statement \
  4156. " throws an exception of type " #expected_exception \
  4157. ".\n Actual: it throws nothing."; \
  4158. goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
  4159. } \
  4160. } else /*NOLINT*/ \
  4161. GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
  4162. : fail(gtest_msg.value.c_str())
  4163. #if GTEST_HAS_EXCEPTIONS
  4164. #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
  4165. catch (std::exception const& e) { \
  4166. gtest_msg.value = "it throws "; \
  4167. gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
  4168. gtest_msg.value += " with description \""; \
  4169. gtest_msg.value += e.what(); \
  4170. gtest_msg.value += "\"."; \
  4171. goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
  4172. }
  4173. #else // GTEST_HAS_EXCEPTIONS
  4174. #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()
  4175. #endif // GTEST_HAS_EXCEPTIONS
  4176. #define GTEST_TEST_NO_THROW_(statement, fail) \
  4177. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  4178. if (::testing::internal::TrueWithString gtest_msg{}) { \
  4179. try { \
  4180. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  4181. } \
  4182. GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
  4183. catch (...) { \
  4184. gtest_msg.value = "it throws."; \
  4185. goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
  4186. } \
  4187. } else \
  4188. GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
  4189. fail(("Expected: " #statement " doesn't throw an exception.\n" \
  4190. " Actual: " + gtest_msg.value).c_str())
  4191. #define GTEST_TEST_ANY_THROW_(statement, fail) \
  4192. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  4193. if (::testing::internal::AlwaysTrue()) { \
  4194. bool gtest_caught_any = false; \
  4195. try { \
  4196. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  4197. } \
  4198. catch (...) { \
  4199. gtest_caught_any = true; \
  4200. } \
  4201. if (!gtest_caught_any) { \
  4202. goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
  4203. } \
  4204. } else \
  4205. GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
  4206. fail("Expected: " #statement " throws an exception.\n" \
  4207. " Actual: it doesn't.")
  4208. // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
  4209. // either a boolean expression or an AssertionResult. text is a textual
  4210. // representation of expression as it was passed into the EXPECT_TRUE.
  4211. #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
  4212. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  4213. if (const ::testing::AssertionResult gtest_ar_ = \
  4214. ::testing::AssertionResult(expression)) \
  4215. ; \
  4216. else \
  4217. fail(::testing::internal::GetBoolAssertionFailureMessage(\
  4218. gtest_ar_, text, #actual, #expected).c_str())
  4219. #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
  4220. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  4221. if (::testing::internal::AlwaysTrue()) { \
  4222. ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
  4223. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  4224. if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
  4225. goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
  4226. } \
  4227. } else \
  4228. GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
  4229. fail("Expected: " #statement " doesn't generate new fatal " \
  4230. "failures in the current thread.\n" \
  4231. " Actual: it does.")
  4232. // Expands to the name of the class that implements the given test.
  4233. #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
  4234. test_suite_name##_##test_name##_Test
  4235. // Helper macro for defining tests.
  4236. #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \
  4237. static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \
  4238. "test_suite_name must not be empty"); \
  4239. static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \
  4240. "test_name must not be empty"); \
  4241. class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
  4242. : public parent_class { \
  4243. public: \
  4244. GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \
  4245. ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \
  4246. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
  4247. test_name)); \
  4248. GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
  4249. test_name)); \
  4250. \
  4251. private: \
  4252. void TestBody() override; \
  4253. static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
  4254. }; \
  4255. \
  4256. ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \
  4257. test_name)::test_info_ = \
  4258. ::testing::internal::MakeAndRegisterTestInfo( \
  4259. #test_suite_name, #test_name, nullptr, nullptr, \
  4260. ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
  4261. ::testing::internal::SuiteApiResolver< \
  4262. parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \
  4263. ::testing::internal::SuiteApiResolver< \
  4264. parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \
  4265. new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \
  4266. test_suite_name, test_name)>); \
  4267. void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
  4268. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
  4269. // Copyright 2005, Google Inc.
  4270. // All rights reserved.
  4271. //
  4272. // Redistribution and use in source and binary forms, with or without
  4273. // modification, are permitted provided that the following conditions are
  4274. // met:
  4275. //
  4276. // * Redistributions of source code must retain the above copyright
  4277. // notice, this list of conditions and the following disclaimer.
  4278. // * Redistributions in binary form must reproduce the above
  4279. // copyright notice, this list of conditions and the following disclaimer
  4280. // in the documentation and/or other materials provided with the
  4281. // distribution.
  4282. // * Neither the name of Google Inc. nor the names of its
  4283. // contributors may be used to endorse or promote products derived from
  4284. // this software without specific prior written permission.
  4285. //
  4286. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4287. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  4288. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  4289. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  4290. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  4291. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4292. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  4293. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  4294. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  4295. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  4296. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4297. //
  4298. // The Google C++ Testing and Mocking Framework (Google Test)
  4299. //
  4300. // This header file defines the public API for death tests. It is
  4301. // #included by gtest.h so a user doesn't need to include this
  4302. // directly.
  4303. // GOOGLETEST_CM0001 DO NOT DELETE
  4304. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
  4305. #define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
  4306. // Copyright 2005, Google Inc.
  4307. // All rights reserved.
  4308. //
  4309. // Redistribution and use in source and binary forms, with or without
  4310. // modification, are permitted provided that the following conditions are
  4311. // met:
  4312. //
  4313. // * Redistributions of source code must retain the above copyright
  4314. // notice, this list of conditions and the following disclaimer.
  4315. // * Redistributions in binary form must reproduce the above
  4316. // copyright notice, this list of conditions and the following disclaimer
  4317. // in the documentation and/or other materials provided with the
  4318. // distribution.
  4319. // * Neither the name of Google Inc. nor the names of its
  4320. // contributors may be used to endorse or promote products derived from
  4321. // this software without specific prior written permission.
  4322. //
  4323. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4324. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  4325. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  4326. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  4327. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  4328. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4329. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  4330. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  4331. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  4332. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  4333. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4334. //
  4335. // The Google C++ Testing and Mocking Framework (Google Test)
  4336. //
  4337. // This header file defines internal utilities needed for implementing
  4338. // death tests. They are subject to change without notice.
  4339. // GOOGLETEST_CM0001 DO NOT DELETE
  4340. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
  4341. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
  4342. // Copyright 2007, Google Inc.
  4343. // All rights reserved.
  4344. //
  4345. // Redistribution and use in source and binary forms, with or without
  4346. // modification, are permitted provided that the following conditions are
  4347. // met:
  4348. //
  4349. // * Redistributions of source code must retain the above copyright
  4350. // notice, this list of conditions and the following disclaimer.
  4351. // * Redistributions in binary form must reproduce the above
  4352. // copyright notice, this list of conditions and the following disclaimer
  4353. // in the documentation and/or other materials provided with the
  4354. // distribution.
  4355. // * Neither the name of Google Inc. nor the names of its
  4356. // contributors may be used to endorse or promote products derived from
  4357. // this software without specific prior written permission.
  4358. //
  4359. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4360. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  4361. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  4362. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  4363. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  4364. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4365. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  4366. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  4367. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  4368. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  4369. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4370. // The Google C++ Testing and Mocking Framework (Google Test)
  4371. //
  4372. // This file implements just enough of the matcher interface to allow
  4373. // EXPECT_DEATH and friends to accept a matcher argument.
  4374. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
  4375. #define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
  4376. #include <atomic>
  4377. #include <memory>
  4378. #include <ostream>
  4379. #include <string>
  4380. #include <type_traits>
  4381. // Copyright 2007, Google Inc.
  4382. // All rights reserved.
  4383. //
  4384. // Redistribution and use in source and binary forms, with or without
  4385. // modification, are permitted provided that the following conditions are
  4386. // met:
  4387. //
  4388. // * Redistributions of source code must retain the above copyright
  4389. // notice, this list of conditions and the following disclaimer.
  4390. // * Redistributions in binary form must reproduce the above
  4391. // copyright notice, this list of conditions and the following disclaimer
  4392. // in the documentation and/or other materials provided with the
  4393. // distribution.
  4394. // * Neither the name of Google Inc. nor the names of its
  4395. // contributors may be used to endorse or promote products derived from
  4396. // this software without specific prior written permission.
  4397. //
  4398. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4399. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  4400. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  4401. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  4402. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  4403. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4404. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  4405. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  4406. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  4407. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  4408. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4409. // Google Test - The Google C++ Testing and Mocking Framework
  4410. //
  4411. // This file implements a universal value printer that can print a
  4412. // value of any type T:
  4413. //
  4414. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  4415. //
  4416. // A user can teach this function how to print a class type T by
  4417. // defining either operator<<() or PrintTo() in the namespace that
  4418. // defines T. More specifically, the FIRST defined function in the
  4419. // following list will be used (assuming T is defined in namespace
  4420. // foo):
  4421. //
  4422. // 1. foo::PrintTo(const T&, ostream*)
  4423. // 2. operator<<(ostream&, const T&) defined in either foo or the
  4424. // global namespace.
  4425. //
  4426. // However if T is an STL-style container then it is printed element-wise
  4427. // unless foo::PrintTo(const T&, ostream*) is defined. Note that
  4428. // operator<<() is ignored for container types.
  4429. //
  4430. // If none of the above is defined, it will print the debug string of
  4431. // the value if it is a protocol buffer, or print the raw bytes in the
  4432. // value otherwise.
  4433. //
  4434. // To aid debugging: when T is a reference type, the address of the
  4435. // value is also printed; when T is a (const) char pointer, both the
  4436. // pointer value and the NUL-terminated string it points to are
  4437. // printed.
  4438. //
  4439. // We also provide some convenient wrappers:
  4440. //
  4441. // // Prints a value to a string. For a (const or not) char
  4442. // // pointer, the NUL-terminated string (but not the pointer) is
  4443. // // printed.
  4444. // std::string ::testing::PrintToString(const T& value);
  4445. //
  4446. // // Prints a value tersely: for a reference type, the referenced
  4447. // // value (but not the address) is printed; for a (const or not) char
  4448. // // pointer, the NUL-terminated string (but not the pointer) is
  4449. // // printed.
  4450. // void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
  4451. //
  4452. // // Prints value using the type inferred by the compiler. The difference
  4453. // // from UniversalTersePrint() is that this function prints both the
  4454. // // pointer and the NUL-terminated string for a (const or not) char pointer.
  4455. // void ::testing::internal::UniversalPrint(const T& value, ostream*);
  4456. //
  4457. // // Prints the fields of a tuple tersely to a string vector, one
  4458. // // element for each field. Tuple support must be enabled in
  4459. // // gtest-port.h.
  4460. // std::vector<string> UniversalTersePrintTupleFieldsToStrings(
  4461. // const Tuple& value);
  4462. //
  4463. // Known limitation:
  4464. //
  4465. // The print primitives print the elements of an STL-style container
  4466. // using the compiler-inferred type of *iter where iter is a
  4467. // const_iterator of the container. When const_iterator is an input
  4468. // iterator but not a forward iterator, this inferred type may not
  4469. // match value_type, and the print output may be incorrect. In
  4470. // practice, this is rarely a problem as for most containers
  4471. // const_iterator is a forward iterator. We'll fix this if there's an
  4472. // actual need for it. Note that this fix cannot rely on value_type
  4473. // being defined as many user-defined container types don't have
  4474. // value_type.
  4475. // GOOGLETEST_CM0001 DO NOT DELETE
  4476. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
  4477. #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
  4478. #include <functional>
  4479. #include <memory>
  4480. #include <ostream> // NOLINT
  4481. #include <sstream>
  4482. #include <string>
  4483. #include <tuple>
  4484. #include <type_traits>
  4485. #include <utility>
  4486. #include <vector>
  4487. namespace testing {
  4488. // Definitions in the internal* namespaces are subject to change without notice.
  4489. // DO NOT USE THEM IN USER CODE!
  4490. namespace internal {
  4491. template <typename T>
  4492. void UniversalPrint(const T& value, ::std::ostream* os);
  4493. // Used to print an STL-style container when the user doesn't define
  4494. // a PrintTo() for it.
  4495. struct ContainerPrinter {
  4496. template <typename T,
  4497. typename = typename std::enable_if<
  4498. (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
  4499. !IsRecursiveContainer<T>::value>::type>
  4500. static void PrintValue(const T& container, std::ostream* os) {
  4501. const size_t kMaxCount = 32; // The maximum number of elements to print.
  4502. *os << '{';
  4503. size_t count = 0;
  4504. for (auto&& elem : container) {
  4505. if (count > 0) {
  4506. *os << ',';
  4507. if (count == kMaxCount) { // Enough has been printed.
  4508. *os << " ...";
  4509. break;
  4510. }
  4511. }
  4512. *os << ' ';
  4513. // We cannot call PrintTo(elem, os) here as PrintTo() doesn't
  4514. // handle `elem` being a native array.
  4515. internal::UniversalPrint(elem, os);
  4516. ++count;
  4517. }
  4518. if (count > 0) {
  4519. *os << ' ';
  4520. }
  4521. *os << '}';
  4522. }
  4523. };
  4524. // Used to print a pointer that is neither a char pointer nor a member
  4525. // pointer, when the user doesn't define PrintTo() for it. (A member
  4526. // variable pointer or member function pointer doesn't really point to
  4527. // a location in the address space. Their representation is
  4528. // implementation-defined. Therefore they will be printed as raw
  4529. // bytes.)
  4530. struct FunctionPointerPrinter {
  4531. template <typename T, typename = typename std::enable_if<
  4532. std::is_function<T>::value>::type>
  4533. static void PrintValue(T* p, ::std::ostream* os) {
  4534. if (p == nullptr) {
  4535. *os << "NULL";
  4536. } else {
  4537. // T is a function type, so '*os << p' doesn't do what we want
  4538. // (it just prints p as bool). We want to print p as a const
  4539. // void*.
  4540. *os << reinterpret_cast<const void*>(p);
  4541. }
  4542. }
  4543. };
  4544. struct PointerPrinter {
  4545. template <typename T>
  4546. static void PrintValue(T* p, ::std::ostream* os) {
  4547. if (p == nullptr) {
  4548. *os << "NULL";
  4549. } else {
  4550. // T is not a function type. We just call << to print p,
  4551. // relying on ADL to pick up user-defined << for their pointer
  4552. // types, if any.
  4553. *os << p;
  4554. }
  4555. }
  4556. };
  4557. namespace internal_stream_operator_without_lexical_name_lookup {
  4558. // The presence of an operator<< here will terminate lexical scope lookup
  4559. // straight away (even though it cannot be a match because of its argument
  4560. // types). Thus, the two operator<< calls in StreamPrinter will find only ADL
  4561. // candidates.
  4562. struct LookupBlocker {};
  4563. void operator<<(LookupBlocker, LookupBlocker);
  4564. struct StreamPrinter {
  4565. template <typename T,
  4566. // Don't accept member pointers here. We'd print them via implicit
  4567. // conversion to bool, which isn't useful.
  4568. typename = typename std::enable_if<
  4569. !std::is_member_pointer<T>::value>::type,
  4570. // Only accept types for which we can find a streaming operator via
  4571. // ADL (possibly involving implicit conversions).
  4572. typename = decltype(std::declval<std::ostream&>()
  4573. << std::declval<const T&>())>
  4574. static void PrintValue(const T& value, ::std::ostream* os) {
  4575. // Call streaming operator found by ADL, possibly with implicit conversions
  4576. // of the arguments.
  4577. *os << value;
  4578. }
  4579. };
  4580. } // namespace internal_stream_operator_without_lexical_name_lookup
  4581. struct ProtobufPrinter {
  4582. // We print a protobuf using its ShortDebugString() when the string
  4583. // doesn't exceed this many characters; otherwise we print it using
  4584. // DebugString() for better readability.
  4585. static const size_t kProtobufOneLinerMaxLength = 50;
  4586. template <typename T,
  4587. typename = typename std::enable_if<
  4588. internal::HasDebugStringAndShortDebugString<T>::value>::type>
  4589. static void PrintValue(const T& value, ::std::ostream* os) {
  4590. std::string pretty_str = value.ShortDebugString();
  4591. if (pretty_str.length() > kProtobufOneLinerMaxLength) {
  4592. pretty_str = "\n" + value.DebugString();
  4593. }
  4594. *os << ("<" + pretty_str + ">");
  4595. }
  4596. };
  4597. struct ConvertibleToIntegerPrinter {
  4598. // Since T has no << operator or PrintTo() but can be implicitly
  4599. // converted to BiggestInt, we print it as a BiggestInt.
  4600. //
  4601. // Most likely T is an enum type (either named or unnamed), in which
  4602. // case printing it as an integer is the desired behavior. In case
  4603. // T is not an enum, printing it as an integer is the best we can do
  4604. // given that it has no user-defined printer.
  4605. static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {
  4606. *os << value;
  4607. }
  4608. };
  4609. struct ConvertibleToStringViewPrinter {
  4610. #if GTEST_INTERNAL_HAS_STRING_VIEW
  4611. static void PrintValue(internal::StringView value, ::std::ostream* os) {
  4612. internal::UniversalPrint(value, os);
  4613. }
  4614. #endif
  4615. };
  4616. // Prints the given number of bytes in the given object to the given
  4617. // ostream.
  4618. GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
  4619. size_t count,
  4620. ::std::ostream* os);
  4621. struct RawBytesPrinter {
  4622. // SFINAE on `sizeof` to make sure we have a complete type.
  4623. template <typename T, size_t = sizeof(T)>
  4624. static void PrintValue(const T& value, ::std::ostream* os) {
  4625. PrintBytesInObjectTo(
  4626. static_cast<const unsigned char*>(
  4627. // Load bearing cast to void* to support iOS
  4628. reinterpret_cast<const void*>(std::addressof(value))),
  4629. sizeof(value), os);
  4630. }
  4631. };
  4632. struct FallbackPrinter {
  4633. template <typename T>
  4634. static void PrintValue(const T&, ::std::ostream* os) {
  4635. *os << "(incomplete type)";
  4636. }
  4637. };
  4638. // Try every printer in order and return the first one that works.
  4639. template <typename T, typename E, typename Printer, typename... Printers>
  4640. struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
  4641. template <typename T, typename Printer, typename... Printers>
  4642. struct FindFirstPrinter<
  4643. T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),
  4644. Printer, Printers...> {
  4645. using type = Printer;
  4646. };
  4647. // Select the best printer in the following order:
  4648. // - Print containers (they have begin/end/etc).
  4649. // - Print function pointers.
  4650. // - Print object pointers.
  4651. // - Use the stream operator, if available.
  4652. // - Print protocol buffers.
  4653. // - Print types convertible to BiggestInt.
  4654. // - Print types convertible to StringView, if available.
  4655. // - Fallback to printing the raw bytes of the object.
  4656. template <typename T>
  4657. void PrintWithFallback(const T& value, ::std::ostream* os) {
  4658. using Printer = typename FindFirstPrinter<
  4659. T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
  4660. internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
  4661. ProtobufPrinter, ConvertibleToIntegerPrinter,
  4662. ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type;
  4663. Printer::PrintValue(value, os);
  4664. }
  4665. // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
  4666. // value of type ToPrint that is an operand of a comparison assertion
  4667. // (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
  4668. // the comparison, and is used to help determine the best way to
  4669. // format the value. In particular, when the value is a C string
  4670. // (char pointer) and the other operand is an STL string object, we
  4671. // want to format the C string as a string, since we know it is
  4672. // compared by value with the string object. If the value is a char
  4673. // pointer but the other operand is not an STL string object, we don't
  4674. // know whether the pointer is supposed to point to a NUL-terminated
  4675. // string, and thus want to print it as a pointer to be safe.
  4676. //
  4677. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  4678. // The default case.
  4679. template <typename ToPrint, typename OtherOperand>
  4680. class FormatForComparison {
  4681. public:
  4682. static ::std::string Format(const ToPrint& value) {
  4683. return ::testing::PrintToString(value);
  4684. }
  4685. };
  4686. // Array.
  4687. template <typename ToPrint, size_t N, typename OtherOperand>
  4688. class FormatForComparison<ToPrint[N], OtherOperand> {
  4689. public:
  4690. static ::std::string Format(const ToPrint* value) {
  4691. return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
  4692. }
  4693. };
  4694. // By default, print C string as pointers to be safe, as we don't know
  4695. // whether they actually point to a NUL-terminated string.
  4696. #define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \
  4697. template <typename OtherOperand> \
  4698. class FormatForComparison<CharType*, OtherOperand> { \
  4699. public: \
  4700. static ::std::string Format(CharType* value) { \
  4701. return ::testing::PrintToString(static_cast<const void*>(value)); \
  4702. } \
  4703. }
  4704. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
  4705. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
  4706. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
  4707. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
  4708. #ifdef __cpp_char8_t
  4709. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
  4710. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
  4711. #endif
  4712. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
  4713. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
  4714. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
  4715. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
  4716. #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
  4717. // If a C string is compared with an STL string object, we know it's meant
  4718. // to point to a NUL-terminated string, and thus can print it as a string.
  4719. #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
  4720. template <> \
  4721. class FormatForComparison<CharType*, OtherStringType> { \
  4722. public: \
  4723. static ::std::string Format(CharType* value) { \
  4724. return ::testing::PrintToString(value); \
  4725. } \
  4726. }
  4727. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
  4728. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
  4729. #ifdef __cpp_char8_t
  4730. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
  4731. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
  4732. #endif
  4733. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
  4734. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
  4735. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
  4736. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
  4737. #if GTEST_HAS_STD_WSTRING
  4738. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
  4739. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
  4740. #endif
  4741. #undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
  4742. // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
  4743. // operand to be used in a failure message. The type (but not value)
  4744. // of the other operand may affect the format. This allows us to
  4745. // print a char* as a raw pointer when it is compared against another
  4746. // char* or void*, and print it as a C string when it is compared
  4747. // against an std::string object, for example.
  4748. //
  4749. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  4750. template <typename T1, typename T2>
  4751. std::string FormatForComparisonFailureMessage(
  4752. const T1& value, const T2& /* other_operand */) {
  4753. return FormatForComparison<T1, T2>::Format(value);
  4754. }
  4755. // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
  4756. // value to the given ostream. The caller must ensure that
  4757. // 'ostream_ptr' is not NULL, or the behavior is undefined.
  4758. //
  4759. // We define UniversalPrinter as a class template (as opposed to a
  4760. // function template), as we need to partially specialize it for
  4761. // reference types, which cannot be done with function templates.
  4762. template <typename T>
  4763. class UniversalPrinter;
  4764. // Prints the given value using the << operator if it has one;
  4765. // otherwise prints the bytes in it. This is what
  4766. // UniversalPrinter<T>::Print() does when PrintTo() is not specialized
  4767. // or overloaded for type T.
  4768. //
  4769. // A user can override this behavior for a class type Foo by defining
  4770. // an overload of PrintTo() in the namespace where Foo is defined. We
  4771. // give the user this option as sometimes defining a << operator for
  4772. // Foo is not desirable (e.g. the coding style may prevent doing it,
  4773. // or there is already a << operator but it doesn't do what the user
  4774. // wants).
  4775. template <typename T>
  4776. void PrintTo(const T& value, ::std::ostream* os) {
  4777. internal::PrintWithFallback(value, os);
  4778. }
  4779. // The following list of PrintTo() overloads tells
  4780. // UniversalPrinter<T>::Print() how to print standard types (built-in
  4781. // types, strings, plain arrays, and pointers).
  4782. // Overloads for various char types.
  4783. GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
  4784. GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
  4785. inline void PrintTo(char c, ::std::ostream* os) {
  4786. // When printing a plain char, we always treat it as unsigned. This
  4787. // way, the output won't be affected by whether the compiler thinks
  4788. // char is signed or not.
  4789. PrintTo(static_cast<unsigned char>(c), os);
  4790. }
  4791. // Overloads for other simple built-in types.
  4792. inline void PrintTo(bool x, ::std::ostream* os) {
  4793. *os << (x ? "true" : "false");
  4794. }
  4795. // Overload for wchar_t type.
  4796. // Prints a wchar_t as a symbol if it is printable or as its internal
  4797. // code otherwise and also as its decimal code (except for L'\0').
  4798. // The L'\0' char is printed as "L'\\0'". The decimal code is printed
  4799. // as signed integer when wchar_t is implemented by the compiler
  4800. // as a signed type and is printed as an unsigned integer when wchar_t
  4801. // is implemented as an unsigned type.
  4802. GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
  4803. GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
  4804. inline void PrintTo(char16_t c, ::std::ostream* os) {
  4805. PrintTo(ImplicitCast_<char32_t>(c), os);
  4806. }
  4807. #ifdef __cpp_char8_t
  4808. inline void PrintTo(char8_t c, ::std::ostream* os) {
  4809. PrintTo(ImplicitCast_<char32_t>(c), os);
  4810. }
  4811. #endif
  4812. // Overloads for C strings.
  4813. GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
  4814. inline void PrintTo(char* s, ::std::ostream* os) {
  4815. PrintTo(ImplicitCast_<const char*>(s), os);
  4816. }
  4817. // signed/unsigned char is often used for representing binary data, so
  4818. // we print pointers to it as void* to be safe.
  4819. inline void PrintTo(const signed char* s, ::std::ostream* os) {
  4820. PrintTo(ImplicitCast_<const void*>(s), os);
  4821. }
  4822. inline void PrintTo(signed char* s, ::std::ostream* os) {
  4823. PrintTo(ImplicitCast_<const void*>(s), os);
  4824. }
  4825. inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
  4826. PrintTo(ImplicitCast_<const void*>(s), os);
  4827. }
  4828. inline void PrintTo(unsigned char* s, ::std::ostream* os) {
  4829. PrintTo(ImplicitCast_<const void*>(s), os);
  4830. }
  4831. #ifdef __cpp_char8_t
  4832. // Overloads for u8 strings.
  4833. GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);
  4834. inline void PrintTo(char8_t* s, ::std::ostream* os) {
  4835. PrintTo(ImplicitCast_<const char8_t*>(s), os);
  4836. }
  4837. #endif
  4838. // Overloads for u16 strings.
  4839. GTEST_API_ void PrintTo(const char16_t* s, ::std::ostream* os);
  4840. inline void PrintTo(char16_t* s, ::std::ostream* os) {
  4841. PrintTo(ImplicitCast_<const char16_t*>(s), os);
  4842. }
  4843. // Overloads for u32 strings.
  4844. GTEST_API_ void PrintTo(const char32_t* s, ::std::ostream* os);
  4845. inline void PrintTo(char32_t* s, ::std::ostream* os) {
  4846. PrintTo(ImplicitCast_<const char32_t*>(s), os);
  4847. }
  4848. // MSVC can be configured to define wchar_t as a typedef of unsigned
  4849. // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
  4850. // type. When wchar_t is a typedef, defining an overload for const
  4851. // wchar_t* would cause unsigned short* be printed as a wide string,
  4852. // possibly causing invalid memory accesses.
  4853. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  4854. // Overloads for wide C strings
  4855. GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
  4856. inline void PrintTo(wchar_t* s, ::std::ostream* os) {
  4857. PrintTo(ImplicitCast_<const wchar_t*>(s), os);
  4858. }
  4859. #endif
  4860. // Overload for C arrays. Multi-dimensional arrays are printed
  4861. // properly.
  4862. // Prints the given number of elements in an array, without printing
  4863. // the curly braces.
  4864. template <typename T>
  4865. void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
  4866. UniversalPrint(a[0], os);
  4867. for (size_t i = 1; i != count; i++) {
  4868. *os << ", ";
  4869. UniversalPrint(a[i], os);
  4870. }
  4871. }
  4872. // Overloads for ::std::string.
  4873. GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
  4874. inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
  4875. PrintStringTo(s, os);
  4876. }
  4877. // Overloads for ::std::u8string
  4878. #ifdef __cpp_char8_t
  4879. GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
  4880. inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
  4881. PrintU8StringTo(s, os);
  4882. }
  4883. #endif
  4884. // Overloads for ::std::u16string
  4885. GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
  4886. inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
  4887. PrintU16StringTo(s, os);
  4888. }
  4889. // Overloads for ::std::u32string
  4890. GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
  4891. inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
  4892. PrintU32StringTo(s, os);
  4893. }
  4894. // Overloads for ::std::wstring.
  4895. #if GTEST_HAS_STD_WSTRING
  4896. GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
  4897. inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
  4898. PrintWideStringTo(s, os);
  4899. }
  4900. #endif // GTEST_HAS_STD_WSTRING
  4901. #if GTEST_INTERNAL_HAS_STRING_VIEW
  4902. // Overload for internal::StringView.
  4903. inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
  4904. PrintTo(::std::string(sp), os);
  4905. }
  4906. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  4907. inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
  4908. template <typename T>
  4909. void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
  4910. UniversalPrinter<T&>::Print(ref.get(), os);
  4911. }
  4912. inline const void* VoidifyPointer(const void* p) { return p; }
  4913. inline const void* VoidifyPointer(volatile const void* p) {
  4914. return const_cast<const void*>(p);
  4915. }
  4916. template <typename T, typename Ptr>
  4917. void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {
  4918. if (ptr == nullptr) {
  4919. *os << "(nullptr)";
  4920. } else {
  4921. // We can't print the value. Just print the pointer..
  4922. *os << "(" << (VoidifyPointer)(ptr.get()) << ")";
  4923. }
  4924. }
  4925. template <typename T, typename Ptr,
  4926. typename = typename std::enable_if<!std::is_void<T>::value &&
  4927. !std::is_array<T>::value>::type>
  4928. void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {
  4929. if (ptr == nullptr) {
  4930. *os << "(nullptr)";
  4931. } else {
  4932. *os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";
  4933. UniversalPrinter<T>::Print(*ptr, os);
  4934. *os << ")";
  4935. }
  4936. }
  4937. template <typename T, typename D>
  4938. void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {
  4939. (PrintSmartPointer<T>)(ptr, os, 0);
  4940. }
  4941. template <typename T>
  4942. void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
  4943. (PrintSmartPointer<T>)(ptr, os, 0);
  4944. }
  4945. // Helper function for printing a tuple. T must be instantiated with
  4946. // a tuple type.
  4947. template <typename T>
  4948. void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
  4949. ::std::ostream*) {}
  4950. template <typename T, size_t I>
  4951. void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
  4952. ::std::ostream* os) {
  4953. PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
  4954. GTEST_INTENTIONAL_CONST_COND_PUSH_()
  4955. if (I > 1) {
  4956. GTEST_INTENTIONAL_CONST_COND_POP_()
  4957. *os << ", ";
  4958. }
  4959. UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
  4960. std::get<I - 1>(t), os);
  4961. }
  4962. template <typename... Types>
  4963. void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
  4964. *os << "(";
  4965. PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
  4966. *os << ")";
  4967. }
  4968. // Overload for std::pair.
  4969. template <typename T1, typename T2>
  4970. void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
  4971. *os << '(';
  4972. // We cannot use UniversalPrint(value.first, os) here, as T1 may be
  4973. // a reference type. The same for printing value.second.
  4974. UniversalPrinter<T1>::Print(value.first, os);
  4975. *os << ", ";
  4976. UniversalPrinter<T2>::Print(value.second, os);
  4977. *os << ')';
  4978. }
  4979. // Implements printing a non-reference type T by letting the compiler
  4980. // pick the right overload of PrintTo() for T.
  4981. template <typename T>
  4982. class UniversalPrinter {
  4983. public:
  4984. // MSVC warns about adding const to a function type, so we want to
  4985. // disable the warning.
  4986. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
  4987. // Note: we deliberately don't call this PrintTo(), as that name
  4988. // conflicts with ::testing::internal::PrintTo in the body of the
  4989. // function.
  4990. static void Print(const T& value, ::std::ostream* os) {
  4991. // By default, ::testing::internal::PrintTo() is used for printing
  4992. // the value.
  4993. //
  4994. // Thanks to Koenig look-up, if T is a class and has its own
  4995. // PrintTo() function defined in its namespace, that function will
  4996. // be visible here. Since it is more specific than the generic ones
  4997. // in ::testing::internal, it will be picked by the compiler in the
  4998. // following statement - exactly what we want.
  4999. PrintTo(value, os);
  5000. }
  5001. GTEST_DISABLE_MSC_WARNINGS_POP_()
  5002. };
  5003. // Remove any const-qualifiers before passing a type to UniversalPrinter.
  5004. template <typename T>
  5005. class UniversalPrinter<const T> : public UniversalPrinter<T> {};
  5006. #if GTEST_INTERNAL_HAS_ANY
  5007. // Printer for std::any / absl::any
  5008. template <>
  5009. class UniversalPrinter<Any> {
  5010. public:
  5011. static void Print(const Any& value, ::std::ostream* os) {
  5012. if (value.has_value()) {
  5013. *os << "value of type " << GetTypeName(value);
  5014. } else {
  5015. *os << "no value";
  5016. }
  5017. }
  5018. private:
  5019. static std::string GetTypeName(const Any& value) {
  5020. #if GTEST_HAS_RTTI
  5021. return internal::GetTypeName(value.type());
  5022. #else
  5023. static_cast<void>(value); // possibly unused
  5024. return "<unknown_type>";
  5025. #endif // GTEST_HAS_RTTI
  5026. }
  5027. };
  5028. #endif // GTEST_INTERNAL_HAS_ANY
  5029. #if GTEST_INTERNAL_HAS_OPTIONAL
  5030. // Printer for std::optional / absl::optional
  5031. template <typename T>
  5032. class UniversalPrinter<Optional<T>> {
  5033. public:
  5034. static void Print(const Optional<T>& value, ::std::ostream* os) {
  5035. *os << '(';
  5036. if (!value) {
  5037. *os << "nullopt";
  5038. } else {
  5039. UniversalPrint(*value, os);
  5040. }
  5041. *os << ')';
  5042. }
  5043. };
  5044. #endif // GTEST_INTERNAL_HAS_OPTIONAL
  5045. #if GTEST_INTERNAL_HAS_VARIANT
  5046. // Printer for std::variant / absl::variant
  5047. template <typename... T>
  5048. class UniversalPrinter<Variant<T...>> {
  5049. public:
  5050. static void Print(const Variant<T...>& value, ::std::ostream* os) {
  5051. *os << '(';
  5052. #if GTEST_HAS_ABSL
  5053. absl::visit(Visitor{os, value.index()}, value);
  5054. #else
  5055. std::visit(Visitor{os, value.index()}, value);
  5056. #endif // GTEST_HAS_ABSL
  5057. *os << ')';
  5058. }
  5059. private:
  5060. struct Visitor {
  5061. template <typename U>
  5062. void operator()(const U& u) const {
  5063. *os << "'" << GetTypeName<U>() << "(index = " << index
  5064. << ")' with value ";
  5065. UniversalPrint(u, os);
  5066. }
  5067. ::std::ostream* os;
  5068. std::size_t index;
  5069. };
  5070. };
  5071. #endif // GTEST_INTERNAL_HAS_VARIANT
  5072. // UniversalPrintArray(begin, len, os) prints an array of 'len'
  5073. // elements, starting at address 'begin'.
  5074. template <typename T>
  5075. void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
  5076. if (len == 0) {
  5077. *os << "{}";
  5078. } else {
  5079. *os << "{ ";
  5080. const size_t kThreshold = 18;
  5081. const size_t kChunkSize = 8;
  5082. // If the array has more than kThreshold elements, we'll have to
  5083. // omit some details by printing only the first and the last
  5084. // kChunkSize elements.
  5085. if (len <= kThreshold) {
  5086. PrintRawArrayTo(begin, len, os);
  5087. } else {
  5088. PrintRawArrayTo(begin, kChunkSize, os);
  5089. *os << ", ..., ";
  5090. PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
  5091. }
  5092. *os << " }";
  5093. }
  5094. }
  5095. // This overload prints a (const) char array compactly.
  5096. GTEST_API_ void UniversalPrintArray(
  5097. const char* begin, size_t len, ::std::ostream* os);
  5098. #ifdef __cpp_char8_t
  5099. // This overload prints a (const) char8_t array compactly.
  5100. GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
  5101. ::std::ostream* os);
  5102. #endif
  5103. // This overload prints a (const) char16_t array compactly.
  5104. GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,
  5105. ::std::ostream* os);
  5106. // This overload prints a (const) char32_t array compactly.
  5107. GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
  5108. ::std::ostream* os);
  5109. // This overload prints a (const) wchar_t array compactly.
  5110. GTEST_API_ void UniversalPrintArray(
  5111. const wchar_t* begin, size_t len, ::std::ostream* os);
  5112. // Implements printing an array type T[N].
  5113. template <typename T, size_t N>
  5114. class UniversalPrinter<T[N]> {
  5115. public:
  5116. // Prints the given array, omitting some elements when there are too
  5117. // many.
  5118. static void Print(const T (&a)[N], ::std::ostream* os) {
  5119. UniversalPrintArray(a, N, os);
  5120. }
  5121. };
  5122. // Implements printing a reference type T&.
  5123. template <typename T>
  5124. class UniversalPrinter<T&> {
  5125. public:
  5126. // MSVC warns about adding const to a function type, so we want to
  5127. // disable the warning.
  5128. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
  5129. static void Print(const T& value, ::std::ostream* os) {
  5130. // Prints the address of the value. We use reinterpret_cast here
  5131. // as static_cast doesn't compile when T is a function type.
  5132. *os << "@" << reinterpret_cast<const void*>(&value) << " ";
  5133. // Then prints the value itself.
  5134. UniversalPrint(value, os);
  5135. }
  5136. GTEST_DISABLE_MSC_WARNINGS_POP_()
  5137. };
  5138. // Prints a value tersely: for a reference type, the referenced value
  5139. // (but not the address) is printed; for a (const) char pointer, the
  5140. // NUL-terminated string (but not the pointer) is printed.
  5141. template <typename T>
  5142. class UniversalTersePrinter {
  5143. public:
  5144. static void Print(const T& value, ::std::ostream* os) {
  5145. UniversalPrint(value, os);
  5146. }
  5147. };
  5148. template <typename T>
  5149. class UniversalTersePrinter<T&> {
  5150. public:
  5151. static void Print(const T& value, ::std::ostream* os) {
  5152. UniversalPrint(value, os);
  5153. }
  5154. };
  5155. template <typename T, size_t N>
  5156. class UniversalTersePrinter<T[N]> {
  5157. public:
  5158. static void Print(const T (&value)[N], ::std::ostream* os) {
  5159. UniversalPrinter<T[N]>::Print(value, os);
  5160. }
  5161. };
  5162. template <>
  5163. class UniversalTersePrinter<const char*> {
  5164. public:
  5165. static void Print(const char* str, ::std::ostream* os) {
  5166. if (str == nullptr) {
  5167. *os << "NULL";
  5168. } else {
  5169. UniversalPrint(std::string(str), os);
  5170. }
  5171. }
  5172. };
  5173. template <>
  5174. class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
  5175. };
  5176. #ifdef __cpp_char8_t
  5177. template <>
  5178. class UniversalTersePrinter<const char8_t*> {
  5179. public:
  5180. static void Print(const char8_t* str, ::std::ostream* os) {
  5181. if (str == nullptr) {
  5182. *os << "NULL";
  5183. } else {
  5184. UniversalPrint(::std::u8string(str), os);
  5185. }
  5186. }
  5187. };
  5188. template <>
  5189. class UniversalTersePrinter<char8_t*>
  5190. : public UniversalTersePrinter<const char8_t*> {};
  5191. #endif
  5192. template <>
  5193. class UniversalTersePrinter<const char16_t*> {
  5194. public:
  5195. static void Print(const char16_t* str, ::std::ostream* os) {
  5196. if (str == nullptr) {
  5197. *os << "NULL";
  5198. } else {
  5199. UniversalPrint(::std::u16string(str), os);
  5200. }
  5201. }
  5202. };
  5203. template <>
  5204. class UniversalTersePrinter<char16_t*>
  5205. : public UniversalTersePrinter<const char16_t*> {};
  5206. template <>
  5207. class UniversalTersePrinter<const char32_t*> {
  5208. public:
  5209. static void Print(const char32_t* str, ::std::ostream* os) {
  5210. if (str == nullptr) {
  5211. *os << "NULL";
  5212. } else {
  5213. UniversalPrint(::std::u32string(str), os);
  5214. }
  5215. }
  5216. };
  5217. template <>
  5218. class UniversalTersePrinter<char32_t*>
  5219. : public UniversalTersePrinter<const char32_t*> {};
  5220. #if GTEST_HAS_STD_WSTRING
  5221. template <>
  5222. class UniversalTersePrinter<const wchar_t*> {
  5223. public:
  5224. static void Print(const wchar_t* str, ::std::ostream* os) {
  5225. if (str == nullptr) {
  5226. *os << "NULL";
  5227. } else {
  5228. UniversalPrint(::std::wstring(str), os);
  5229. }
  5230. }
  5231. };
  5232. #endif
  5233. template <>
  5234. class UniversalTersePrinter<wchar_t*> {
  5235. public:
  5236. static void Print(wchar_t* str, ::std::ostream* os) {
  5237. UniversalTersePrinter<const wchar_t*>::Print(str, os);
  5238. }
  5239. };
  5240. template <typename T>
  5241. void UniversalTersePrint(const T& value, ::std::ostream* os) {
  5242. UniversalTersePrinter<T>::Print(value, os);
  5243. }
  5244. // Prints a value using the type inferred by the compiler. The
  5245. // difference between this and UniversalTersePrint() is that for a
  5246. // (const) char pointer, this prints both the pointer and the
  5247. // NUL-terminated string.
  5248. template <typename T>
  5249. void UniversalPrint(const T& value, ::std::ostream* os) {
  5250. // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
  5251. // UniversalPrinter with T directly.
  5252. typedef T T1;
  5253. UniversalPrinter<T1>::Print(value, os);
  5254. }
  5255. typedef ::std::vector< ::std::string> Strings;
  5256. // Tersely prints the first N fields of a tuple to a string vector,
  5257. // one element for each field.
  5258. template <typename Tuple>
  5259. void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
  5260. Strings*) {}
  5261. template <typename Tuple, size_t I>
  5262. void TersePrintPrefixToStrings(const Tuple& t,
  5263. std::integral_constant<size_t, I>,
  5264. Strings* strings) {
  5265. TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
  5266. strings);
  5267. ::std::stringstream ss;
  5268. UniversalTersePrint(std::get<I - 1>(t), &ss);
  5269. strings->push_back(ss.str());
  5270. }
  5271. // Prints the fields of a tuple tersely to a string vector, one
  5272. // element for each field. See the comment before
  5273. // UniversalTersePrint() for how we define "tersely".
  5274. template <typename Tuple>
  5275. Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
  5276. Strings result;
  5277. TersePrintPrefixToStrings(
  5278. value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
  5279. &result);
  5280. return result;
  5281. }
  5282. } // namespace internal
  5283. template <typename T>
  5284. ::std::string PrintToString(const T& value) {
  5285. ::std::stringstream ss;
  5286. internal::UniversalTersePrinter<T>::Print(value, &ss);
  5287. return ss.str();
  5288. }
  5289. } // namespace testing
  5290. // Include any custom printer added by the local installation.
  5291. // We must include this header at the end to make sure it can use the
  5292. // declarations from this file.
  5293. // Copyright 2015, Google Inc.
  5294. // All rights reserved.
  5295. //
  5296. // Redistribution and use in source and binary forms, with or without
  5297. // modification, are permitted provided that the following conditions are
  5298. // met:
  5299. //
  5300. // * Redistributions of source code must retain the above copyright
  5301. // notice, this list of conditions and the following disclaimer.
  5302. // * Redistributions in binary form must reproduce the above
  5303. // copyright notice, this list of conditions and the following disclaimer
  5304. // in the documentation and/or other materials provided with the
  5305. // distribution.
  5306. // * Neither the name of Google Inc. nor the names of its
  5307. // contributors may be used to endorse or promote products derived from
  5308. // this software without specific prior written permission.
  5309. //
  5310. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  5311. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5312. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  5313. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  5314. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  5315. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5316. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  5317. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  5318. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  5319. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  5320. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5321. //
  5322. // This file provides an injection point for custom printers in a local
  5323. // installation of gTest.
  5324. // It will be included from gtest-printers.h and the overrides in this file
  5325. // will be visible to everyone.
  5326. //
  5327. // Injection point for custom user configurations. See README for details
  5328. //
  5329. // ** Custom implementation starts here **
  5330. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
  5331. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
  5332. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
  5333. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
  5334. // MSVC warning C5046 is new as of VS2017 version 15.8.
  5335. #if defined(_MSC_VER) && _MSC_VER >= 1915
  5336. #define GTEST_MAYBE_5046_ 5046
  5337. #else
  5338. #define GTEST_MAYBE_5046_
  5339. #endif
  5340. GTEST_DISABLE_MSC_WARNINGS_PUSH_(
  5341. 4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
  5342. clients of class B */
  5343. /* Symbol involving type with internal linkage not defined */)
  5344. namespace testing {
  5345. // To implement a matcher Foo for type T, define:
  5346. // 1. a class FooMatcherMatcher that implements the matcher interface:
  5347. // using is_gtest_matcher = void;
  5348. // bool MatchAndExplain(const T&, std::ostream*);
  5349. // (MatchResultListener* can also be used instead of std::ostream*)
  5350. // void DescribeTo(std::ostream*);
  5351. // void DescribeNegationTo(std::ostream*);
  5352. //
  5353. // 2. a factory function that creates a Matcher<T> object from a
  5354. // FooMatcherMatcher.
  5355. class MatchResultListener {
  5356. public:
  5357. // Creates a listener object with the given underlying ostream. The
  5358. // listener does not own the ostream, and does not dereference it
  5359. // in the constructor or destructor.
  5360. explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
  5361. virtual ~MatchResultListener() = 0; // Makes this class abstract.
  5362. // Streams x to the underlying ostream; does nothing if the ostream
  5363. // is NULL.
  5364. template <typename T>
  5365. MatchResultListener& operator<<(const T& x) {
  5366. if (stream_ != nullptr) *stream_ << x;
  5367. return *this;
  5368. }
  5369. // Returns the underlying ostream.
  5370. ::std::ostream* stream() { return stream_; }
  5371. // Returns true if and only if the listener is interested in an explanation
  5372. // of the match result. A matcher's MatchAndExplain() method can use
  5373. // this information to avoid generating the explanation when no one
  5374. // intends to hear it.
  5375. bool IsInterested() const { return stream_ != nullptr; }
  5376. private:
  5377. ::std::ostream* const stream_;
  5378. GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
  5379. };
  5380. inline MatchResultListener::~MatchResultListener() {
  5381. }
  5382. // An instance of a subclass of this knows how to describe itself as a
  5383. // matcher.
  5384. class GTEST_API_ MatcherDescriberInterface {
  5385. public:
  5386. virtual ~MatcherDescriberInterface() {}
  5387. // Describes this matcher to an ostream. The function should print
  5388. // a verb phrase that describes the property a value matching this
  5389. // matcher should have. The subject of the verb phrase is the value
  5390. // being matched. For example, the DescribeTo() method of the Gt(7)
  5391. // matcher prints "is greater than 7".
  5392. virtual void DescribeTo(::std::ostream* os) const = 0;
  5393. // Describes the negation of this matcher to an ostream. For
  5394. // example, if the description of this matcher is "is greater than
  5395. // 7", the negated description could be "is not greater than 7".
  5396. // You are not required to override this when implementing
  5397. // MatcherInterface, but it is highly advised so that your matcher
  5398. // can produce good error messages.
  5399. virtual void DescribeNegationTo(::std::ostream* os) const {
  5400. *os << "not (";
  5401. DescribeTo(os);
  5402. *os << ")";
  5403. }
  5404. };
  5405. // The implementation of a matcher.
  5406. template <typename T>
  5407. class MatcherInterface : public MatcherDescriberInterface {
  5408. public:
  5409. // Returns true if and only if the matcher matches x; also explains the
  5410. // match result to 'listener' if necessary (see the next paragraph), in
  5411. // the form of a non-restrictive relative clause ("which ...",
  5412. // "whose ...", etc) that describes x. For example, the
  5413. // MatchAndExplain() method of the Pointee(...) matcher should
  5414. // generate an explanation like "which points to ...".
  5415. //
  5416. // Implementations of MatchAndExplain() should add an explanation of
  5417. // the match result *if and only if* they can provide additional
  5418. // information that's not already present (or not obvious) in the
  5419. // print-out of x and the matcher's description. Whether the match
  5420. // succeeds is not a factor in deciding whether an explanation is
  5421. // needed, as sometimes the caller needs to print a failure message
  5422. // when the match succeeds (e.g. when the matcher is used inside
  5423. // Not()).
  5424. //
  5425. // For example, a "has at least 10 elements" matcher should explain
  5426. // what the actual element count is, regardless of the match result,
  5427. // as it is useful information to the reader; on the other hand, an
  5428. // "is empty" matcher probably only needs to explain what the actual
  5429. // size is when the match fails, as it's redundant to say that the
  5430. // size is 0 when the value is already known to be empty.
  5431. //
  5432. // You should override this method when defining a new matcher.
  5433. //
  5434. // It's the responsibility of the caller (Google Test) to guarantee
  5435. // that 'listener' is not NULL. This helps to simplify a matcher's
  5436. // implementation when it doesn't care about the performance, as it
  5437. // can talk to 'listener' without checking its validity first.
  5438. // However, in order to implement dummy listeners efficiently,
  5439. // listener->stream() may be NULL.
  5440. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
  5441. // Inherits these methods from MatcherDescriberInterface:
  5442. // virtual void DescribeTo(::std::ostream* os) const = 0;
  5443. // virtual void DescribeNegationTo(::std::ostream* os) const;
  5444. };
  5445. namespace internal {
  5446. struct AnyEq {
  5447. template <typename A, typename B>
  5448. bool operator()(const A& a, const B& b) const { return a == b; }
  5449. };
  5450. struct AnyNe {
  5451. template <typename A, typename B>
  5452. bool operator()(const A& a, const B& b) const { return a != b; }
  5453. };
  5454. struct AnyLt {
  5455. template <typename A, typename B>
  5456. bool operator()(const A& a, const B& b) const { return a < b; }
  5457. };
  5458. struct AnyGt {
  5459. template <typename A, typename B>
  5460. bool operator()(const A& a, const B& b) const { return a > b; }
  5461. };
  5462. struct AnyLe {
  5463. template <typename A, typename B>
  5464. bool operator()(const A& a, const B& b) const { return a <= b; }
  5465. };
  5466. struct AnyGe {
  5467. template <typename A, typename B>
  5468. bool operator()(const A& a, const B& b) const { return a >= b; }
  5469. };
  5470. // A match result listener that ignores the explanation.
  5471. class DummyMatchResultListener : public MatchResultListener {
  5472. public:
  5473. DummyMatchResultListener() : MatchResultListener(nullptr) {}
  5474. private:
  5475. GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
  5476. };
  5477. // A match result listener that forwards the explanation to a given
  5478. // ostream. The difference between this and MatchResultListener is
  5479. // that the former is concrete.
  5480. class StreamMatchResultListener : public MatchResultListener {
  5481. public:
  5482. explicit StreamMatchResultListener(::std::ostream* os)
  5483. : MatchResultListener(os) {}
  5484. private:
  5485. GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
  5486. };
  5487. struct SharedPayloadBase {
  5488. std::atomic<int> ref{1};
  5489. void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
  5490. bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
  5491. };
  5492. template <typename T>
  5493. struct SharedPayload : SharedPayloadBase {
  5494. explicit SharedPayload(const T& v) : value(v) {}
  5495. explicit SharedPayload(T&& v) : value(std::move(v)) {}
  5496. static void Destroy(SharedPayloadBase* shared) {
  5497. delete static_cast<SharedPayload*>(shared);
  5498. }
  5499. T value;
  5500. };
  5501. // An internal class for implementing Matcher<T>, which will derive
  5502. // from it. We put functionalities common to all Matcher<T>
  5503. // specializations here to avoid code duplication.
  5504. template <typename T>
  5505. class MatcherBase : private MatcherDescriberInterface {
  5506. public:
  5507. // Returns true if and only if the matcher matches x; also explains the
  5508. // match result to 'listener'.
  5509. bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
  5510. GTEST_CHECK_(vtable_ != nullptr);
  5511. return vtable_->match_and_explain(*this, x, listener);
  5512. }
  5513. // Returns true if and only if this matcher matches x.
  5514. bool Matches(const T& x) const {
  5515. DummyMatchResultListener dummy;
  5516. return MatchAndExplain(x, &dummy);
  5517. }
  5518. // Describes this matcher to an ostream.
  5519. void DescribeTo(::std::ostream* os) const final {
  5520. GTEST_CHECK_(vtable_ != nullptr);
  5521. vtable_->describe(*this, os, false);
  5522. }
  5523. // Describes the negation of this matcher to an ostream.
  5524. void DescribeNegationTo(::std::ostream* os) const final {
  5525. GTEST_CHECK_(vtable_ != nullptr);
  5526. vtable_->describe(*this, os, true);
  5527. }
  5528. // Explains why x matches, or doesn't match, the matcher.
  5529. void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
  5530. StreamMatchResultListener listener(os);
  5531. MatchAndExplain(x, &listener);
  5532. }
  5533. // Returns the describer for this matcher object; retains ownership
  5534. // of the describer, which is only guaranteed to be alive when
  5535. // this matcher object is alive.
  5536. const MatcherDescriberInterface* GetDescriber() const {
  5537. if (vtable_ == nullptr) return nullptr;
  5538. return vtable_->get_describer(*this);
  5539. }
  5540. protected:
  5541. MatcherBase() : vtable_(nullptr) {}
  5542. // Constructs a matcher from its implementation.
  5543. template <typename U>
  5544. explicit MatcherBase(const MatcherInterface<U>* impl) {
  5545. Init(impl);
  5546. }
  5547. template <typename M, typename = typename std::remove_reference<
  5548. M>::type::is_gtest_matcher>
  5549. MatcherBase(M&& m) { // NOLINT
  5550. Init(std::forward<M>(m));
  5551. }
  5552. MatcherBase(const MatcherBase& other)
  5553. : vtable_(other.vtable_), buffer_(other.buffer_) {
  5554. if (IsShared()) buffer_.shared->Ref();
  5555. }
  5556. MatcherBase& operator=(const MatcherBase& other) {
  5557. if (this == &other) return *this;
  5558. Destroy();
  5559. vtable_ = other.vtable_;
  5560. buffer_ = other.buffer_;
  5561. if (IsShared()) buffer_.shared->Ref();
  5562. return *this;
  5563. }
  5564. MatcherBase(MatcherBase&& other)
  5565. : vtable_(other.vtable_), buffer_(other.buffer_) {
  5566. other.vtable_ = nullptr;
  5567. }
  5568. MatcherBase& operator=(MatcherBase&& other) {
  5569. if (this == &other) return *this;
  5570. Destroy();
  5571. vtable_ = other.vtable_;
  5572. buffer_ = other.buffer_;
  5573. other.vtable_ = nullptr;
  5574. return *this;
  5575. }
  5576. ~MatcherBase() override { Destroy(); }
  5577. private:
  5578. struct VTable {
  5579. bool (*match_and_explain)(const MatcherBase&, const T&,
  5580. MatchResultListener*);
  5581. void (*describe)(const MatcherBase&, std::ostream*, bool negation);
  5582. // Returns the captured object if it implements the interface, otherwise
  5583. // returns the MatcherBase itself.
  5584. const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
  5585. // Called on shared instances when the reference count reaches 0.
  5586. void (*shared_destroy)(SharedPayloadBase*);
  5587. };
  5588. bool IsShared() const {
  5589. return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
  5590. }
  5591. // If the implementation uses a listener, call that.
  5592. template <typename P>
  5593. static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
  5594. MatchResultListener* listener)
  5595. -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
  5596. return P::Get(m).MatchAndExplain(value, listener->stream());
  5597. }
  5598. template <typename P>
  5599. static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
  5600. MatchResultListener* listener)
  5601. -> decltype(P::Get(m).MatchAndExplain(value, listener)) {
  5602. return P::Get(m).MatchAndExplain(value, listener);
  5603. }
  5604. template <typename P>
  5605. static void DescribeImpl(const MatcherBase& m, std::ostream* os,
  5606. bool negation) {
  5607. if (negation) {
  5608. P::Get(m).DescribeNegationTo(os);
  5609. } else {
  5610. P::Get(m).DescribeTo(os);
  5611. }
  5612. }
  5613. template <typename P>
  5614. static const MatcherDescriberInterface* GetDescriberImpl(
  5615. const MatcherBase& m) {
  5616. // If the impl is a MatcherDescriberInterface, then return it.
  5617. // Otherwise use MatcherBase itself.
  5618. // This allows us to implement the GetDescriber() function without support
  5619. // from the impl, but some users really want to get their impl back when
  5620. // they call GetDescriber().
  5621. // We use std::get on a tuple as a workaround of not having `if constexpr`.
  5622. return std::get<(
  5623. std::is_convertible<decltype(&P::Get(m)),
  5624. const MatcherDescriberInterface*>::value
  5625. ? 1
  5626. : 0)>(std::make_tuple(&m, &P::Get(m)));
  5627. }
  5628. template <typename P>
  5629. const VTable* GetVTable() {
  5630. static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
  5631. &DescribeImpl<P>, &GetDescriberImpl<P>,
  5632. P::shared_destroy};
  5633. return &kVTable;
  5634. }
  5635. union Buffer {
  5636. // Add some types to give Buffer some common alignment/size use cases.
  5637. void* ptr;
  5638. double d;
  5639. int64_t i;
  5640. // And add one for the out-of-line cases.
  5641. SharedPayloadBase* shared;
  5642. };
  5643. void Destroy() {
  5644. if (IsShared() && buffer_.shared->Unref()) {
  5645. vtable_->shared_destroy(buffer_.shared);
  5646. }
  5647. }
  5648. template <typename M>
  5649. static constexpr bool IsInlined() {
  5650. return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
  5651. std::is_trivially_copy_constructible<M>::value &&
  5652. std::is_trivially_destructible<M>::value;
  5653. }
  5654. template <typename M, bool = MatcherBase::IsInlined<M>()>
  5655. struct ValuePolicy {
  5656. static const M& Get(const MatcherBase& m) {
  5657. // When inlined along with Init, need to be explicit to avoid violating
  5658. // strict aliasing rules.
  5659. const M *ptr = static_cast<const M*>(
  5660. static_cast<const void*>(&m.buffer_));
  5661. return *ptr;
  5662. }
  5663. static void Init(MatcherBase& m, M impl) {
  5664. ::new (static_cast<void*>(&m.buffer_)) M(impl);
  5665. }
  5666. static constexpr auto shared_destroy = nullptr;
  5667. };
  5668. template <typename M>
  5669. struct ValuePolicy<M, false> {
  5670. using Shared = SharedPayload<M>;
  5671. static const M& Get(const MatcherBase& m) {
  5672. return static_cast<Shared*>(m.buffer_.shared)->value;
  5673. }
  5674. template <typename Arg>
  5675. static void Init(MatcherBase& m, Arg&& arg) {
  5676. m.buffer_.shared = new Shared(std::forward<Arg>(arg));
  5677. }
  5678. static constexpr auto shared_destroy = &Shared::Destroy;
  5679. };
  5680. template <typename U, bool B>
  5681. struct ValuePolicy<const MatcherInterface<U>*, B> {
  5682. using M = const MatcherInterface<U>;
  5683. using Shared = SharedPayload<std::unique_ptr<M>>;
  5684. static const M& Get(const MatcherBase& m) {
  5685. return *static_cast<Shared*>(m.buffer_.shared)->value;
  5686. }
  5687. static void Init(MatcherBase& m, M* impl) {
  5688. m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
  5689. }
  5690. static constexpr auto shared_destroy = &Shared::Destroy;
  5691. };
  5692. template <typename M>
  5693. void Init(M&& m) {
  5694. using MM = typename std::decay<M>::type;
  5695. using Policy = ValuePolicy<MM>;
  5696. vtable_ = GetVTable<Policy>();
  5697. Policy::Init(*this, std::forward<M>(m));
  5698. }
  5699. const VTable* vtable_;
  5700. Buffer buffer_;
  5701. };
  5702. } // namespace internal
  5703. // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
  5704. // object that can check whether a value of type T matches. The
  5705. // implementation of Matcher<T> is just a std::shared_ptr to const
  5706. // MatcherInterface<T>. Don't inherit from Matcher!
  5707. template <typename T>
  5708. class Matcher : public internal::MatcherBase<T> {
  5709. public:
  5710. // Constructs a null matcher. Needed for storing Matcher objects in STL
  5711. // containers. A default-constructed matcher is not yet initialized. You
  5712. // cannot use it until a valid value has been assigned to it.
  5713. explicit Matcher() {} // NOLINT
  5714. // Constructs a matcher from its implementation.
  5715. explicit Matcher(const MatcherInterface<const T&>* impl)
  5716. : internal::MatcherBase<T>(impl) {}
  5717. template <typename U>
  5718. explicit Matcher(
  5719. const MatcherInterface<U>* impl,
  5720. typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
  5721. nullptr)
  5722. : internal::MatcherBase<T>(impl) {}
  5723. template <typename M, typename = typename std::remove_reference<
  5724. M>::type::is_gtest_matcher>
  5725. Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {} // NOLINT
  5726. // Implicit constructor here allows people to write
  5727. // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
  5728. Matcher(T value); // NOLINT
  5729. };
  5730. // The following two specializations allow the user to write str
  5731. // instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
  5732. // matcher is expected.
  5733. template <>
  5734. class GTEST_API_ Matcher<const std::string&>
  5735. : public internal::MatcherBase<const std::string&> {
  5736. public:
  5737. Matcher() {}
  5738. explicit Matcher(const MatcherInterface<const std::string&>* impl)
  5739. : internal::MatcherBase<const std::string&>(impl) {}
  5740. template <typename M, typename = typename std::remove_reference<
  5741. M>::type::is_gtest_matcher>
  5742. Matcher(M&& m) // NOLINT
  5743. : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
  5744. // Allows the user to write str instead of Eq(str) sometimes, where
  5745. // str is a std::string object.
  5746. Matcher(const std::string& s); // NOLINT
  5747. // Allows the user to write "foo" instead of Eq("foo") sometimes.
  5748. Matcher(const char* s); // NOLINT
  5749. };
  5750. template <>
  5751. class GTEST_API_ Matcher<std::string>
  5752. : public internal::MatcherBase<std::string> {
  5753. public:
  5754. Matcher() {}
  5755. explicit Matcher(const MatcherInterface<const std::string&>* impl)
  5756. : internal::MatcherBase<std::string>(impl) {}
  5757. explicit Matcher(const MatcherInterface<std::string>* impl)
  5758. : internal::MatcherBase<std::string>(impl) {}
  5759. template <typename M, typename = typename std::remove_reference<
  5760. M>::type::is_gtest_matcher>
  5761. Matcher(M&& m) // NOLINT
  5762. : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
  5763. // Allows the user to write str instead of Eq(str) sometimes, where
  5764. // str is a string object.
  5765. Matcher(const std::string& s); // NOLINT
  5766. // Allows the user to write "foo" instead of Eq("foo") sometimes.
  5767. Matcher(const char* s); // NOLINT
  5768. };
  5769. #if GTEST_INTERNAL_HAS_STRING_VIEW
  5770. // The following two specializations allow the user to write str
  5771. // instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
  5772. // matcher is expected.
  5773. template <>
  5774. class GTEST_API_ Matcher<const internal::StringView&>
  5775. : public internal::MatcherBase<const internal::StringView&> {
  5776. public:
  5777. Matcher() {}
  5778. explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
  5779. : internal::MatcherBase<const internal::StringView&>(impl) {}
  5780. template <typename M, typename = typename std::remove_reference<
  5781. M>::type::is_gtest_matcher>
  5782. Matcher(M&& m) // NOLINT
  5783. : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
  5784. }
  5785. // Allows the user to write str instead of Eq(str) sometimes, where
  5786. // str is a std::string object.
  5787. Matcher(const std::string& s); // NOLINT
  5788. // Allows the user to write "foo" instead of Eq("foo") sometimes.
  5789. Matcher(const char* s); // NOLINT
  5790. // Allows the user to pass absl::string_views or std::string_views directly.
  5791. Matcher(internal::StringView s); // NOLINT
  5792. };
  5793. template <>
  5794. class GTEST_API_ Matcher<internal::StringView>
  5795. : public internal::MatcherBase<internal::StringView> {
  5796. public:
  5797. Matcher() {}
  5798. explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
  5799. : internal::MatcherBase<internal::StringView>(impl) {}
  5800. explicit Matcher(const MatcherInterface<internal::StringView>* impl)
  5801. : internal::MatcherBase<internal::StringView>(impl) {}
  5802. template <typename M, typename = typename std::remove_reference<
  5803. M>::type::is_gtest_matcher>
  5804. Matcher(M&& m) // NOLINT
  5805. : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
  5806. // Allows the user to write str instead of Eq(str) sometimes, where
  5807. // str is a std::string object.
  5808. Matcher(const std::string& s); // NOLINT
  5809. // Allows the user to write "foo" instead of Eq("foo") sometimes.
  5810. Matcher(const char* s); // NOLINT
  5811. // Allows the user to pass absl::string_views or std::string_views directly.
  5812. Matcher(internal::StringView s); // NOLINT
  5813. };
  5814. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  5815. // Prints a matcher in a human-readable format.
  5816. template <typename T>
  5817. std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
  5818. matcher.DescribeTo(&os);
  5819. return os;
  5820. }
  5821. // The PolymorphicMatcher class template makes it easy to implement a
  5822. // polymorphic matcher (i.e. a matcher that can match values of more
  5823. // than one type, e.g. Eq(n) and NotNull()).
  5824. //
  5825. // To define a polymorphic matcher, a user should provide an Impl
  5826. // class that has a DescribeTo() method and a DescribeNegationTo()
  5827. // method, and define a member function (or member function template)
  5828. //
  5829. // bool MatchAndExplain(const Value& value,
  5830. // MatchResultListener* listener) const;
  5831. //
  5832. // See the definition of NotNull() for a complete example.
  5833. template <class Impl>
  5834. class PolymorphicMatcher {
  5835. public:
  5836. explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
  5837. // Returns a mutable reference to the underlying matcher
  5838. // implementation object.
  5839. Impl& mutable_impl() { return impl_; }
  5840. // Returns an immutable reference to the underlying matcher
  5841. // implementation object.
  5842. const Impl& impl() const { return impl_; }
  5843. template <typename T>
  5844. operator Matcher<T>() const {
  5845. return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
  5846. }
  5847. private:
  5848. template <typename T>
  5849. class MonomorphicImpl : public MatcherInterface<T> {
  5850. public:
  5851. explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
  5852. void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
  5853. void DescribeNegationTo(::std::ostream* os) const override {
  5854. impl_.DescribeNegationTo(os);
  5855. }
  5856. bool MatchAndExplain(T x, MatchResultListener* listener) const override {
  5857. return impl_.MatchAndExplain(x, listener);
  5858. }
  5859. private:
  5860. const Impl impl_;
  5861. };
  5862. Impl impl_;
  5863. };
  5864. // Creates a matcher from its implementation.
  5865. // DEPRECATED: Especially in the generic code, prefer:
  5866. // Matcher<T>(new MyMatcherImpl<const T&>(...));
  5867. //
  5868. // MakeMatcher may create a Matcher that accepts its argument by value, which
  5869. // leads to unnecessary copies & lack of support for non-copyable types.
  5870. template <typename T>
  5871. inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
  5872. return Matcher<T>(impl);
  5873. }
  5874. // Creates a polymorphic matcher from its implementation. This is
  5875. // easier to use than the PolymorphicMatcher<Impl> constructor as it
  5876. // doesn't require you to explicitly write the template argument, e.g.
  5877. //
  5878. // MakePolymorphicMatcher(foo);
  5879. // vs
  5880. // PolymorphicMatcher<TypeOfFoo>(foo);
  5881. template <class Impl>
  5882. inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
  5883. return PolymorphicMatcher<Impl>(impl);
  5884. }
  5885. namespace internal {
  5886. // Implements a matcher that compares a given value with a
  5887. // pre-supplied value using one of the ==, <=, <, etc, operators. The
  5888. // two values being compared don't have to have the same type.
  5889. //
  5890. // The matcher defined here is polymorphic (for example, Eq(5) can be
  5891. // used to match an int, a short, a double, etc). Therefore we use
  5892. // a template type conversion operator in the implementation.
  5893. //
  5894. // The following template definition assumes that the Rhs parameter is
  5895. // a "bare" type (i.e. neither 'const T' nor 'T&').
  5896. template <typename D, typename Rhs, typename Op>
  5897. class ComparisonBase {
  5898. public:
  5899. explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
  5900. using is_gtest_matcher = void;
  5901. template <typename Lhs>
  5902. bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
  5903. return Op()(lhs, Unwrap(rhs_));
  5904. }
  5905. void DescribeTo(std::ostream* os) const {
  5906. *os << D::Desc() << " ";
  5907. UniversalPrint(Unwrap(rhs_), os);
  5908. }
  5909. void DescribeNegationTo(std::ostream* os) const {
  5910. *os << D::NegatedDesc() << " ";
  5911. UniversalPrint(Unwrap(rhs_), os);
  5912. }
  5913. private:
  5914. template <typename T>
  5915. static const T& Unwrap(const T& v) {
  5916. return v;
  5917. }
  5918. template <typename T>
  5919. static const T& Unwrap(std::reference_wrapper<T> v) {
  5920. return v;
  5921. }
  5922. Rhs rhs_;
  5923. };
  5924. template <typename Rhs>
  5925. class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
  5926. public:
  5927. explicit EqMatcher(const Rhs& rhs)
  5928. : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
  5929. static const char* Desc() { return "is equal to"; }
  5930. static const char* NegatedDesc() { return "isn't equal to"; }
  5931. };
  5932. template <typename Rhs>
  5933. class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
  5934. public:
  5935. explicit NeMatcher(const Rhs& rhs)
  5936. : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
  5937. static const char* Desc() { return "isn't equal to"; }
  5938. static const char* NegatedDesc() { return "is equal to"; }
  5939. };
  5940. template <typename Rhs>
  5941. class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
  5942. public:
  5943. explicit LtMatcher(const Rhs& rhs)
  5944. : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
  5945. static const char* Desc() { return "is <"; }
  5946. static const char* NegatedDesc() { return "isn't <"; }
  5947. };
  5948. template <typename Rhs>
  5949. class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
  5950. public:
  5951. explicit GtMatcher(const Rhs& rhs)
  5952. : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
  5953. static const char* Desc() { return "is >"; }
  5954. static const char* NegatedDesc() { return "isn't >"; }
  5955. };
  5956. template <typename Rhs>
  5957. class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
  5958. public:
  5959. explicit LeMatcher(const Rhs& rhs)
  5960. : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
  5961. static const char* Desc() { return "is <="; }
  5962. static const char* NegatedDesc() { return "isn't <="; }
  5963. };
  5964. template <typename Rhs>
  5965. class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
  5966. public:
  5967. explicit GeMatcher(const Rhs& rhs)
  5968. : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
  5969. static const char* Desc() { return "is >="; }
  5970. static const char* NegatedDesc() { return "isn't >="; }
  5971. };
  5972. template <typename T, typename = typename std::enable_if<
  5973. std::is_constructible<std::string, T>::value>::type>
  5974. using StringLike = T;
  5975. // Implements polymorphic matchers MatchesRegex(regex) and
  5976. // ContainsRegex(regex), which can be used as a Matcher<T> as long as
  5977. // T can be converted to a string.
  5978. class MatchesRegexMatcher {
  5979. public:
  5980. MatchesRegexMatcher(const RE* regex, bool full_match)
  5981. : regex_(regex), full_match_(full_match) {}
  5982. #if GTEST_INTERNAL_HAS_STRING_VIEW
  5983. bool MatchAndExplain(const internal::StringView& s,
  5984. MatchResultListener* listener) const {
  5985. return MatchAndExplain(std::string(s), listener);
  5986. }
  5987. #endif // GTEST_INTERNAL_HAS_STRING_VIEW
  5988. // Accepts pointer types, particularly:
  5989. // const char*
  5990. // char*
  5991. // const wchar_t*
  5992. // wchar_t*
  5993. template <typename CharType>
  5994. bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
  5995. return s != nullptr && MatchAndExplain(std::string(s), listener);
  5996. }
  5997. // Matches anything that can convert to std::string.
  5998. //
  5999. // This is a template, not just a plain function with const std::string&,
  6000. // because absl::string_view has some interfering non-explicit constructors.
  6001. template <class MatcheeStringType>
  6002. bool MatchAndExplain(const MatcheeStringType& s,
  6003. MatchResultListener* /* listener */) const {
  6004. const std::string& s2(s);
  6005. return full_match_ ? RE::FullMatch(s2, *regex_)
  6006. : RE::PartialMatch(s2, *regex_);
  6007. }
  6008. void DescribeTo(::std::ostream* os) const {
  6009. *os << (full_match_ ? "matches" : "contains") << " regular expression ";
  6010. UniversalPrinter<std::string>::Print(regex_->pattern(), os);
  6011. }
  6012. void DescribeNegationTo(::std::ostream* os) const {
  6013. *os << "doesn't " << (full_match_ ? "match" : "contain")
  6014. << " regular expression ";
  6015. UniversalPrinter<std::string>::Print(regex_->pattern(), os);
  6016. }
  6017. private:
  6018. const std::shared_ptr<const RE> regex_;
  6019. const bool full_match_;
  6020. };
  6021. } // namespace internal
  6022. // Matches a string that fully matches regular expression 'regex'.
  6023. // The matcher takes ownership of 'regex'.
  6024. inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
  6025. const internal::RE* regex) {
  6026. return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
  6027. }
  6028. template <typename T = std::string>
  6029. PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
  6030. const internal::StringLike<T>& regex) {
  6031. return MatchesRegex(new internal::RE(std::string(regex)));
  6032. }
  6033. // Matches a string that contains regular expression 'regex'.
  6034. // The matcher takes ownership of 'regex'.
  6035. inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
  6036. const internal::RE* regex) {
  6037. return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
  6038. }
  6039. template <typename T = std::string>
  6040. PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
  6041. const internal::StringLike<T>& regex) {
  6042. return ContainsRegex(new internal::RE(std::string(regex)));
  6043. }
  6044. // Creates a polymorphic matcher that matches anything equal to x.
  6045. // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
  6046. // wouldn't compile.
  6047. template <typename T>
  6048. inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
  6049. // Constructs a Matcher<T> from a 'value' of type T. The constructed
  6050. // matcher matches any value that's equal to 'value'.
  6051. template <typename T>
  6052. Matcher<T>::Matcher(T value) { *this = Eq(value); }
  6053. // Creates a monomorphic matcher that matches anything with type Lhs
  6054. // and equal to rhs. A user may need to use this instead of Eq(...)
  6055. // in order to resolve an overloading ambiguity.
  6056. //
  6057. // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
  6058. // or Matcher<T>(x), but more readable than the latter.
  6059. //
  6060. // We could define similar monomorphic matchers for other comparison
  6061. // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
  6062. // it yet as those are used much less than Eq() in practice. A user
  6063. // can always write Matcher<T>(Lt(5)) to be explicit about the type,
  6064. // for example.
  6065. template <typename Lhs, typename Rhs>
  6066. inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
  6067. // Creates a polymorphic matcher that matches anything >= x.
  6068. template <typename Rhs>
  6069. inline internal::GeMatcher<Rhs> Ge(Rhs x) {
  6070. return internal::GeMatcher<Rhs>(x);
  6071. }
  6072. // Creates a polymorphic matcher that matches anything > x.
  6073. template <typename Rhs>
  6074. inline internal::GtMatcher<Rhs> Gt(Rhs x) {
  6075. return internal::GtMatcher<Rhs>(x);
  6076. }
  6077. // Creates a polymorphic matcher that matches anything <= x.
  6078. template <typename Rhs>
  6079. inline internal::LeMatcher<Rhs> Le(Rhs x) {
  6080. return internal::LeMatcher<Rhs>(x);
  6081. }
  6082. // Creates a polymorphic matcher that matches anything < x.
  6083. template <typename Rhs>
  6084. inline internal::LtMatcher<Rhs> Lt(Rhs x) {
  6085. return internal::LtMatcher<Rhs>(x);
  6086. }
  6087. // Creates a polymorphic matcher that matches anything != x.
  6088. template <typename Rhs>
  6089. inline internal::NeMatcher<Rhs> Ne(Rhs x) {
  6090. return internal::NeMatcher<Rhs>(x);
  6091. }
  6092. } // namespace testing
  6093. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
  6094. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
  6095. #include <stdio.h>
  6096. #include <memory>
  6097. namespace testing {
  6098. namespace internal {
  6099. GTEST_DECLARE_string_(internal_run_death_test);
  6100. // Names of the flags (needed for parsing Google Test flags).
  6101. const char kDeathTestStyleFlag[] = "death_test_style";
  6102. const char kDeathTestUseFork[] = "death_test_use_fork";
  6103. const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
  6104. #if GTEST_HAS_DEATH_TEST
  6105. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  6106. /* class A needs to have dll-interface to be used by clients of class B */)
  6107. // DeathTest is a class that hides much of the complexity of the
  6108. // GTEST_DEATH_TEST_ macro. It is abstract; its static Create method
  6109. // returns a concrete class that depends on the prevailing death test
  6110. // style, as defined by the --gtest_death_test_style and/or
  6111. // --gtest_internal_run_death_test flags.
  6112. // In describing the results of death tests, these terms are used with
  6113. // the corresponding definitions:
  6114. //
  6115. // exit status: The integer exit information in the format specified
  6116. // by wait(2)
  6117. // exit code: The integer code passed to exit(3), _exit(2), or
  6118. // returned from main()
  6119. class GTEST_API_ DeathTest {
  6120. public:
  6121. // Create returns false if there was an error determining the
  6122. // appropriate action to take for the current death test; for example,
  6123. // if the gtest_death_test_style flag is set to an invalid value.
  6124. // The LastMessage method will return a more detailed message in that
  6125. // case. Otherwise, the DeathTest pointer pointed to by the "test"
  6126. // argument is set. If the death test should be skipped, the pointer
  6127. // is set to NULL; otherwise, it is set to the address of a new concrete
  6128. // DeathTest object that controls the execution of the current test.
  6129. static bool Create(const char* statement, Matcher<const std::string&> matcher,
  6130. const char* file, int line, DeathTest** test);
  6131. DeathTest();
  6132. virtual ~DeathTest() { }
  6133. // A helper class that aborts a death test when it's deleted.
  6134. class ReturnSentinel {
  6135. public:
  6136. explicit ReturnSentinel(DeathTest* test) : test_(test) { }
  6137. ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
  6138. private:
  6139. DeathTest* const test_;
  6140. GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
  6141. } GTEST_ATTRIBUTE_UNUSED_;
  6142. // An enumeration of possible roles that may be taken when a death
  6143. // test is encountered. EXECUTE means that the death test logic should
  6144. // be executed immediately. OVERSEE means that the program should prepare
  6145. // the appropriate environment for a child process to execute the death
  6146. // test, then wait for it to complete.
  6147. enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
  6148. // An enumeration of the three reasons that a test might be aborted.
  6149. enum AbortReason {
  6150. TEST_ENCOUNTERED_RETURN_STATEMENT,
  6151. TEST_THREW_EXCEPTION,
  6152. TEST_DID_NOT_DIE
  6153. };
  6154. // Assumes one of the above roles.
  6155. virtual TestRole AssumeRole() = 0;
  6156. // Waits for the death test to finish and returns its status.
  6157. virtual int Wait() = 0;
  6158. // Returns true if the death test passed; that is, the test process
  6159. // exited during the test, its exit status matches a user-supplied
  6160. // predicate, and its stderr output matches a user-supplied regular
  6161. // expression.
  6162. // The user-supplied predicate may be a macro expression rather
  6163. // than a function pointer or functor, or else Wait and Passed could
  6164. // be combined.
  6165. virtual bool Passed(bool exit_status_ok) = 0;
  6166. // Signals that the death test did not die as expected.
  6167. virtual void Abort(AbortReason reason) = 0;
  6168. // Returns a human-readable outcome message regarding the outcome of
  6169. // the last death test.
  6170. static const char* LastMessage();
  6171. static void set_last_death_test_message(const std::string& message);
  6172. private:
  6173. // A string containing a description of the outcome of the last death test.
  6174. static std::string last_death_test_message_;
  6175. GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
  6176. };
  6177. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  6178. // Factory interface for death tests. May be mocked out for testing.
  6179. class DeathTestFactory {
  6180. public:
  6181. virtual ~DeathTestFactory() { }
  6182. virtual bool Create(const char* statement,
  6183. Matcher<const std::string&> matcher, const char* file,
  6184. int line, DeathTest** test) = 0;
  6185. };
  6186. // A concrete DeathTestFactory implementation for normal use.
  6187. class DefaultDeathTestFactory : public DeathTestFactory {
  6188. public:
  6189. bool Create(const char* statement, Matcher<const std::string&> matcher,
  6190. const char* file, int line, DeathTest** test) override;
  6191. };
  6192. // Returns true if exit_status describes a process that was terminated
  6193. // by a signal, or exited normally with a nonzero exit code.
  6194. GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
  6195. // A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
  6196. // and interpreted as a regex (rather than an Eq matcher) for legacy
  6197. // compatibility.
  6198. inline Matcher<const ::std::string&> MakeDeathTestMatcher(
  6199. ::testing::internal::RE regex) {
  6200. return ContainsRegex(regex.pattern());
  6201. }
  6202. inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
  6203. return ContainsRegex(regex);
  6204. }
  6205. inline Matcher<const ::std::string&> MakeDeathTestMatcher(
  6206. const ::std::string& regex) {
  6207. return ContainsRegex(regex);
  6208. }
  6209. // If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
  6210. // used directly.
  6211. inline Matcher<const ::std::string&> MakeDeathTestMatcher(
  6212. Matcher<const ::std::string&> matcher) {
  6213. return matcher;
  6214. }
  6215. // Traps C++ exceptions escaping statement and reports them as test
  6216. // failures. Note that trapping SEH exceptions is not implemented here.
  6217. # if GTEST_HAS_EXCEPTIONS
  6218. # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
  6219. try { \
  6220. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  6221. } catch (const ::std::exception& gtest_exception) { \
  6222. fprintf(\
  6223. stderr, \
  6224. "\n%s: Caught std::exception-derived exception escaping the " \
  6225. "death test statement. Exception message: %s\n", \
  6226. ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
  6227. gtest_exception.what()); \
  6228. fflush(stderr); \
  6229. death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
  6230. } catch (...) { \
  6231. death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
  6232. }
  6233. # else
  6234. # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
  6235. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
  6236. # endif
  6237. // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
  6238. // ASSERT_EXIT*, and EXPECT_EXIT*.
  6239. #define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail) \
  6240. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  6241. if (::testing::internal::AlwaysTrue()) { \
  6242. ::testing::internal::DeathTest* gtest_dt; \
  6243. if (!::testing::internal::DeathTest::Create( \
  6244. #statement, \
  6245. ::testing::internal::MakeDeathTestMatcher(regex_or_matcher), \
  6246. __FILE__, __LINE__, &gtest_dt)) { \
  6247. goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
  6248. } \
  6249. if (gtest_dt != nullptr) { \
  6250. std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \
  6251. switch (gtest_dt->AssumeRole()) { \
  6252. case ::testing::internal::DeathTest::OVERSEE_TEST: \
  6253. if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
  6254. goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
  6255. } \
  6256. break; \
  6257. case ::testing::internal::DeathTest::EXECUTE_TEST: { \
  6258. ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
  6259. gtest_dt); \
  6260. GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
  6261. gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
  6262. break; \
  6263. } \
  6264. default: \
  6265. break; \
  6266. } \
  6267. } \
  6268. } else \
  6269. GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \
  6270. : fail(::testing::internal::DeathTest::LastMessage())
  6271. // The symbol "fail" here expands to something into which a message
  6272. // can be streamed.
  6273. // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
  6274. // NDEBUG mode. In this case we need the statements to be executed and the macro
  6275. // must accept a streamed message even though the message is never printed.
  6276. // The regex object is not evaluated, but it is used to prevent "unused"
  6277. // warnings and to avoid an expression that doesn't compile in debug mode.
  6278. #define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
  6279. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  6280. if (::testing::internal::AlwaysTrue()) { \
  6281. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  6282. } else if (!::testing::internal::AlwaysTrue()) { \
  6283. ::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
  6284. } else \
  6285. ::testing::Message()
  6286. // A class representing the parsed contents of the
  6287. // --gtest_internal_run_death_test flag, as it existed when
  6288. // RUN_ALL_TESTS was called.
  6289. class InternalRunDeathTestFlag {
  6290. public:
  6291. InternalRunDeathTestFlag(const std::string& a_file,
  6292. int a_line,
  6293. int an_index,
  6294. int a_write_fd)
  6295. : file_(a_file), line_(a_line), index_(an_index),
  6296. write_fd_(a_write_fd) {}
  6297. ~InternalRunDeathTestFlag() {
  6298. if (write_fd_ >= 0)
  6299. posix::Close(write_fd_);
  6300. }
  6301. const std::string& file() const { return file_; }
  6302. int line() const { return line_; }
  6303. int index() const { return index_; }
  6304. int write_fd() const { return write_fd_; }
  6305. private:
  6306. std::string file_;
  6307. int line_;
  6308. int index_;
  6309. int write_fd_;
  6310. GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
  6311. };
  6312. // Returns a newly created InternalRunDeathTestFlag object with fields
  6313. // initialized from the GTEST_FLAG(internal_run_death_test) flag if
  6314. // the flag is specified; otherwise returns NULL.
  6315. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
  6316. #endif // GTEST_HAS_DEATH_TEST
  6317. } // namespace internal
  6318. } // namespace testing
  6319. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
  6320. namespace testing {
  6321. // This flag controls the style of death tests. Valid values are "threadsafe",
  6322. // meaning that the death test child process will re-execute the test binary
  6323. // from the start, running only a single death test, or "fast",
  6324. // meaning that the child process will execute the test logic immediately
  6325. // after forking.
  6326. GTEST_DECLARE_string_(death_test_style);
  6327. #if GTEST_HAS_DEATH_TEST
  6328. namespace internal {
  6329. // Returns a Boolean value indicating whether the caller is currently
  6330. // executing in the context of the death test child process. Tools such as
  6331. // Valgrind heap checkers may need this to modify their behavior in death
  6332. // tests. IMPORTANT: This is an internal utility. Using it may break the
  6333. // implementation of death tests. User code MUST NOT use it.
  6334. GTEST_API_ bool InDeathTestChild();
  6335. } // namespace internal
  6336. // The following macros are useful for writing death tests.
  6337. // Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
  6338. // executed:
  6339. //
  6340. // 1. It generates a warning if there is more than one active
  6341. // thread. This is because it's safe to fork() or clone() only
  6342. // when there is a single thread.
  6343. //
  6344. // 2. The parent process clone()s a sub-process and runs the death
  6345. // test in it; the sub-process exits with code 0 at the end of the
  6346. // death test, if it hasn't exited already.
  6347. //
  6348. // 3. The parent process waits for the sub-process to terminate.
  6349. //
  6350. // 4. The parent process checks the exit code and error message of
  6351. // the sub-process.
  6352. //
  6353. // Examples:
  6354. //
  6355. // ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");
  6356. // for (int i = 0; i < 5; i++) {
  6357. // EXPECT_DEATH(server.ProcessRequest(i),
  6358. // "Invalid request .* in ProcessRequest()")
  6359. // << "Failed to die on request " << i;
  6360. // }
  6361. //
  6362. // ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
  6363. //
  6364. // bool KilledBySIGHUP(int exit_code) {
  6365. // return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;
  6366. // }
  6367. //
  6368. // ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
  6369. //
  6370. // The final parameter to each of these macros is a matcher applied to any data
  6371. // the sub-process wrote to stderr. For compatibility with existing tests, a
  6372. // bare string is interpreted as a regular expression matcher.
  6373. //
  6374. // On the regular expressions used in death tests:
  6375. //
  6376. // GOOGLETEST_CM0005 DO NOT DELETE
  6377. // On POSIX-compliant systems (*nix), we use the <regex.h> library,
  6378. // which uses the POSIX extended regex syntax.
  6379. //
  6380. // On other platforms (e.g. Windows or Mac), we only support a simple regex
  6381. // syntax implemented as part of Google Test. This limited
  6382. // implementation should be enough most of the time when writing
  6383. // death tests; though it lacks many features you can find in PCRE
  6384. // or POSIX extended regex syntax. For example, we don't support
  6385. // union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and
  6386. // repetition count ("x{5,7}"), among others.
  6387. //
  6388. // Below is the syntax that we do support. We chose it to be a
  6389. // subset of both PCRE and POSIX extended regex, so it's easy to
  6390. // learn wherever you come from. In the following: 'A' denotes a
  6391. // literal character, period (.), or a single \\ escape sequence;
  6392. // 'x' and 'y' denote regular expressions; 'm' and 'n' are for
  6393. // natural numbers.
  6394. //
  6395. // c matches any literal character c
  6396. // \\d matches any decimal digit
  6397. // \\D matches any character that's not a decimal digit
  6398. // \\f matches \f
  6399. // \\n matches \n
  6400. // \\r matches \r
  6401. // \\s matches any ASCII whitespace, including \n
  6402. // \\S matches any character that's not a whitespace
  6403. // \\t matches \t
  6404. // \\v matches \v
  6405. // \\w matches any letter, _, or decimal digit
  6406. // \\W matches any character that \\w doesn't match
  6407. // \\c matches any literal character c, which must be a punctuation
  6408. // . matches any single character except \n
  6409. // A? matches 0 or 1 occurrences of A
  6410. // A* matches 0 or many occurrences of A
  6411. // A+ matches 1 or many occurrences of A
  6412. // ^ matches the beginning of a string (not that of each line)
  6413. // $ matches the end of a string (not that of each line)
  6414. // xy matches x followed by y
  6415. //
  6416. // If you accidentally use PCRE or POSIX extended regex features
  6417. // not implemented by us, you will get a run-time failure. In that
  6418. // case, please try to rewrite your regular expression within the
  6419. // above syntax.
  6420. //
  6421. // This implementation is *not* meant to be as highly tuned or robust
  6422. // as a compiled regex library, but should perform well enough for a
  6423. // death test, which already incurs significant overhead by launching
  6424. // a child process.
  6425. //
  6426. // Known caveats:
  6427. //
  6428. // A "threadsafe" style death test obtains the path to the test
  6429. // program from argv[0] and re-executes it in the sub-process. For
  6430. // simplicity, the current implementation doesn't search the PATH
  6431. // when launching the sub-process. This means that the user must
  6432. // invoke the test program via a path that contains at least one
  6433. // path separator (e.g. path/to/foo_test and
  6434. // /absolute/path/to/bar_test are fine, but foo_test is not). This
  6435. // is rarely a problem as people usually don't put the test binary
  6436. // directory in PATH.
  6437. //
  6438. // Asserts that a given `statement` causes the program to exit, with an
  6439. // integer exit status that satisfies `predicate`, and emitting error output
  6440. // that matches `matcher`.
  6441. # define ASSERT_EXIT(statement, predicate, matcher) \
  6442. GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_)
  6443. // Like `ASSERT_EXIT`, but continues on to successive tests in the
  6444. // test suite, if any:
  6445. # define EXPECT_EXIT(statement, predicate, matcher) \
  6446. GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_)
  6447. // Asserts that a given `statement` causes the program to exit, either by
  6448. // explicitly exiting with a nonzero exit code or being killed by a
  6449. // signal, and emitting error output that matches `matcher`.
  6450. # define ASSERT_DEATH(statement, matcher) \
  6451. ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
  6452. // Like `ASSERT_DEATH`, but continues on to successive tests in the
  6453. // test suite, if any:
  6454. # define EXPECT_DEATH(statement, matcher) \
  6455. EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
  6456. // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
  6457. // Tests that an exit code describes a normal exit with a given exit code.
  6458. class GTEST_API_ ExitedWithCode {
  6459. public:
  6460. explicit ExitedWithCode(int exit_code);
  6461. ExitedWithCode(const ExitedWithCode&) = default;
  6462. void operator=(const ExitedWithCode& other) = delete;
  6463. bool operator()(int exit_status) const;
  6464. private:
  6465. const int exit_code_;
  6466. };
  6467. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6468. // Tests that an exit code describes an exit due to termination by a
  6469. // given signal.
  6470. // GOOGLETEST_CM0006 DO NOT DELETE
  6471. class GTEST_API_ KilledBySignal {
  6472. public:
  6473. explicit KilledBySignal(int signum);
  6474. bool operator()(int exit_status) const;
  6475. private:
  6476. const int signum_;
  6477. };
  6478. # endif // !GTEST_OS_WINDOWS
  6479. // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
  6480. // The death testing framework causes this to have interesting semantics,
  6481. // since the sideeffects of the call are only visible in opt mode, and not
  6482. // in debug mode.
  6483. //
  6484. // In practice, this can be used to test functions that utilize the
  6485. // LOG(DFATAL) macro using the following style:
  6486. //
  6487. // int DieInDebugOr12(int* sideeffect) {
  6488. // if (sideeffect) {
  6489. // *sideeffect = 12;
  6490. // }
  6491. // LOG(DFATAL) << "death";
  6492. // return 12;
  6493. // }
  6494. //
  6495. // TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) {
  6496. // int sideeffect = 0;
  6497. // // Only asserts in dbg.
  6498. // EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
  6499. //
  6500. // #ifdef NDEBUG
  6501. // // opt-mode has sideeffect visible.
  6502. // EXPECT_EQ(12, sideeffect);
  6503. // #else
  6504. // // dbg-mode no visible sideeffect.
  6505. // EXPECT_EQ(0, sideeffect);
  6506. // #endif
  6507. // }
  6508. //
  6509. // This will assert that DieInDebugReturn12InOpt() crashes in debug
  6510. // mode, usually due to a DCHECK or LOG(DFATAL), but returns the
  6511. // appropriate fallback value (12 in this case) in opt mode. If you
  6512. // need to test that a function has appropriate side-effects in opt
  6513. // mode, include assertions against the side-effects. A general
  6514. // pattern for this is:
  6515. //
  6516. // EXPECT_DEBUG_DEATH({
  6517. // // Side-effects here will have an effect after this statement in
  6518. // // opt mode, but none in debug mode.
  6519. // EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
  6520. // }, "death");
  6521. //
  6522. # ifdef NDEBUG
  6523. # define EXPECT_DEBUG_DEATH(statement, regex) \
  6524. GTEST_EXECUTE_STATEMENT_(statement, regex)
  6525. # define ASSERT_DEBUG_DEATH(statement, regex) \
  6526. GTEST_EXECUTE_STATEMENT_(statement, regex)
  6527. # else
  6528. # define EXPECT_DEBUG_DEATH(statement, regex) \
  6529. EXPECT_DEATH(statement, regex)
  6530. # define ASSERT_DEBUG_DEATH(statement, regex) \
  6531. ASSERT_DEATH(statement, regex)
  6532. # endif // NDEBUG for EXPECT_DEBUG_DEATH
  6533. #endif // GTEST_HAS_DEATH_TEST
  6534. // This macro is used for implementing macros such as
  6535. // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
  6536. // death tests are not supported. Those macros must compile on such systems
  6537. // if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters
  6538. // on systems that support death tests. This allows one to write such a macro on
  6539. // a system that does not support death tests and be sure that it will compile
  6540. // on a death-test supporting system. It is exposed publicly so that systems
  6541. // that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST
  6542. // can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and
  6543. // ASSERT_DEATH_IF_SUPPORTED.
  6544. //
  6545. // Parameters:
  6546. // statement - A statement that a macro such as EXPECT_DEATH would test
  6547. // for program termination. This macro has to make sure this
  6548. // statement is compiled but not executed, to ensure that
  6549. // EXPECT_DEATH_IF_SUPPORTED compiles with a certain
  6550. // parameter if and only if EXPECT_DEATH compiles with it.
  6551. // regex - A regex that a macro such as EXPECT_DEATH would use to test
  6552. // the output of statement. This parameter has to be
  6553. // compiled but not evaluated by this macro, to ensure that
  6554. // this macro only accepts expressions that a macro such as
  6555. // EXPECT_DEATH would accept.
  6556. // terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
  6557. // and a return statement for ASSERT_DEATH_IF_SUPPORTED.
  6558. // This ensures that ASSERT_DEATH_IF_SUPPORTED will not
  6559. // compile inside functions where ASSERT_DEATH doesn't
  6560. // compile.
  6561. //
  6562. // The branch that has an always false condition is used to ensure that
  6563. // statement and regex are compiled (and thus syntactically correct) but
  6564. // never executed. The unreachable code macro protects the terminator
  6565. // statement from generating an 'unreachable code' warning in case
  6566. // statement unconditionally returns or throws. The Message constructor at
  6567. // the end allows the syntax of streaming additional messages into the
  6568. // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
  6569. # define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
  6570. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  6571. if (::testing::internal::AlwaysTrue()) { \
  6572. GTEST_LOG_(WARNING) \
  6573. << "Death tests are not supported on this platform.\n" \
  6574. << "Statement '" #statement "' cannot be verified."; \
  6575. } else if (::testing::internal::AlwaysFalse()) { \
  6576. ::testing::internal::RE::PartialMatch(".*", (regex)); \
  6577. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  6578. terminator; \
  6579. } else \
  6580. ::testing::Message()
  6581. // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
  6582. // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
  6583. // death tests are supported; otherwise they just issue a warning. This is
  6584. // useful when you are combining death test assertions with normal test
  6585. // assertions in one test.
  6586. #if GTEST_HAS_DEATH_TEST
  6587. # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
  6588. EXPECT_DEATH(statement, regex)
  6589. # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
  6590. ASSERT_DEATH(statement, regex)
  6591. #else
  6592. # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
  6593. GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
  6594. # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
  6595. GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
  6596. #endif
  6597. } // namespace testing
  6598. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
  6599. // Copyright 2008, Google Inc.
  6600. // All rights reserved.
  6601. //
  6602. // Redistribution and use in source and binary forms, with or without
  6603. // modification, are permitted provided that the following conditions are
  6604. // met:
  6605. //
  6606. // * Redistributions of source code must retain the above copyright
  6607. // notice, this list of conditions and the following disclaimer.
  6608. // * Redistributions in binary form must reproduce the above
  6609. // copyright notice, this list of conditions and the following disclaimer
  6610. // in the documentation and/or other materials provided with the
  6611. // distribution.
  6612. // * Neither the name of Google Inc. nor the names of its
  6613. // contributors may be used to endorse or promote products derived from
  6614. // this software without specific prior written permission.
  6615. //
  6616. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6617. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6618. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6619. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6620. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6621. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6622. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6623. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6624. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6625. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6626. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6627. //
  6628. // Macros and functions for implementing parameterized tests
  6629. // in Google C++ Testing and Mocking Framework (Google Test)
  6630. //
  6631. // GOOGLETEST_CM0001 DO NOT DELETE
  6632. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
  6633. #define GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
  6634. // Value-parameterized tests allow you to test your code with different
  6635. // parameters without writing multiple copies of the same test.
  6636. //
  6637. // Here is how you use value-parameterized tests:
  6638. #if 0
  6639. // To write value-parameterized tests, first you should define a fixture
  6640. // class. It is usually derived from testing::TestWithParam<T> (see below for
  6641. // another inheritance scheme that's sometimes useful in more complicated
  6642. // class hierarchies), where the type of your parameter values.
  6643. // TestWithParam<T> is itself derived from testing::Test. T can be any
  6644. // copyable type. If it's a raw pointer, you are responsible for managing the
  6645. // lifespan of the pointed values.
  6646. class FooTest : public ::testing::TestWithParam<const char*> {
  6647. // You can implement all the usual class fixture members here.
  6648. };
  6649. // Then, use the TEST_P macro to define as many parameterized tests
  6650. // for this fixture as you want. The _P suffix is for "parameterized"
  6651. // or "pattern", whichever you prefer to think.
  6652. TEST_P(FooTest, DoesBlah) {
  6653. // Inside a test, access the test parameter with the GetParam() method
  6654. // of the TestWithParam<T> class:
  6655. EXPECT_TRUE(foo.Blah(GetParam()));
  6656. ...
  6657. }
  6658. TEST_P(FooTest, HasBlahBlah) {
  6659. ...
  6660. }
  6661. // Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test
  6662. // case with any set of parameters you want. Google Test defines a number
  6663. // of functions for generating test parameters. They return what we call
  6664. // (surprise!) parameter generators. Here is a summary of them, which
  6665. // are all in the testing namespace:
  6666. //
  6667. //
  6668. // Range(begin, end [, step]) - Yields values {begin, begin+step,
  6669. // begin+step+step, ...}. The values do not
  6670. // include end. step defaults to 1.
  6671. // Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}.
  6672. // ValuesIn(container) - Yields values from a C-style array, an STL
  6673. // ValuesIn(begin,end) container, or an iterator range [begin, end).
  6674. // Bool() - Yields sequence {false, true}.
  6675. // Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product
  6676. // for the math savvy) of the values generated
  6677. // by the N generators.
  6678. //
  6679. // For more details, see comments at the definitions of these functions below
  6680. // in this file.
  6681. //
  6682. // The following statement will instantiate tests from the FooTest test suite
  6683. // each with parameter values "meeny", "miny", and "moe".
  6684. INSTANTIATE_TEST_SUITE_P(InstantiationName,
  6685. FooTest,
  6686. Values("meeny", "miny", "moe"));
  6687. // To distinguish different instances of the pattern, (yes, you
  6688. // can instantiate it more than once) the first argument to the
  6689. // INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the
  6690. // actual test suite name. Remember to pick unique prefixes for different
  6691. // instantiations. The tests from the instantiation above will have
  6692. // these names:
  6693. //
  6694. // * InstantiationName/FooTest.DoesBlah/0 for "meeny"
  6695. // * InstantiationName/FooTest.DoesBlah/1 for "miny"
  6696. // * InstantiationName/FooTest.DoesBlah/2 for "moe"
  6697. // * InstantiationName/FooTest.HasBlahBlah/0 for "meeny"
  6698. // * InstantiationName/FooTest.HasBlahBlah/1 for "miny"
  6699. // * InstantiationName/FooTest.HasBlahBlah/2 for "moe"
  6700. //
  6701. // You can use these names in --gtest_filter.
  6702. //
  6703. // This statement will instantiate all tests from FooTest again, each
  6704. // with parameter values "cat" and "dog":
  6705. const char* pets[] = {"cat", "dog"};
  6706. INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));
  6707. // The tests from the instantiation above will have these names:
  6708. //
  6709. // * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat"
  6710. // * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog"
  6711. // * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat"
  6712. // * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog"
  6713. //
  6714. // Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests
  6715. // in the given test suite, whether their definitions come before or
  6716. // AFTER the INSTANTIATE_TEST_SUITE_P statement.
  6717. //
  6718. // Please also note that generator expressions (including parameters to the
  6719. // generators) are evaluated in InitGoogleTest(), after main() has started.
  6720. // This allows the user on one hand, to adjust generator parameters in order
  6721. // to dynamically determine a set of tests to run and on the other hand,
  6722. // give the user a chance to inspect the generated tests with Google Test
  6723. // reflection API before RUN_ALL_TESTS() is executed.
  6724. //
  6725. // You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc
  6726. // for more examples.
  6727. //
  6728. // In the future, we plan to publish the API for defining new parameter
  6729. // generators. But for now this interface remains part of the internal
  6730. // implementation and is subject to change.
  6731. //
  6732. //
  6733. // A parameterized test fixture must be derived from testing::Test and from
  6734. // testing::WithParamInterface<T>, where T is the type of the parameter
  6735. // values. Inheriting from TestWithParam<T> satisfies that requirement because
  6736. // TestWithParam<T> inherits from both Test and WithParamInterface. In more
  6737. // complicated hierarchies, however, it is occasionally useful to inherit
  6738. // separately from Test and WithParamInterface. For example:
  6739. class BaseTest : public ::testing::Test {
  6740. // You can inherit all the usual members for a non-parameterized test
  6741. // fixture here.
  6742. };
  6743. class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {
  6744. // The usual test fixture members go here too.
  6745. };
  6746. TEST_F(BaseTest, HasFoo) {
  6747. // This is an ordinary non-parameterized test.
  6748. }
  6749. TEST_P(DerivedTest, DoesBlah) {
  6750. // GetParam works just the same here as if you inherit from TestWithParam.
  6751. EXPECT_TRUE(foo.Blah(GetParam()));
  6752. }
  6753. #endif // 0
  6754. #include <iterator>
  6755. #include <utility>
  6756. // Copyright 2008 Google Inc.
  6757. // All Rights Reserved.
  6758. //
  6759. // Redistribution and use in source and binary forms, with or without
  6760. // modification, are permitted provided that the following conditions are
  6761. // met:
  6762. //
  6763. // * Redistributions of source code must retain the above copyright
  6764. // notice, this list of conditions and the following disclaimer.
  6765. // * Redistributions in binary form must reproduce the above
  6766. // copyright notice, this list of conditions and the following disclaimer
  6767. // in the documentation and/or other materials provided with the
  6768. // distribution.
  6769. // * Neither the name of Google Inc. nor the names of its
  6770. // contributors may be used to endorse or promote products derived from
  6771. // this software without specific prior written permission.
  6772. //
  6773. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6774. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6775. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6776. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6777. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6778. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6779. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6780. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6781. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6782. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6783. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6784. // Type and function utilities for implementing parameterized tests.
  6785. // GOOGLETEST_CM0001 DO NOT DELETE
  6786. #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
  6787. #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
  6788. #include <ctype.h>
  6789. #include <cassert>
  6790. #include <iterator>
  6791. #include <memory>
  6792. #include <set>
  6793. #include <tuple>
  6794. #include <type_traits>
  6795. #include <utility>
  6796. #include <vector>
  6797. // Copyright 2008, Google Inc.
  6798. // All rights reserved.
  6799. //
  6800. // Redistribution and use in source and binary forms, with or without
  6801. // modification, are permitted provided that the following conditions are
  6802. // met:
  6803. //
  6804. // * Redistributions of source code must retain the above copyright
  6805. // notice, this list of conditions and the following disclaimer.
  6806. // * Redistributions in binary form must reproduce the above
  6807. // copyright notice, this list of conditions and the following disclaimer
  6808. // in the documentation and/or other materials provided with the
  6809. // distribution.
  6810. // * Neither the name of Google Inc. nor the names of its
  6811. // contributors may be used to endorse or promote products derived from
  6812. // this software without specific prior written permission.
  6813. //
  6814. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6815. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6816. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6817. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6818. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6819. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6820. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6821. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6822. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6823. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6824. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6825. //
  6826. // GOOGLETEST_CM0001 DO NOT DELETE
  6827. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
  6828. #define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
  6829. #include <iosfwd>
  6830. #include <vector>
  6831. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  6832. /* class A needs to have dll-interface to be used by clients of class B */)
  6833. namespace testing {
  6834. // A copyable object representing the result of a test part (i.e. an
  6835. // assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
  6836. //
  6837. // Don't inherit from TestPartResult as its destructor is not virtual.
  6838. class GTEST_API_ TestPartResult {
  6839. public:
  6840. // The possible outcomes of a test part (i.e. an assertion or an
  6841. // explicit SUCCEED(), FAIL(), or ADD_FAILURE()).
  6842. enum Type {
  6843. kSuccess, // Succeeded.
  6844. kNonFatalFailure, // Failed but the test can continue.
  6845. kFatalFailure, // Failed and the test should be terminated.
  6846. kSkip // Skipped.
  6847. };
  6848. // C'tor. TestPartResult does NOT have a default constructor.
  6849. // Always use this constructor (with parameters) to create a
  6850. // TestPartResult object.
  6851. TestPartResult(Type a_type, const char* a_file_name, int a_line_number,
  6852. const char* a_message)
  6853. : type_(a_type),
  6854. file_name_(a_file_name == nullptr ? "" : a_file_name),
  6855. line_number_(a_line_number),
  6856. summary_(ExtractSummary(a_message)),
  6857. message_(a_message) {}
  6858. // Gets the outcome of the test part.
  6859. Type type() const { return type_; }
  6860. // Gets the name of the source file where the test part took place, or
  6861. // NULL if it's unknown.
  6862. const char* file_name() const {
  6863. return file_name_.empty() ? nullptr : file_name_.c_str();
  6864. }
  6865. // Gets the line in the source file where the test part took place,
  6866. // or -1 if it's unknown.
  6867. int line_number() const { return line_number_; }
  6868. // Gets the summary of the failure message.
  6869. const char* summary() const { return summary_.c_str(); }
  6870. // Gets the message associated with the test part.
  6871. const char* message() const { return message_.c_str(); }
  6872. // Returns true if and only if the test part was skipped.
  6873. bool skipped() const { return type_ == kSkip; }
  6874. // Returns true if and only if the test part passed.
  6875. bool passed() const { return type_ == kSuccess; }
  6876. // Returns true if and only if the test part non-fatally failed.
  6877. bool nonfatally_failed() const { return type_ == kNonFatalFailure; }
  6878. // Returns true if and only if the test part fatally failed.
  6879. bool fatally_failed() const { return type_ == kFatalFailure; }
  6880. // Returns true if and only if the test part failed.
  6881. bool failed() const { return fatally_failed() || nonfatally_failed(); }
  6882. private:
  6883. Type type_;
  6884. // Gets the summary of the failure message by omitting the stack
  6885. // trace in it.
  6886. static std::string ExtractSummary(const char* message);
  6887. // The name of the source file where the test part took place, or
  6888. // "" if the source file is unknown.
  6889. std::string file_name_;
  6890. // The line in the source file where the test part took place, or -1
  6891. // if the line number is unknown.
  6892. int line_number_;
  6893. std::string summary_; // The test failure summary.
  6894. std::string message_; // The test failure message.
  6895. };
  6896. // Prints a TestPartResult object.
  6897. std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
  6898. // An array of TestPartResult objects.
  6899. //
  6900. // Don't inherit from TestPartResultArray as its destructor is not
  6901. // virtual.
  6902. class GTEST_API_ TestPartResultArray {
  6903. public:
  6904. TestPartResultArray() {}
  6905. // Appends the given TestPartResult to the array.
  6906. void Append(const TestPartResult& result);
  6907. // Returns the TestPartResult at the given index (0-based).
  6908. const TestPartResult& GetTestPartResult(int index) const;
  6909. // Returns the number of TestPartResult objects in the array.
  6910. int size() const;
  6911. private:
  6912. std::vector<TestPartResult> array_;
  6913. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray);
  6914. };
  6915. // This interface knows how to report a test part result.
  6916. class GTEST_API_ TestPartResultReporterInterface {
  6917. public:
  6918. virtual ~TestPartResultReporterInterface() {}
  6919. virtual void ReportTestPartResult(const TestPartResult& result) = 0;
  6920. };
  6921. namespace internal {
  6922. // This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a
  6923. // statement generates new fatal failures. To do so it registers itself as the
  6924. // current test part result reporter. Besides checking if fatal failures were
  6925. // reported, it only delegates the reporting to the former result reporter.
  6926. // The original result reporter is restored in the destructor.
  6927. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  6928. class GTEST_API_ HasNewFatalFailureHelper
  6929. : public TestPartResultReporterInterface {
  6930. public:
  6931. HasNewFatalFailureHelper();
  6932. ~HasNewFatalFailureHelper() override;
  6933. void ReportTestPartResult(const TestPartResult& result) override;
  6934. bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
  6935. private:
  6936. bool has_new_fatal_failure_;
  6937. TestPartResultReporterInterface* original_reporter_;
  6938. GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper);
  6939. };
  6940. } // namespace internal
  6941. } // namespace testing
  6942. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  6943. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
  6944. namespace testing {
  6945. // Input to a parameterized test name generator, describing a test parameter.
  6946. // Consists of the parameter value and the integer parameter index.
  6947. template <class ParamType>
  6948. struct TestParamInfo {
  6949. TestParamInfo(const ParamType& a_param, size_t an_index) :
  6950. param(a_param),
  6951. index(an_index) {}
  6952. ParamType param;
  6953. size_t index;
  6954. };
  6955. // A builtin parameterized test name generator which returns the result of
  6956. // testing::PrintToString.
  6957. struct PrintToStringParamName {
  6958. template <class ParamType>
  6959. std::string operator()(const TestParamInfo<ParamType>& info) const {
  6960. return PrintToString(info.param);
  6961. }
  6962. };
  6963. namespace internal {
  6964. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  6965. // Utility Functions
  6966. // Outputs a message explaining invalid registration of different
  6967. // fixture class for the same test suite. This may happen when
  6968. // TEST_P macro is used to define two tests with the same name
  6969. // but in different namespaces.
  6970. GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
  6971. CodeLocation code_location);
  6972. template <typename> class ParamGeneratorInterface;
  6973. template <typename> class ParamGenerator;
  6974. // Interface for iterating over elements provided by an implementation
  6975. // of ParamGeneratorInterface<T>.
  6976. template <typename T>
  6977. class ParamIteratorInterface {
  6978. public:
  6979. virtual ~ParamIteratorInterface() {}
  6980. // A pointer to the base generator instance.
  6981. // Used only for the purposes of iterator comparison
  6982. // to make sure that two iterators belong to the same generator.
  6983. virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;
  6984. // Advances iterator to point to the next element
  6985. // provided by the generator. The caller is responsible
  6986. // for not calling Advance() on an iterator equal to
  6987. // BaseGenerator()->End().
  6988. virtual void Advance() = 0;
  6989. // Clones the iterator object. Used for implementing copy semantics
  6990. // of ParamIterator<T>.
  6991. virtual ParamIteratorInterface* Clone() const = 0;
  6992. // Dereferences the current iterator and provides (read-only) access
  6993. // to the pointed value. It is the caller's responsibility not to call
  6994. // Current() on an iterator equal to BaseGenerator()->End().
  6995. // Used for implementing ParamGenerator<T>::operator*().
  6996. virtual const T* Current() const = 0;
  6997. // Determines whether the given iterator and other point to the same
  6998. // element in the sequence generated by the generator.
  6999. // Used for implementing ParamGenerator<T>::operator==().
  7000. virtual bool Equals(const ParamIteratorInterface& other) const = 0;
  7001. };
  7002. // Class iterating over elements provided by an implementation of
  7003. // ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
  7004. // and implements the const forward iterator concept.
  7005. template <typename T>
  7006. class ParamIterator {
  7007. public:
  7008. typedef T value_type;
  7009. typedef const T& reference;
  7010. typedef ptrdiff_t difference_type;
  7011. // ParamIterator assumes ownership of the impl_ pointer.
  7012. ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
  7013. ParamIterator& operator=(const ParamIterator& other) {
  7014. if (this != &other)
  7015. impl_.reset(other.impl_->Clone());
  7016. return *this;
  7017. }
  7018. const T& operator*() const { return *impl_->Current(); }
  7019. const T* operator->() const { return impl_->Current(); }
  7020. // Prefix version of operator++.
  7021. ParamIterator& operator++() {
  7022. impl_->Advance();
  7023. return *this;
  7024. }
  7025. // Postfix version of operator++.
  7026. ParamIterator operator++(int /*unused*/) {
  7027. ParamIteratorInterface<T>* clone = impl_->Clone();
  7028. impl_->Advance();
  7029. return ParamIterator(clone);
  7030. }
  7031. bool operator==(const ParamIterator& other) const {
  7032. return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);
  7033. }
  7034. bool operator!=(const ParamIterator& other) const {
  7035. return !(*this == other);
  7036. }
  7037. private:
  7038. friend class ParamGenerator<T>;
  7039. explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
  7040. std::unique_ptr<ParamIteratorInterface<T> > impl_;
  7041. };
  7042. // ParamGeneratorInterface<T> is the binary interface to access generators
  7043. // defined in other translation units.
  7044. template <typename T>
  7045. class ParamGeneratorInterface {
  7046. public:
  7047. typedef T ParamType;
  7048. virtual ~ParamGeneratorInterface() {}
  7049. // Generator interface definition
  7050. virtual ParamIteratorInterface<T>* Begin() const = 0;
  7051. virtual ParamIteratorInterface<T>* End() const = 0;
  7052. };
  7053. // Wraps ParamGeneratorInterface<T> and provides general generator syntax
  7054. // compatible with the STL Container concept.
  7055. // This class implements copy initialization semantics and the contained
  7056. // ParamGeneratorInterface<T> instance is shared among all copies
  7057. // of the original object. This is possible because that instance is immutable.
  7058. template<typename T>
  7059. class ParamGenerator {
  7060. public:
  7061. typedef ParamIterator<T> iterator;
  7062. explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}
  7063. ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}
  7064. ParamGenerator& operator=(const ParamGenerator& other) {
  7065. impl_ = other.impl_;
  7066. return *this;
  7067. }
  7068. iterator begin() const { return iterator(impl_->Begin()); }
  7069. iterator end() const { return iterator(impl_->End()); }
  7070. private:
  7071. std::shared_ptr<const ParamGeneratorInterface<T> > impl_;
  7072. };
  7073. // Generates values from a range of two comparable values. Can be used to
  7074. // generate sequences of user-defined types that implement operator+() and
  7075. // operator<().
  7076. // This class is used in the Range() function.
  7077. template <typename T, typename IncrementT>
  7078. class RangeGenerator : public ParamGeneratorInterface<T> {
  7079. public:
  7080. RangeGenerator(T begin, T end, IncrementT step)
  7081. : begin_(begin), end_(end),
  7082. step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
  7083. ~RangeGenerator() override {}
  7084. ParamIteratorInterface<T>* Begin() const override {
  7085. return new Iterator(this, begin_, 0, step_);
  7086. }
  7087. ParamIteratorInterface<T>* End() const override {
  7088. return new Iterator(this, end_, end_index_, step_);
  7089. }
  7090. private:
  7091. class Iterator : public ParamIteratorInterface<T> {
  7092. public:
  7093. Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
  7094. IncrementT step)
  7095. : base_(base), value_(value), index_(index), step_(step) {}
  7096. ~Iterator() override {}
  7097. const ParamGeneratorInterface<T>* BaseGenerator() const override {
  7098. return base_;
  7099. }
  7100. void Advance() override {
  7101. value_ = static_cast<T>(value_ + step_);
  7102. index_++;
  7103. }
  7104. ParamIteratorInterface<T>* Clone() const override {
  7105. return new Iterator(*this);
  7106. }
  7107. const T* Current() const override { return &value_; }
  7108. bool Equals(const ParamIteratorInterface<T>& other) const override {
  7109. // Having the same base generator guarantees that the other
  7110. // iterator is of the same type and we can downcast.
  7111. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
  7112. << "The program attempted to compare iterators "
  7113. << "from different generators." << std::endl;
  7114. const int other_index =
  7115. CheckedDowncastToActualType<const Iterator>(&other)->index_;
  7116. return index_ == other_index;
  7117. }
  7118. private:
  7119. Iterator(const Iterator& other)
  7120. : ParamIteratorInterface<T>(),
  7121. base_(other.base_), value_(other.value_), index_(other.index_),
  7122. step_(other.step_) {}
  7123. // No implementation - assignment is unsupported.
  7124. void operator=(const Iterator& other);
  7125. const ParamGeneratorInterface<T>* const base_;
  7126. T value_;
  7127. int index_;
  7128. const IncrementT step_;
  7129. }; // class RangeGenerator::Iterator
  7130. static int CalculateEndIndex(const T& begin,
  7131. const T& end,
  7132. const IncrementT& step) {
  7133. int end_index = 0;
  7134. for (T i = begin; i < end; i = static_cast<T>(i + step))
  7135. end_index++;
  7136. return end_index;
  7137. }
  7138. // No implementation - assignment is unsupported.
  7139. void operator=(const RangeGenerator& other);
  7140. const T begin_;
  7141. const T end_;
  7142. const IncrementT step_;
  7143. // The index for the end() iterator. All the elements in the generated
  7144. // sequence are indexed (0-based) to aid iterator comparison.
  7145. const int end_index_;
  7146. }; // class RangeGenerator
  7147. // Generates values from a pair of STL-style iterators. Used in the
  7148. // ValuesIn() function. The elements are copied from the source range
  7149. // since the source can be located on the stack, and the generator
  7150. // is likely to persist beyond that stack frame.
  7151. template <typename T>
  7152. class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
  7153. public:
  7154. template <typename ForwardIterator>
  7155. ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
  7156. : container_(begin, end) {}
  7157. ~ValuesInIteratorRangeGenerator() override {}
  7158. ParamIteratorInterface<T>* Begin() const override {
  7159. return new Iterator(this, container_.begin());
  7160. }
  7161. ParamIteratorInterface<T>* End() const override {
  7162. return new Iterator(this, container_.end());
  7163. }
  7164. private:
  7165. typedef typename ::std::vector<T> ContainerType;
  7166. class Iterator : public ParamIteratorInterface<T> {
  7167. public:
  7168. Iterator(const ParamGeneratorInterface<T>* base,
  7169. typename ContainerType::const_iterator iterator)
  7170. : base_(base), iterator_(iterator) {}
  7171. ~Iterator() override {}
  7172. const ParamGeneratorInterface<T>* BaseGenerator() const override {
  7173. return base_;
  7174. }
  7175. void Advance() override {
  7176. ++iterator_;
  7177. value_.reset();
  7178. }
  7179. ParamIteratorInterface<T>* Clone() const override {
  7180. return new Iterator(*this);
  7181. }
  7182. // We need to use cached value referenced by iterator_ because *iterator_
  7183. // can return a temporary object (and of type other then T), so just
  7184. // having "return &*iterator_;" doesn't work.
  7185. // value_ is updated here and not in Advance() because Advance()
  7186. // can advance iterator_ beyond the end of the range, and we cannot
  7187. // detect that fact. The client code, on the other hand, is
  7188. // responsible for not calling Current() on an out-of-range iterator.
  7189. const T* Current() const override {
  7190. if (value_.get() == nullptr) value_.reset(new T(*iterator_));
  7191. return value_.get();
  7192. }
  7193. bool Equals(const ParamIteratorInterface<T>& other) const override {
  7194. // Having the same base generator guarantees that the other
  7195. // iterator is of the same type and we can downcast.
  7196. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
  7197. << "The program attempted to compare iterators "
  7198. << "from different generators." << std::endl;
  7199. return iterator_ ==
  7200. CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
  7201. }
  7202. private:
  7203. Iterator(const Iterator& other)
  7204. // The explicit constructor call suppresses a false warning
  7205. // emitted by gcc when supplied with the -Wextra option.
  7206. : ParamIteratorInterface<T>(),
  7207. base_(other.base_),
  7208. iterator_(other.iterator_) {}
  7209. const ParamGeneratorInterface<T>* const base_;
  7210. typename ContainerType::const_iterator iterator_;
  7211. // A cached value of *iterator_. We keep it here to allow access by
  7212. // pointer in the wrapping iterator's operator->().
  7213. // value_ needs to be mutable to be accessed in Current().
  7214. // Use of std::unique_ptr helps manage cached value's lifetime,
  7215. // which is bound by the lifespan of the iterator itself.
  7216. mutable std::unique_ptr<const T> value_;
  7217. }; // class ValuesInIteratorRangeGenerator::Iterator
  7218. // No implementation - assignment is unsupported.
  7219. void operator=(const ValuesInIteratorRangeGenerator& other);
  7220. const ContainerType container_;
  7221. }; // class ValuesInIteratorRangeGenerator
  7222. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7223. //
  7224. // Default parameterized test name generator, returns a string containing the
  7225. // integer test parameter index.
  7226. template <class ParamType>
  7227. std::string DefaultParamName(const TestParamInfo<ParamType>& info) {
  7228. Message name_stream;
  7229. name_stream << info.index;
  7230. return name_stream.GetString();
  7231. }
  7232. template <typename T = int>
  7233. void TestNotEmpty() {
  7234. static_assert(sizeof(T) == 0, "Empty arguments are not allowed.");
  7235. }
  7236. template <typename T = int>
  7237. void TestNotEmpty(const T&) {}
  7238. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7239. //
  7240. // Stores a parameter value and later creates tests parameterized with that
  7241. // value.
  7242. template <class TestClass>
  7243. class ParameterizedTestFactory : public TestFactoryBase {
  7244. public:
  7245. typedef typename TestClass::ParamType ParamType;
  7246. explicit ParameterizedTestFactory(ParamType parameter) :
  7247. parameter_(parameter) {}
  7248. Test* CreateTest() override {
  7249. TestClass::SetParam(&parameter_);
  7250. return new TestClass();
  7251. }
  7252. private:
  7253. const ParamType parameter_;
  7254. GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
  7255. };
  7256. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7257. //
  7258. // TestMetaFactoryBase is a base class for meta-factories that create
  7259. // test factories for passing into MakeAndRegisterTestInfo function.
  7260. template <class ParamType>
  7261. class TestMetaFactoryBase {
  7262. public:
  7263. virtual ~TestMetaFactoryBase() {}
  7264. virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
  7265. };
  7266. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7267. //
  7268. // TestMetaFactory creates test factories for passing into
  7269. // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
  7270. // ownership of test factory pointer, same factory object cannot be passed
  7271. // into that method twice. But ParameterizedTestSuiteInfo is going to call
  7272. // it for each Test/Parameter value combination. Thus it needs meta factory
  7273. // creator class.
  7274. template <class TestSuite>
  7275. class TestMetaFactory
  7276. : public TestMetaFactoryBase<typename TestSuite::ParamType> {
  7277. public:
  7278. using ParamType = typename TestSuite::ParamType;
  7279. TestMetaFactory() {}
  7280. TestFactoryBase* CreateTestFactory(ParamType parameter) override {
  7281. return new ParameterizedTestFactory<TestSuite>(parameter);
  7282. }
  7283. private:
  7284. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
  7285. };
  7286. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7287. //
  7288. // ParameterizedTestSuiteInfoBase is a generic interface
  7289. // to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase
  7290. // accumulates test information provided by TEST_P macro invocations
  7291. // and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations
  7292. // and uses that information to register all resulting test instances
  7293. // in RegisterTests method. The ParameterizeTestSuiteRegistry class holds
  7294. // a collection of pointers to the ParameterizedTestSuiteInfo objects
  7295. // and calls RegisterTests() on each of them when asked.
  7296. class ParameterizedTestSuiteInfoBase {
  7297. public:
  7298. virtual ~ParameterizedTestSuiteInfoBase() {}
  7299. // Base part of test suite name for display purposes.
  7300. virtual const std::string& GetTestSuiteName() const = 0;
  7301. // Test suite id to verify identity.
  7302. virtual TypeId GetTestSuiteTypeId() const = 0;
  7303. // UnitTest class invokes this method to register tests in this
  7304. // test suite right before running them in RUN_ALL_TESTS macro.
  7305. // This method should not be called more than once on any single
  7306. // instance of a ParameterizedTestSuiteInfoBase derived class.
  7307. virtual void RegisterTests() = 0;
  7308. protected:
  7309. ParameterizedTestSuiteInfoBase() {}
  7310. private:
  7311. GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase);
  7312. };
  7313. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7314. //
  7315. // Report a the name of a test_suit as safe to ignore
  7316. // as the side effect of construction of this type.
  7317. struct GTEST_API_ MarkAsIgnored {
  7318. explicit MarkAsIgnored(const char* test_suite);
  7319. };
  7320. GTEST_API_ void InsertSyntheticTestCase(const std::string& name,
  7321. CodeLocation location, bool has_test_p);
  7322. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7323. //
  7324. // ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P
  7325. // macro invocations for a particular test suite and generators
  7326. // obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that
  7327. // test suite. It registers tests with all values generated by all
  7328. // generators when asked.
  7329. template <class TestSuite>
  7330. class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
  7331. public:
  7332. // ParamType and GeneratorCreationFunc are private types but are required
  7333. // for declarations of public methods AddTestPattern() and
  7334. // AddTestSuiteInstantiation().
  7335. using ParamType = typename TestSuite::ParamType;
  7336. // A function that returns an instance of appropriate generator type.
  7337. typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
  7338. using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&);
  7339. explicit ParameterizedTestSuiteInfo(const char* name,
  7340. CodeLocation code_location)
  7341. : test_suite_name_(name), code_location_(code_location) {}
  7342. // Test suite base name for display purposes.
  7343. const std::string& GetTestSuiteName() const override {
  7344. return test_suite_name_;
  7345. }
  7346. // Test suite id to verify identity.
  7347. TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }
  7348. // TEST_P macro uses AddTestPattern() to record information
  7349. // about a single test in a LocalTestInfo structure.
  7350. // test_suite_name is the base name of the test suite (without invocation
  7351. // prefix). test_base_name is the name of an individual test without
  7352. // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
  7353. // test suite base name and DoBar is test base name.
  7354. void AddTestPattern(const char* test_suite_name, const char* test_base_name,
  7355. TestMetaFactoryBase<ParamType>* meta_factory,
  7356. CodeLocation code_location) {
  7357. tests_.push_back(std::shared_ptr<TestInfo>(new TestInfo(
  7358. test_suite_name, test_base_name, meta_factory, code_location)));
  7359. }
  7360. // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
  7361. // about a generator.
  7362. int AddTestSuiteInstantiation(const std::string& instantiation_name,
  7363. GeneratorCreationFunc* func,
  7364. ParamNameGeneratorFunc* name_func,
  7365. const char* file, int line) {
  7366. instantiations_.push_back(
  7367. InstantiationInfo(instantiation_name, func, name_func, file, line));
  7368. return 0; // Return value used only to run this method in namespace scope.
  7369. }
  7370. // UnitTest class invokes this method to register tests in this test suite
  7371. // right before running tests in RUN_ALL_TESTS macro.
  7372. // This method should not be called more than once on any single
  7373. // instance of a ParameterizedTestSuiteInfoBase derived class.
  7374. // UnitTest has a guard to prevent from calling this method more than once.
  7375. void RegisterTests() override {
  7376. bool generated_instantiations = false;
  7377. for (typename TestInfoContainer::iterator test_it = tests_.begin();
  7378. test_it != tests_.end(); ++test_it) {
  7379. std::shared_ptr<TestInfo> test_info = *test_it;
  7380. for (typename InstantiationContainer::iterator gen_it =
  7381. instantiations_.begin(); gen_it != instantiations_.end();
  7382. ++gen_it) {
  7383. const std::string& instantiation_name = gen_it->name;
  7384. ParamGenerator<ParamType> generator((*gen_it->generator)());
  7385. ParamNameGeneratorFunc* name_func = gen_it->name_func;
  7386. const char* file = gen_it->file;
  7387. int line = gen_it->line;
  7388. std::string test_suite_name;
  7389. if ( !instantiation_name.empty() )
  7390. test_suite_name = instantiation_name + "/";
  7391. test_suite_name += test_info->test_suite_base_name;
  7392. size_t i = 0;
  7393. std::set<std::string> test_param_names;
  7394. for (typename ParamGenerator<ParamType>::iterator param_it =
  7395. generator.begin();
  7396. param_it != generator.end(); ++param_it, ++i) {
  7397. generated_instantiations = true;
  7398. Message test_name_stream;
  7399. std::string param_name = name_func(
  7400. TestParamInfo<ParamType>(*param_it, i));
  7401. GTEST_CHECK_(IsValidParamName(param_name))
  7402. << "Parameterized test name '" << param_name
  7403. << "' is invalid, in " << file
  7404. << " line " << line << std::endl;
  7405. GTEST_CHECK_(test_param_names.count(param_name) == 0)
  7406. << "Duplicate parameterized test name '" << param_name
  7407. << "', in " << file << " line " << line << std::endl;
  7408. test_param_names.insert(param_name);
  7409. if (!test_info->test_base_name.empty()) {
  7410. test_name_stream << test_info->test_base_name << "/";
  7411. }
  7412. test_name_stream << param_name;
  7413. MakeAndRegisterTestInfo(
  7414. test_suite_name.c_str(), test_name_stream.GetString().c_str(),
  7415. nullptr, // No type parameter.
  7416. PrintToString(*param_it).c_str(), test_info->code_location,
  7417. GetTestSuiteTypeId(),
  7418. SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
  7419. SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
  7420. test_info->test_meta_factory->CreateTestFactory(*param_it));
  7421. } // for param_it
  7422. } // for gen_it
  7423. } // for test_it
  7424. if (!generated_instantiations) {
  7425. // There are no generaotrs, or they all generate nothing ...
  7426. InsertSyntheticTestCase(GetTestSuiteName(), code_location_,
  7427. !tests_.empty());
  7428. }
  7429. } // RegisterTests
  7430. private:
  7431. // LocalTestInfo structure keeps information about a single test registered
  7432. // with TEST_P macro.
  7433. struct TestInfo {
  7434. TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
  7435. TestMetaFactoryBase<ParamType>* a_test_meta_factory,
  7436. CodeLocation a_code_location)
  7437. : test_suite_base_name(a_test_suite_base_name),
  7438. test_base_name(a_test_base_name),
  7439. test_meta_factory(a_test_meta_factory),
  7440. code_location(a_code_location) {}
  7441. const std::string test_suite_base_name;
  7442. const std::string test_base_name;
  7443. const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
  7444. const CodeLocation code_location;
  7445. };
  7446. using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
  7447. // Records data received from INSTANTIATE_TEST_SUITE_P macros:
  7448. // <Instantiation name, Sequence generator creation function,
  7449. // Name generator function, Source file, Source line>
  7450. struct InstantiationInfo {
  7451. InstantiationInfo(const std::string &name_in,
  7452. GeneratorCreationFunc* generator_in,
  7453. ParamNameGeneratorFunc* name_func_in,
  7454. const char* file_in,
  7455. int line_in)
  7456. : name(name_in),
  7457. generator(generator_in),
  7458. name_func(name_func_in),
  7459. file(file_in),
  7460. line(line_in) {}
  7461. std::string name;
  7462. GeneratorCreationFunc* generator;
  7463. ParamNameGeneratorFunc* name_func;
  7464. const char* file;
  7465. int line;
  7466. };
  7467. typedef ::std::vector<InstantiationInfo> InstantiationContainer;
  7468. static bool IsValidParamName(const std::string& name) {
  7469. // Check for empty string
  7470. if (name.empty())
  7471. return false;
  7472. // Check for invalid characters
  7473. for (std::string::size_type index = 0; index < name.size(); ++index) {
  7474. if (!IsAlNum(name[index]) && name[index] != '_')
  7475. return false;
  7476. }
  7477. return true;
  7478. }
  7479. const std::string test_suite_name_;
  7480. CodeLocation code_location_;
  7481. TestInfoContainer tests_;
  7482. InstantiationContainer instantiations_;
  7483. GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo);
  7484. }; // class ParameterizedTestSuiteInfo
  7485. // Legacy API is deprecated but still available
  7486. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  7487. template <class TestCase>
  7488. using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
  7489. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  7490. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  7491. //
  7492. // ParameterizedTestSuiteRegistry contains a map of
  7493. // ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P
  7494. // and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding
  7495. // ParameterizedTestSuiteInfo descriptors.
  7496. class ParameterizedTestSuiteRegistry {
  7497. public:
  7498. ParameterizedTestSuiteRegistry() {}
  7499. ~ParameterizedTestSuiteRegistry() {
  7500. for (auto& test_suite_info : test_suite_infos_) {
  7501. delete test_suite_info;
  7502. }
  7503. }
  7504. // Looks up or creates and returns a structure containing information about
  7505. // tests and instantiations of a particular test suite.
  7506. template <class TestSuite>
  7507. ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder(
  7508. const char* test_suite_name, CodeLocation code_location) {
  7509. ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr;
  7510. for (auto& test_suite_info : test_suite_infos_) {
  7511. if (test_suite_info->GetTestSuiteName() == test_suite_name) {
  7512. if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {
  7513. // Complain about incorrect usage of Google Test facilities
  7514. // and terminate the program since we cannot guaranty correct
  7515. // test suite setup and tear-down in this case.
  7516. ReportInvalidTestSuiteType(test_suite_name, code_location);
  7517. posix::Abort();
  7518. } else {
  7519. // At this point we are sure that the object we found is of the same
  7520. // type we are looking for, so we downcast it to that type
  7521. // without further checks.
  7522. typed_test_info = CheckedDowncastToActualType<
  7523. ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info);
  7524. }
  7525. break;
  7526. }
  7527. }
  7528. if (typed_test_info == nullptr) {
  7529. typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>(
  7530. test_suite_name, code_location);
  7531. test_suite_infos_.push_back(typed_test_info);
  7532. }
  7533. return typed_test_info;
  7534. }
  7535. void RegisterTests() {
  7536. for (auto& test_suite_info : test_suite_infos_) {
  7537. test_suite_info->RegisterTests();
  7538. }
  7539. }
  7540. // Legacy API is deprecated but still available
  7541. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  7542. template <class TestCase>
  7543. ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
  7544. const char* test_case_name, CodeLocation code_location) {
  7545. return GetTestSuitePatternHolder<TestCase>(test_case_name, code_location);
  7546. }
  7547. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  7548. private:
  7549. using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>;
  7550. TestSuiteInfoContainer test_suite_infos_;
  7551. GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry);
  7552. };
  7553. // Keep track of what type-parameterized test suite are defined and
  7554. // where as well as which are intatiated. This allows susequently
  7555. // identifying suits that are defined but never used.
  7556. class TypeParameterizedTestSuiteRegistry {
  7557. public:
  7558. // Add a suite definition
  7559. void RegisterTestSuite(const char* test_suite_name,
  7560. CodeLocation code_location);
  7561. // Add an instantiation of a suit.
  7562. void RegisterInstantiation(const char* test_suite_name);
  7563. // For each suit repored as defined but not reported as instantiation,
  7564. // emit a test that reports that fact (configurably, as an error).
  7565. void CheckForInstantiations();
  7566. private:
  7567. struct TypeParameterizedTestSuiteInfo {
  7568. explicit TypeParameterizedTestSuiteInfo(CodeLocation c)
  7569. : code_location(c), instantiated(false) {}
  7570. CodeLocation code_location;
  7571. bool instantiated;
  7572. };
  7573. std::map<std::string, TypeParameterizedTestSuiteInfo> suites_;
  7574. };
  7575. } // namespace internal
  7576. // Forward declarations of ValuesIn(), which is implemented in
  7577. // include/gtest/gtest-param-test.h.
  7578. template <class Container>
  7579. internal::ParamGenerator<typename Container::value_type> ValuesIn(
  7580. const Container& container);
  7581. namespace internal {
  7582. // Used in the Values() function to provide polymorphic capabilities.
  7583. #ifdef _MSC_VER
  7584. #pragma warning(push)
  7585. #pragma warning(disable : 4100)
  7586. #endif
  7587. template <typename... Ts>
  7588. class ValueArray {
  7589. public:
  7590. explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}
  7591. template <typename T>
  7592. operator ParamGenerator<T>() const { // NOLINT
  7593. return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>()));
  7594. }
  7595. private:
  7596. template <typename T, size_t... I>
  7597. std::vector<T> MakeVector(IndexSequence<I...>) const {
  7598. return std::vector<T>{static_cast<T>(v_.template Get<I>())...};
  7599. }
  7600. FlatTuple<Ts...> v_;
  7601. };
  7602. #ifdef _MSC_VER
  7603. #pragma warning(pop)
  7604. #endif
  7605. template <typename... T>
  7606. class CartesianProductGenerator
  7607. : public ParamGeneratorInterface<::std::tuple<T...>> {
  7608. public:
  7609. typedef ::std::tuple<T...> ParamType;
  7610. CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
  7611. : generators_(g) {}
  7612. ~CartesianProductGenerator() override {}
  7613. ParamIteratorInterface<ParamType>* Begin() const override {
  7614. return new Iterator(this, generators_, false);
  7615. }
  7616. ParamIteratorInterface<ParamType>* End() const override {
  7617. return new Iterator(this, generators_, true);
  7618. }
  7619. private:
  7620. template <class I>
  7621. class IteratorImpl;
  7622. template <size_t... I>
  7623. class IteratorImpl<IndexSequence<I...>>
  7624. : public ParamIteratorInterface<ParamType> {
  7625. public:
  7626. IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
  7627. const std::tuple<ParamGenerator<T>...>& generators, bool is_end)
  7628. : base_(base),
  7629. begin_(std::get<I>(generators).begin()...),
  7630. end_(std::get<I>(generators).end()...),
  7631. current_(is_end ? end_ : begin_) {
  7632. ComputeCurrentValue();
  7633. }
  7634. ~IteratorImpl() override {}
  7635. const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
  7636. return base_;
  7637. }
  7638. // Advance should not be called on beyond-of-range iterators
  7639. // so no component iterators must be beyond end of range, either.
  7640. void Advance() override {
  7641. assert(!AtEnd());
  7642. // Advance the last iterator.
  7643. ++std::get<sizeof...(T) - 1>(current_);
  7644. // if that reaches end, propagate that up.
  7645. AdvanceIfEnd<sizeof...(T) - 1>();
  7646. ComputeCurrentValue();
  7647. }
  7648. ParamIteratorInterface<ParamType>* Clone() const override {
  7649. return new IteratorImpl(*this);
  7650. }
  7651. const ParamType* Current() const override { return current_value_.get(); }
  7652. bool Equals(const ParamIteratorInterface<ParamType>& other) const override {
  7653. // Having the same base generator guarantees that the other
  7654. // iterator is of the same type and we can downcast.
  7655. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
  7656. << "The program attempted to compare iterators "
  7657. << "from different generators." << std::endl;
  7658. const IteratorImpl* typed_other =
  7659. CheckedDowncastToActualType<const IteratorImpl>(&other);
  7660. // We must report iterators equal if they both point beyond their
  7661. // respective ranges. That can happen in a variety of fashions,
  7662. // so we have to consult AtEnd().
  7663. if (AtEnd() && typed_other->AtEnd()) return true;
  7664. bool same = true;
  7665. bool dummy[] = {
  7666. (same = same && std::get<I>(current_) ==
  7667. std::get<I>(typed_other->current_))...};
  7668. (void)dummy;
  7669. return same;
  7670. }
  7671. private:
  7672. template <size_t ThisI>
  7673. void AdvanceIfEnd() {
  7674. if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return;
  7675. bool last = ThisI == 0;
  7676. if (last) {
  7677. // We are done. Nothing else to propagate.
  7678. return;
  7679. }
  7680. constexpr size_t NextI = ThisI - (ThisI != 0);
  7681. std::get<ThisI>(current_) = std::get<ThisI>(begin_);
  7682. ++std::get<NextI>(current_);
  7683. AdvanceIfEnd<NextI>();
  7684. }
  7685. void ComputeCurrentValue() {
  7686. if (!AtEnd())
  7687. current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...);
  7688. }
  7689. bool AtEnd() const {
  7690. bool at_end = false;
  7691. bool dummy[] = {
  7692. (at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...};
  7693. (void)dummy;
  7694. return at_end;
  7695. }
  7696. const ParamGeneratorInterface<ParamType>* const base_;
  7697. std::tuple<typename ParamGenerator<T>::iterator...> begin_;
  7698. std::tuple<typename ParamGenerator<T>::iterator...> end_;
  7699. std::tuple<typename ParamGenerator<T>::iterator...> current_;
  7700. std::shared_ptr<ParamType> current_value_;
  7701. };
  7702. using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>;
  7703. std::tuple<ParamGenerator<T>...> generators_;
  7704. };
  7705. template <class... Gen>
  7706. class CartesianProductHolder {
  7707. public:
  7708. CartesianProductHolder(const Gen&... g) : generators_(g...) {}
  7709. template <typename... T>
  7710. operator ParamGenerator<::std::tuple<T...>>() const {
  7711. return ParamGenerator<::std::tuple<T...>>(
  7712. new CartesianProductGenerator<T...>(generators_));
  7713. }
  7714. private:
  7715. std::tuple<Gen...> generators_;
  7716. };
  7717. } // namespace internal
  7718. } // namespace testing
  7719. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
  7720. namespace testing {
  7721. // Functions producing parameter generators.
  7722. //
  7723. // Google Test uses these generators to produce parameters for value-
  7724. // parameterized tests. When a parameterized test suite is instantiated
  7725. // with a particular generator, Google Test creates and runs tests
  7726. // for each element in the sequence produced by the generator.
  7727. //
  7728. // In the following sample, tests from test suite FooTest are instantiated
  7729. // each three times with parameter values 3, 5, and 8:
  7730. //
  7731. // class FooTest : public TestWithParam<int> { ... };
  7732. //
  7733. // TEST_P(FooTest, TestThis) {
  7734. // }
  7735. // TEST_P(FooTest, TestThat) {
  7736. // }
  7737. // INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8));
  7738. //
  7739. // Range() returns generators providing sequences of values in a range.
  7740. //
  7741. // Synopsis:
  7742. // Range(start, end)
  7743. // - returns a generator producing a sequence of values {start, start+1,
  7744. // start+2, ..., }.
  7745. // Range(start, end, step)
  7746. // - returns a generator producing a sequence of values {start, start+step,
  7747. // start+step+step, ..., }.
  7748. // Notes:
  7749. // * The generated sequences never include end. For example, Range(1, 5)
  7750. // returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2)
  7751. // returns a generator producing {1, 3, 5, 7}.
  7752. // * start and end must have the same type. That type may be any integral or
  7753. // floating-point type or a user defined type satisfying these conditions:
  7754. // * It must be assignable (have operator=() defined).
  7755. // * It must have operator+() (operator+(int-compatible type) for
  7756. // two-operand version).
  7757. // * It must have operator<() defined.
  7758. // Elements in the resulting sequences will also have that type.
  7759. // * Condition start < end must be satisfied in order for resulting sequences
  7760. // to contain any elements.
  7761. //
  7762. template <typename T, typename IncrementT>
  7763. internal::ParamGenerator<T> Range(T start, T end, IncrementT step) {
  7764. return internal::ParamGenerator<T>(
  7765. new internal::RangeGenerator<T, IncrementT>(start, end, step));
  7766. }
  7767. template <typename T>
  7768. internal::ParamGenerator<T> Range(T start, T end) {
  7769. return Range(start, end, 1);
  7770. }
  7771. // ValuesIn() function allows generation of tests with parameters coming from
  7772. // a container.
  7773. //
  7774. // Synopsis:
  7775. // ValuesIn(const T (&array)[N])
  7776. // - returns a generator producing sequences with elements from
  7777. // a C-style array.
  7778. // ValuesIn(const Container& container)
  7779. // - returns a generator producing sequences with elements from
  7780. // an STL-style container.
  7781. // ValuesIn(Iterator begin, Iterator end)
  7782. // - returns a generator producing sequences with elements from
  7783. // a range [begin, end) defined by a pair of STL-style iterators. These
  7784. // iterators can also be plain C pointers.
  7785. //
  7786. // Please note that ValuesIn copies the values from the containers
  7787. // passed in and keeps them to generate tests in RUN_ALL_TESTS().
  7788. //
  7789. // Examples:
  7790. //
  7791. // This instantiates tests from test suite StringTest
  7792. // each with C-string values of "foo", "bar", and "baz":
  7793. //
  7794. // const char* strings[] = {"foo", "bar", "baz"};
  7795. // INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings));
  7796. //
  7797. // This instantiates tests from test suite StlStringTest
  7798. // each with STL strings with values "a" and "b":
  7799. //
  7800. // ::std::vector< ::std::string> GetParameterStrings() {
  7801. // ::std::vector< ::std::string> v;
  7802. // v.push_back("a");
  7803. // v.push_back("b");
  7804. // return v;
  7805. // }
  7806. //
  7807. // INSTANTIATE_TEST_SUITE_P(CharSequence,
  7808. // StlStringTest,
  7809. // ValuesIn(GetParameterStrings()));
  7810. //
  7811. //
  7812. // This will also instantiate tests from CharTest
  7813. // each with parameter values 'a' and 'b':
  7814. //
  7815. // ::std::list<char> GetParameterChars() {
  7816. // ::std::list<char> list;
  7817. // list.push_back('a');
  7818. // list.push_back('b');
  7819. // return list;
  7820. // }
  7821. // ::std::list<char> l = GetParameterChars();
  7822. // INSTANTIATE_TEST_SUITE_P(CharSequence2,
  7823. // CharTest,
  7824. // ValuesIn(l.begin(), l.end()));
  7825. //
  7826. template <typename ForwardIterator>
  7827. internal::ParamGenerator<
  7828. typename std::iterator_traits<ForwardIterator>::value_type>
  7829. ValuesIn(ForwardIterator begin, ForwardIterator end) {
  7830. typedef typename std::iterator_traits<ForwardIterator>::value_type ParamType;
  7831. return internal::ParamGenerator<ParamType>(
  7832. new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end));
  7833. }
  7834. template <typename T, size_t N>
  7835. internal::ParamGenerator<T> ValuesIn(const T (&array)[N]) {
  7836. return ValuesIn(array, array + N);
  7837. }
  7838. template <class Container>
  7839. internal::ParamGenerator<typename Container::value_type> ValuesIn(
  7840. const Container& container) {
  7841. return ValuesIn(container.begin(), container.end());
  7842. }
  7843. // Values() allows generating tests from explicitly specified list of
  7844. // parameters.
  7845. //
  7846. // Synopsis:
  7847. // Values(T v1, T v2, ..., T vN)
  7848. // - returns a generator producing sequences with elements v1, v2, ..., vN.
  7849. //
  7850. // For example, this instantiates tests from test suite BarTest each
  7851. // with values "one", "two", and "three":
  7852. //
  7853. // INSTANTIATE_TEST_SUITE_P(NumSequence,
  7854. // BarTest,
  7855. // Values("one", "two", "three"));
  7856. //
  7857. // This instantiates tests from test suite BazTest each with values 1, 2, 3.5.
  7858. // The exact type of values will depend on the type of parameter in BazTest.
  7859. //
  7860. // INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5));
  7861. //
  7862. //
  7863. template <typename... T>
  7864. internal::ValueArray<T...> Values(T... v) {
  7865. return internal::ValueArray<T...>(std::move(v)...);
  7866. }
  7867. // Bool() allows generating tests with parameters in a set of (false, true).
  7868. //
  7869. // Synopsis:
  7870. // Bool()
  7871. // - returns a generator producing sequences with elements {false, true}.
  7872. //
  7873. // It is useful when testing code that depends on Boolean flags. Combinations
  7874. // of multiple flags can be tested when several Bool()'s are combined using
  7875. // Combine() function.
  7876. //
  7877. // In the following example all tests in the test suite FlagDependentTest
  7878. // will be instantiated twice with parameters false and true.
  7879. //
  7880. // class FlagDependentTest : public testing::TestWithParam<bool> {
  7881. // virtual void SetUp() {
  7882. // external_flag = GetParam();
  7883. // }
  7884. // }
  7885. // INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());
  7886. //
  7887. inline internal::ParamGenerator<bool> Bool() {
  7888. return Values(false, true);
  7889. }
  7890. // Combine() allows the user to combine two or more sequences to produce
  7891. // values of a Cartesian product of those sequences' elements.
  7892. //
  7893. // Synopsis:
  7894. // Combine(gen1, gen2, ..., genN)
  7895. // - returns a generator producing sequences with elements coming from
  7896. // the Cartesian product of elements from the sequences generated by
  7897. // gen1, gen2, ..., genN. The sequence elements will have a type of
  7898. // std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
  7899. // of elements from sequences produces by gen1, gen2, ..., genN.
  7900. //
  7901. // Example:
  7902. //
  7903. // This will instantiate tests in test suite AnimalTest each one with
  7904. // the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
  7905. // tuple("dog", BLACK), and tuple("dog", WHITE):
  7906. //
  7907. // enum Color { BLACK, GRAY, WHITE };
  7908. // class AnimalTest
  7909. // : public testing::TestWithParam<std::tuple<const char*, Color> > {...};
  7910. //
  7911. // TEST_P(AnimalTest, AnimalLooksNice) {...}
  7912. //
  7913. // INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
  7914. // Combine(Values("cat", "dog"),
  7915. // Values(BLACK, WHITE)));
  7916. //
  7917. // This will instantiate tests in FlagDependentTest with all variations of two
  7918. // Boolean flags:
  7919. //
  7920. // class FlagDependentTest
  7921. // : public testing::TestWithParam<std::tuple<bool, bool> > {
  7922. // virtual void SetUp() {
  7923. // // Assigns external_flag_1 and external_flag_2 values from the tuple.
  7924. // std::tie(external_flag_1, external_flag_2) = GetParam();
  7925. // }
  7926. // };
  7927. //
  7928. // TEST_P(FlagDependentTest, TestFeature1) {
  7929. // // Test your code using external_flag_1 and external_flag_2 here.
  7930. // }
  7931. // INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest,
  7932. // Combine(Bool(), Bool()));
  7933. //
  7934. template <typename... Generator>
  7935. internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
  7936. return internal::CartesianProductHolder<Generator...>(g...);
  7937. }
  7938. #define TEST_P(test_suite_name, test_name) \
  7939. class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
  7940. : public test_suite_name { \
  7941. public: \
  7942. GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
  7943. void TestBody() override; \
  7944. \
  7945. private: \
  7946. static int AddToRegistry() { \
  7947. ::testing::UnitTest::GetInstance() \
  7948. ->parameterized_test_registry() \
  7949. .GetTestSuitePatternHolder<test_suite_name>( \
  7950. GTEST_STRINGIFY_(test_suite_name), \
  7951. ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
  7952. ->AddTestPattern( \
  7953. GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \
  7954. new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
  7955. test_suite_name, test_name)>(), \
  7956. ::testing::internal::CodeLocation(__FILE__, __LINE__)); \
  7957. return 0; \
  7958. } \
  7959. static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
  7960. GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
  7961. test_name)); \
  7962. }; \
  7963. int GTEST_TEST_CLASS_NAME_(test_suite_name, \
  7964. test_name)::gtest_registering_dummy_ = \
  7965. GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry(); \
  7966. void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
  7967. // The last argument to INSTANTIATE_TEST_SUITE_P allows the user to specify
  7968. // generator and an optional function or functor that generates custom test name
  7969. // suffixes based on the test parameters. Such a function or functor should
  7970. // accept one argument of type testing::TestParamInfo<class ParamType>, and
  7971. // return std::string.
  7972. //
  7973. // testing::PrintToStringParamName is a builtin test suffix generator that
  7974. // returns the value of testing::PrintToString(GetParam()).
  7975. //
  7976. // Note: test names must be non-empty, unique, and may only contain ASCII
  7977. // alphanumeric characters or underscore. Because PrintToString adds quotes
  7978. // to std::string and C strings, it won't work for these types.
  7979. #define GTEST_EXPAND_(arg) arg
  7980. #define GTEST_GET_FIRST_(first, ...) first
  7981. #define GTEST_GET_SECOND_(first, second, ...) second
  7982. #define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
  7983. static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
  7984. gtest_##prefix##test_suite_name##_EvalGenerator_() { \
  7985. return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
  7986. } \
  7987. static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
  7988. const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
  7989. if (::testing::internal::AlwaysFalse()) { \
  7990. ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
  7991. __VA_ARGS__, \
  7992. ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
  7993. DUMMY_PARAM_))); \
  7994. auto t = std::make_tuple(__VA_ARGS__); \
  7995. static_assert(std::tuple_size<decltype(t)>::value <= 2, \
  7996. "Too Many Args!"); \
  7997. } \
  7998. return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
  7999. __VA_ARGS__, \
  8000. ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
  8001. DUMMY_PARAM_))))(info); \
  8002. } \
  8003. static int gtest_##prefix##test_suite_name##_dummy_ \
  8004. GTEST_ATTRIBUTE_UNUSED_ = \
  8005. ::testing::UnitTest::GetInstance() \
  8006. ->parameterized_test_registry() \
  8007. .GetTestSuitePatternHolder<test_suite_name>( \
  8008. GTEST_STRINGIFY_(test_suite_name), \
  8009. ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
  8010. ->AddTestSuiteInstantiation( \
  8011. GTEST_STRINGIFY_(prefix), \
  8012. &gtest_##prefix##test_suite_name##_EvalGenerator_, \
  8013. &gtest_##prefix##test_suite_name##_EvalGenerateName_, \
  8014. __FILE__, __LINE__)
  8015. // Allow Marking a Parameterized test class as not needing to be instantiated.
  8016. #define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \
  8017. namespace gtest_do_not_use_outside_namespace_scope {} \
  8018. static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
  8019. GTEST_STRINGIFY_(T))
  8020. // Legacy API is deprecated but still available
  8021. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8022. #define INSTANTIATE_TEST_CASE_P \
  8023. static_assert(::testing::internal::InstantiateTestCase_P_IsDeprecated(), \
  8024. ""); \
  8025. INSTANTIATE_TEST_SUITE_P
  8026. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8027. } // namespace testing
  8028. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
  8029. // Copyright 2006, Google Inc.
  8030. // All rights reserved.
  8031. //
  8032. // Redistribution and use in source and binary forms, with or without
  8033. // modification, are permitted provided that the following conditions are
  8034. // met:
  8035. //
  8036. // * Redistributions of source code must retain the above copyright
  8037. // notice, this list of conditions and the following disclaimer.
  8038. // * Redistributions in binary form must reproduce the above
  8039. // copyright notice, this list of conditions and the following disclaimer
  8040. // in the documentation and/or other materials provided with the
  8041. // distribution.
  8042. // * Neither the name of Google Inc. nor the names of its
  8043. // contributors may be used to endorse or promote products derived from
  8044. // this software without specific prior written permission.
  8045. //
  8046. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8047. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8048. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8049. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8050. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8051. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8052. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8053. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8054. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8055. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8056. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8057. //
  8058. // Google C++ Testing and Mocking Framework definitions useful in production code.
  8059. // GOOGLETEST_CM0003 DO NOT DELETE
  8060. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
  8061. #define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
  8062. // When you need to test the private or protected members of a class,
  8063. // use the FRIEND_TEST macro to declare your tests as friends of the
  8064. // class. For example:
  8065. //
  8066. // class MyClass {
  8067. // private:
  8068. // void PrivateMethod();
  8069. // FRIEND_TEST(MyClassTest, PrivateMethodWorks);
  8070. // };
  8071. //
  8072. // class MyClassTest : public testing::Test {
  8073. // // ...
  8074. // };
  8075. //
  8076. // TEST_F(MyClassTest, PrivateMethodWorks) {
  8077. // // Can call MyClass::PrivateMethod() here.
  8078. // }
  8079. //
  8080. // Note: The test class must be in the same namespace as the class being tested.
  8081. // For example, putting MyClassTest in an anonymous namespace will not work.
  8082. #define FRIEND_TEST(test_case_name, test_name)\
  8083. friend class test_case_name##_##test_name##_Test
  8084. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
  8085. // Copyright 2008 Google Inc.
  8086. // All Rights Reserved.
  8087. //
  8088. // Redistribution and use in source and binary forms, with or without
  8089. // modification, are permitted provided that the following conditions are
  8090. // met:
  8091. //
  8092. // * Redistributions of source code must retain the above copyright
  8093. // notice, this list of conditions and the following disclaimer.
  8094. // * Redistributions in binary form must reproduce the above
  8095. // copyright notice, this list of conditions and the following disclaimer
  8096. // in the documentation and/or other materials provided with the
  8097. // distribution.
  8098. // * Neither the name of Google Inc. nor the names of its
  8099. // contributors may be used to endorse or promote products derived from
  8100. // this software without specific prior written permission.
  8101. //
  8102. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8103. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8104. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8105. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8106. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8107. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8108. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8109. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8110. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8111. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8112. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8113. // GOOGLETEST_CM0001 DO NOT DELETE
  8114. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
  8115. #define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
  8116. // This header implements typed tests and type-parameterized tests.
  8117. // Typed (aka type-driven) tests repeat the same test for types in a
  8118. // list. You must know which types you want to test with when writing
  8119. // typed tests. Here's how you do it:
  8120. #if 0
  8121. // First, define a fixture class template. It should be parameterized
  8122. // by a type. Remember to derive it from testing::Test.
  8123. template <typename T>
  8124. class FooTest : public testing::Test {
  8125. public:
  8126. ...
  8127. typedef std::list<T> List;
  8128. static T shared_;
  8129. T value_;
  8130. };
  8131. // Next, associate a list of types with the test suite, which will be
  8132. // repeated for each type in the list. The typedef is necessary for
  8133. // the macro to parse correctly.
  8134. typedef testing::Types<char, int, unsigned int> MyTypes;
  8135. TYPED_TEST_SUITE(FooTest, MyTypes);
  8136. // If the type list contains only one type, you can write that type
  8137. // directly without Types<...>:
  8138. // TYPED_TEST_SUITE(FooTest, int);
  8139. // Then, use TYPED_TEST() instead of TEST_F() to define as many typed
  8140. // tests for this test suite as you want.
  8141. TYPED_TEST(FooTest, DoesBlah) {
  8142. // Inside a test, refer to the special name TypeParam to get the type
  8143. // parameter. Since we are inside a derived class template, C++ requires
  8144. // us to visit the members of FooTest via 'this'.
  8145. TypeParam n = this->value_;
  8146. // To visit static members of the fixture, add the TestFixture::
  8147. // prefix.
  8148. n += TestFixture::shared_;
  8149. // To refer to typedefs in the fixture, add the "typename
  8150. // TestFixture::" prefix.
  8151. typename TestFixture::List values;
  8152. values.push_back(n);
  8153. ...
  8154. }
  8155. TYPED_TEST(FooTest, HasPropertyA) { ... }
  8156. // TYPED_TEST_SUITE takes an optional third argument which allows to specify a
  8157. // class that generates custom test name suffixes based on the type. This should
  8158. // be a class which has a static template function GetName(int index) returning
  8159. // a string for each type. The provided integer index equals the index of the
  8160. // type in the provided type list. In many cases the index can be ignored.
  8161. //
  8162. // For example:
  8163. // class MyTypeNames {
  8164. // public:
  8165. // template <typename T>
  8166. // static std::string GetName(int) {
  8167. // if (std::is_same<T, char>()) return "char";
  8168. // if (std::is_same<T, int>()) return "int";
  8169. // if (std::is_same<T, unsigned int>()) return "unsignedInt";
  8170. // }
  8171. // };
  8172. // TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames);
  8173. #endif // 0
  8174. // Type-parameterized tests are abstract test patterns parameterized
  8175. // by a type. Compared with typed tests, type-parameterized tests
  8176. // allow you to define the test pattern without knowing what the type
  8177. // parameters are. The defined pattern can be instantiated with
  8178. // different types any number of times, in any number of translation
  8179. // units.
  8180. //
  8181. // If you are designing an interface or concept, you can define a
  8182. // suite of type-parameterized tests to verify properties that any
  8183. // valid implementation of the interface/concept should have. Then,
  8184. // each implementation can easily instantiate the test suite to verify
  8185. // that it conforms to the requirements, without having to write
  8186. // similar tests repeatedly. Here's an example:
  8187. #if 0
  8188. // First, define a fixture class template. It should be parameterized
  8189. // by a type. Remember to derive it from testing::Test.
  8190. template <typename T>
  8191. class FooTest : public testing::Test {
  8192. ...
  8193. };
  8194. // Next, declare that you will define a type-parameterized test suite
  8195. // (the _P suffix is for "parameterized" or "pattern", whichever you
  8196. // prefer):
  8197. TYPED_TEST_SUITE_P(FooTest);
  8198. // Then, use TYPED_TEST_P() to define as many type-parameterized tests
  8199. // for this type-parameterized test suite as you want.
  8200. TYPED_TEST_P(FooTest, DoesBlah) {
  8201. // Inside a test, refer to TypeParam to get the type parameter.
  8202. TypeParam n = 0;
  8203. ...
  8204. }
  8205. TYPED_TEST_P(FooTest, HasPropertyA) { ... }
  8206. // Now the tricky part: you need to register all test patterns before
  8207. // you can instantiate them. The first argument of the macro is the
  8208. // test suite name; the rest are the names of the tests in this test
  8209. // case.
  8210. REGISTER_TYPED_TEST_SUITE_P(FooTest,
  8211. DoesBlah, HasPropertyA);
  8212. // Finally, you are free to instantiate the pattern with the types you
  8213. // want. If you put the above code in a header file, you can #include
  8214. // it in multiple C++ source files and instantiate it multiple times.
  8215. //
  8216. // To distinguish different instances of the pattern, the first
  8217. // argument to the INSTANTIATE_* macro is a prefix that will be added
  8218. // to the actual test suite name. Remember to pick unique prefixes for
  8219. // different instances.
  8220. typedef testing::Types<char, int, unsigned int> MyTypes;
  8221. INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
  8222. // If the type list contains only one type, you can write that type
  8223. // directly without Types<...>:
  8224. // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int);
  8225. //
  8226. // Similar to the optional argument of TYPED_TEST_SUITE above,
  8227. // INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to
  8228. // generate custom names.
  8229. // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames);
  8230. #endif // 0
  8231. // Implements typed tests.
  8232. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  8233. //
  8234. // Expands to the name of the typedef for the type parameters of the
  8235. // given test suite.
  8236. #define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_
  8237. // Expands to the name of the typedef for the NameGenerator, responsible for
  8238. // creating the suffixes of the name.
  8239. #define GTEST_NAME_GENERATOR_(TestSuiteName) \
  8240. gtest_type_params_##TestSuiteName##_NameGenerator
  8241. #define TYPED_TEST_SUITE(CaseName, Types, ...) \
  8242. typedef ::testing::internal::GenerateTypeList<Types>::type \
  8243. GTEST_TYPE_PARAMS_(CaseName); \
  8244. typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
  8245. GTEST_NAME_GENERATOR_(CaseName)
  8246. #define TYPED_TEST(CaseName, TestName) \
  8247. static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \
  8248. "test-name must not be empty"); \
  8249. template <typename gtest_TypeParam_> \
  8250. class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
  8251. : public CaseName<gtest_TypeParam_> { \
  8252. private: \
  8253. typedef CaseName<gtest_TypeParam_> TestFixture; \
  8254. typedef gtest_TypeParam_ TypeParam; \
  8255. void TestBody() override; \
  8256. }; \
  8257. static bool gtest_##CaseName##_##TestName##_registered_ \
  8258. GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \
  8259. CaseName, \
  8260. ::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \
  8261. TestName)>, \
  8262. GTEST_TYPE_PARAMS_( \
  8263. CaseName)>::Register("", \
  8264. ::testing::internal::CodeLocation( \
  8265. __FILE__, __LINE__), \
  8266. GTEST_STRINGIFY_(CaseName), \
  8267. GTEST_STRINGIFY_(TestName), 0, \
  8268. ::testing::internal::GenerateNames< \
  8269. GTEST_NAME_GENERATOR_(CaseName), \
  8270. GTEST_TYPE_PARAMS_(CaseName)>()); \
  8271. template <typename gtest_TypeParam_> \
  8272. void GTEST_TEST_CLASS_NAME_(CaseName, \
  8273. TestName)<gtest_TypeParam_>::TestBody()
  8274. // Legacy API is deprecated but still available
  8275. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8276. #define TYPED_TEST_CASE \
  8277. static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \
  8278. TYPED_TEST_SUITE
  8279. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8280. // Implements type-parameterized tests.
  8281. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  8282. //
  8283. // Expands to the namespace name that the type-parameterized tests for
  8284. // the given type-parameterized test suite are defined in. The exact
  8285. // name of the namespace is subject to change without notice.
  8286. #define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_
  8287. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  8288. //
  8289. // Expands to the name of the variable used to remember the names of
  8290. // the defined tests in the given test suite.
  8291. #define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \
  8292. gtest_typed_test_suite_p_state_##TestSuiteName##_
  8293. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.
  8294. //
  8295. // Expands to the name of the variable used to remember the names of
  8296. // the registered tests in the given test suite.
  8297. #define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \
  8298. gtest_registered_test_names_##TestSuiteName##_
  8299. // The variables defined in the type-parameterized test macros are
  8300. // static as typically these macros are used in a .h file that can be
  8301. // #included in multiple translation units linked together.
  8302. #define TYPED_TEST_SUITE_P(SuiteName) \
  8303. static ::testing::internal::TypedTestSuitePState \
  8304. GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName)
  8305. // Legacy API is deprecated but still available
  8306. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8307. #define TYPED_TEST_CASE_P \
  8308. static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \
  8309. TYPED_TEST_SUITE_P
  8310. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8311. #define TYPED_TEST_P(SuiteName, TestName) \
  8312. namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
  8313. template <typename gtest_TypeParam_> \
  8314. class TestName : public SuiteName<gtest_TypeParam_> { \
  8315. private: \
  8316. typedef SuiteName<gtest_TypeParam_> TestFixture; \
  8317. typedef gtest_TypeParam_ TypeParam; \
  8318. void TestBody() override; \
  8319. }; \
  8320. static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
  8321. GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
  8322. __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
  8323. GTEST_STRINGIFY_(TestName)); \
  8324. } \
  8325. template <typename gtest_TypeParam_> \
  8326. void GTEST_SUITE_NAMESPACE_( \
  8327. SuiteName)::TestName<gtest_TypeParam_>::TestBody()
  8328. // Note: this won't work correctly if the trailing arguments are macros.
  8329. #define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
  8330. namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
  8331. typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
  8332. } \
  8333. static const char* const GTEST_REGISTERED_TEST_NAMES_( \
  8334. SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
  8335. GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
  8336. GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__)
  8337. // Legacy API is deprecated but still available
  8338. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8339. #define REGISTER_TYPED_TEST_CASE_P \
  8340. static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \
  8341. ""); \
  8342. REGISTER_TYPED_TEST_SUITE_P
  8343. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8344. #define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \
  8345. static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \
  8346. "test-suit-prefix must not be empty"); \
  8347. static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \
  8348. ::testing::internal::TypeParameterizedTestSuite< \
  8349. SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
  8350. ::testing::internal::GenerateTypeList<Types>::type>:: \
  8351. Register(GTEST_STRINGIFY_(Prefix), \
  8352. ::testing::internal::CodeLocation(__FILE__, __LINE__), \
  8353. &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \
  8354. GTEST_STRINGIFY_(SuiteName), \
  8355. GTEST_REGISTERED_TEST_NAMES_(SuiteName), \
  8356. ::testing::internal::GenerateNames< \
  8357. ::testing::internal::NameGeneratorSelector< \
  8358. __VA_ARGS__>::type, \
  8359. ::testing::internal::GenerateTypeList<Types>::type>())
  8360. // Legacy API is deprecated but still available
  8361. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8362. #define INSTANTIATE_TYPED_TEST_CASE_P \
  8363. static_assert( \
  8364. ::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \
  8365. INSTANTIATE_TYPED_TEST_SUITE_P
  8366. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8367. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
  8368. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  8369. /* class A needs to have dll-interface to be used by clients of class B */)
  8370. namespace testing {
  8371. // Silence C4100 (unreferenced formal parameter) and 4805
  8372. // unsafe mix of type 'const int' and type 'const bool'
  8373. #ifdef _MSC_VER
  8374. # pragma warning(push)
  8375. # pragma warning(disable:4805)
  8376. # pragma warning(disable:4100)
  8377. #endif
  8378. // Declares the flags.
  8379. // This flag temporary enables the disabled tests.
  8380. GTEST_DECLARE_bool_(also_run_disabled_tests);
  8381. // This flag brings the debugger on an assertion failure.
  8382. GTEST_DECLARE_bool_(break_on_failure);
  8383. // This flag controls whether Google Test catches all test-thrown exceptions
  8384. // and logs them as failures.
  8385. GTEST_DECLARE_bool_(catch_exceptions);
  8386. // This flag enables using colors in terminal output. Available values are
  8387. // "yes" to enable colors, "no" (disable colors), or "auto" (the default)
  8388. // to let Google Test decide.
  8389. GTEST_DECLARE_string_(color);
  8390. // This flag controls whether the test runner should continue execution past
  8391. // first failure.
  8392. GTEST_DECLARE_bool_(fail_fast);
  8393. // This flag sets up the filter to select by name using a glob pattern
  8394. // the tests to run. If the filter is not given all tests are executed.
  8395. GTEST_DECLARE_string_(filter);
  8396. // This flag controls whether Google Test installs a signal handler that dumps
  8397. // debugging information when fatal signals are raised.
  8398. GTEST_DECLARE_bool_(install_failure_signal_handler);
  8399. // This flag causes the Google Test to list tests. None of the tests listed
  8400. // are actually run if the flag is provided.
  8401. GTEST_DECLARE_bool_(list_tests);
  8402. // This flag controls whether Google Test emits a detailed XML report to a file
  8403. // in addition to its normal textual output.
  8404. GTEST_DECLARE_string_(output);
  8405. // This flags control whether Google Test prints only test failures.
  8406. GTEST_DECLARE_bool_(brief);
  8407. // This flags control whether Google Test prints the elapsed time for each
  8408. // test.
  8409. GTEST_DECLARE_bool_(print_time);
  8410. // This flags control whether Google Test prints UTF8 characters as text.
  8411. GTEST_DECLARE_bool_(print_utf8);
  8412. // This flag specifies the random number seed.
  8413. GTEST_DECLARE_int32_(random_seed);
  8414. // This flag sets how many times the tests are repeated. The default value
  8415. // is 1. If the value is -1 the tests are repeating forever.
  8416. GTEST_DECLARE_int32_(repeat);
  8417. // This flag controls whether Google Test includes Google Test internal
  8418. // stack frames in failure stack traces.
  8419. GTEST_DECLARE_bool_(show_internal_stack_frames);
  8420. // When this flag is specified, tests' order is randomized on every iteration.
  8421. GTEST_DECLARE_bool_(shuffle);
  8422. // This flag specifies the maximum number of stack frames to be
  8423. // printed in a failure message.
  8424. GTEST_DECLARE_int32_(stack_trace_depth);
  8425. // When this flag is specified, a failed assertion will throw an
  8426. // exception if exceptions are enabled, or exit the program with a
  8427. // non-zero code otherwise. For use with an external test framework.
  8428. GTEST_DECLARE_bool_(throw_on_failure);
  8429. // When this flag is set with a "host:port" string, on supported
  8430. // platforms test results are streamed to the specified port on
  8431. // the specified host machine.
  8432. GTEST_DECLARE_string_(stream_result_to);
  8433. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  8434. GTEST_DECLARE_string_(flagfile);
  8435. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  8436. // The upper limit for valid stack trace depths.
  8437. const int kMaxStackTraceDepth = 100;
  8438. namespace internal {
  8439. class AssertHelper;
  8440. class DefaultGlobalTestPartResultReporter;
  8441. class ExecDeathTest;
  8442. class NoExecDeathTest;
  8443. class FinalSuccessChecker;
  8444. class GTestFlagSaver;
  8445. class StreamingListenerTest;
  8446. class TestResultAccessor;
  8447. class TestEventListenersAccessor;
  8448. class TestEventRepeater;
  8449. class UnitTestRecordPropertyTestHelper;
  8450. class WindowsDeathTest;
  8451. class FuchsiaDeathTest;
  8452. class UnitTestImpl* GetUnitTestImpl();
  8453. void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  8454. const std::string& message);
  8455. std::set<std::string>* GetIgnoredParameterizedTestSuites();
  8456. } // namespace internal
  8457. // The friend relationship of some of these classes is cyclic.
  8458. // If we don't forward declare them the compiler might confuse the classes
  8459. // in friendship clauses with same named classes on the scope.
  8460. class Test;
  8461. class TestSuite;
  8462. // Old API is still available but deprecated
  8463. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8464. using TestCase = TestSuite;
  8465. #endif
  8466. class TestInfo;
  8467. class UnitTest;
  8468. // A class for indicating whether an assertion was successful. When
  8469. // the assertion wasn't successful, the AssertionResult object
  8470. // remembers a non-empty message that describes how it failed.
  8471. //
  8472. // To create an instance of this class, use one of the factory functions
  8473. // (AssertionSuccess() and AssertionFailure()).
  8474. //
  8475. // This class is useful for two purposes:
  8476. // 1. Defining predicate functions to be used with Boolean test assertions
  8477. // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
  8478. // 2. Defining predicate-format functions to be
  8479. // used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
  8480. //
  8481. // For example, if you define IsEven predicate:
  8482. //
  8483. // testing::AssertionResult IsEven(int n) {
  8484. // if ((n % 2) == 0)
  8485. // return testing::AssertionSuccess();
  8486. // else
  8487. // return testing::AssertionFailure() << n << " is odd";
  8488. // }
  8489. //
  8490. // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
  8491. // will print the message
  8492. //
  8493. // Value of: IsEven(Fib(5))
  8494. // Actual: false (5 is odd)
  8495. // Expected: true
  8496. //
  8497. // instead of a more opaque
  8498. //
  8499. // Value of: IsEven(Fib(5))
  8500. // Actual: false
  8501. // Expected: true
  8502. //
  8503. // in case IsEven is a simple Boolean predicate.
  8504. //
  8505. // If you expect your predicate to be reused and want to support informative
  8506. // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
  8507. // about half as often as positive ones in our tests), supply messages for
  8508. // both success and failure cases:
  8509. //
  8510. // testing::AssertionResult IsEven(int n) {
  8511. // if ((n % 2) == 0)
  8512. // return testing::AssertionSuccess() << n << " is even";
  8513. // else
  8514. // return testing::AssertionFailure() << n << " is odd";
  8515. // }
  8516. //
  8517. // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
  8518. //
  8519. // Value of: IsEven(Fib(6))
  8520. // Actual: true (8 is even)
  8521. // Expected: false
  8522. //
  8523. // NB: Predicates that support negative Boolean assertions have reduced
  8524. // performance in positive ones so be careful not to use them in tests
  8525. // that have lots (tens of thousands) of positive Boolean assertions.
  8526. //
  8527. // To use this class with EXPECT_PRED_FORMAT assertions such as:
  8528. //
  8529. // // Verifies that Foo() returns an even number.
  8530. // EXPECT_PRED_FORMAT1(IsEven, Foo());
  8531. //
  8532. // you need to define:
  8533. //
  8534. // testing::AssertionResult IsEven(const char* expr, int n) {
  8535. // if ((n % 2) == 0)
  8536. // return testing::AssertionSuccess();
  8537. // else
  8538. // return testing::AssertionFailure()
  8539. // << "Expected: " << expr << " is even\n Actual: it's " << n;
  8540. // }
  8541. //
  8542. // If Foo() returns 5, you will see the following message:
  8543. //
  8544. // Expected: Foo() is even
  8545. // Actual: it's 5
  8546. //
  8547. class GTEST_API_ AssertionResult {
  8548. public:
  8549. // Copy constructor.
  8550. // Used in EXPECT_TRUE/FALSE(assertion_result).
  8551. AssertionResult(const AssertionResult& other);
  8552. // C4800 is a level 3 warning in Visual Studio 2015 and earlier.
  8553. // This warning is not emitted in Visual Studio 2017.
  8554. // This warning is off by default starting in Visual Studio 2019 but can be
  8555. // enabled with command-line options.
  8556. #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
  8557. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
  8558. #endif
  8559. // Used in the EXPECT_TRUE/FALSE(bool_expression).
  8560. //
  8561. // T must be contextually convertible to bool.
  8562. //
  8563. // The second parameter prevents this overload from being considered if
  8564. // the argument is implicitly convertible to AssertionResult. In that case
  8565. // we want AssertionResult's copy constructor to be used.
  8566. template <typename T>
  8567. explicit AssertionResult(
  8568. const T& success,
  8569. typename std::enable_if<
  8570. !std::is_convertible<T, AssertionResult>::value>::type*
  8571. /*enabler*/
  8572. = nullptr)
  8573. : success_(success) {}
  8574. #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
  8575. GTEST_DISABLE_MSC_WARNINGS_POP_()
  8576. #endif
  8577. // Assignment operator.
  8578. AssertionResult& operator=(AssertionResult other) {
  8579. swap(other);
  8580. return *this;
  8581. }
  8582. // Returns true if and only if the assertion succeeded.
  8583. operator bool() const { return success_; } // NOLINT
  8584. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  8585. AssertionResult operator!() const;
  8586. // Returns the text streamed into this AssertionResult. Test assertions
  8587. // use it when they fail (i.e., the predicate's outcome doesn't match the
  8588. // assertion's expectation). When nothing has been streamed into the
  8589. // object, returns an empty string.
  8590. const char* message() const {
  8591. return message_.get() != nullptr ? message_->c_str() : "";
  8592. }
  8593. // Deprecated; please use message() instead.
  8594. const char* failure_message() const { return message(); }
  8595. // Streams a custom failure message into this object.
  8596. template <typename T> AssertionResult& operator<<(const T& value) {
  8597. AppendMessage(Message() << value);
  8598. return *this;
  8599. }
  8600. // Allows streaming basic output manipulators such as endl or flush into
  8601. // this object.
  8602. AssertionResult& operator<<(
  8603. ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
  8604. AppendMessage(Message() << basic_manipulator);
  8605. return *this;
  8606. }
  8607. private:
  8608. // Appends the contents of message to message_.
  8609. void AppendMessage(const Message& a_message) {
  8610. if (message_.get() == nullptr) message_.reset(new ::std::string);
  8611. message_->append(a_message.GetString().c_str());
  8612. }
  8613. // Swap the contents of this AssertionResult with other.
  8614. void swap(AssertionResult& other);
  8615. // Stores result of the assertion predicate.
  8616. bool success_;
  8617. // Stores the message describing the condition in case the expectation
  8618. // construct is not satisfied with the predicate's outcome.
  8619. // Referenced via a pointer to avoid taking too much stack frame space
  8620. // with test assertions.
  8621. std::unique_ptr< ::std::string> message_;
  8622. };
  8623. // Makes a successful assertion result.
  8624. GTEST_API_ AssertionResult AssertionSuccess();
  8625. // Makes a failed assertion result.
  8626. GTEST_API_ AssertionResult AssertionFailure();
  8627. // Makes a failed assertion result with the given failure message.
  8628. // Deprecated; use AssertionFailure() << msg.
  8629. GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
  8630. } // namespace testing
  8631. // Includes the auto-generated header that implements a family of generic
  8632. // predicate assertion macros. This include comes late because it relies on
  8633. // APIs declared above.
  8634. // Copyright 2006, Google Inc.
  8635. // All rights reserved.
  8636. //
  8637. // Redistribution and use in source and binary forms, with or without
  8638. // modification, are permitted provided that the following conditions are
  8639. // met:
  8640. //
  8641. // * Redistributions of source code must retain the above copyright
  8642. // notice, this list of conditions and the following disclaimer.
  8643. // * Redistributions in binary form must reproduce the above
  8644. // copyright notice, this list of conditions and the following disclaimer
  8645. // in the documentation and/or other materials provided with the
  8646. // distribution.
  8647. // * Neither the name of Google Inc. nor the names of its
  8648. // contributors may be used to endorse or promote products derived from
  8649. // this software without specific prior written permission.
  8650. //
  8651. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8652. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8653. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8654. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8655. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8656. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8657. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8658. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8659. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8660. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8661. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8662. // This file is AUTOMATICALLY GENERATED on 01/02/2019 by command
  8663. // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND!
  8664. //
  8665. // Implements a family of generic predicate assertion macros.
  8666. // GOOGLETEST_CM0001 DO NOT DELETE
  8667. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
  8668. #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
  8669. namespace testing {
  8670. // This header implements a family of generic predicate assertion
  8671. // macros:
  8672. //
  8673. // ASSERT_PRED_FORMAT1(pred_format, v1)
  8674. // ASSERT_PRED_FORMAT2(pred_format, v1, v2)
  8675. // ...
  8676. //
  8677. // where pred_format is a function or functor that takes n (in the
  8678. // case of ASSERT_PRED_FORMATn) values and their source expression
  8679. // text, and returns a testing::AssertionResult. See the definition
  8680. // of ASSERT_EQ in gtest.h for an example.
  8681. //
  8682. // If you don't care about formatting, you can use the more
  8683. // restrictive version:
  8684. //
  8685. // ASSERT_PRED1(pred, v1)
  8686. // ASSERT_PRED2(pred, v1, v2)
  8687. // ...
  8688. //
  8689. // where pred is an n-ary function or functor that returns bool,
  8690. // and the values v1, v2, ..., must support the << operator for
  8691. // streaming to std::ostream.
  8692. //
  8693. // We also define the EXPECT_* variations.
  8694. //
  8695. // For now we only support predicates whose arity is at most 5.
  8696. // Please email googletestframework@googlegroups.com if you need
  8697. // support for higher arities.
  8698. // GTEST_ASSERT_ is the basic statement to which all of the assertions
  8699. // in this file reduce. Don't use this in your code.
  8700. #define GTEST_ASSERT_(expression, on_failure) \
  8701. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  8702. if (const ::testing::AssertionResult gtest_ar = (expression)) \
  8703. ; \
  8704. else \
  8705. on_failure(gtest_ar.failure_message())
  8706. // Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
  8707. // this in your code.
  8708. template <typename Pred,
  8709. typename T1>
  8710. AssertionResult AssertPred1Helper(const char* pred_text,
  8711. const char* e1,
  8712. Pred pred,
  8713. const T1& v1) {
  8714. if (pred(v1)) return AssertionSuccess();
  8715. return AssertionFailure()
  8716. << pred_text << "(" << e1 << ") evaluates to false, where"
  8717. << "\n"
  8718. << e1 << " evaluates to " << ::testing::PrintToString(v1);
  8719. }
  8720. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
  8721. // Don't use this in your code.
  8722. #define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\
  8723. GTEST_ASSERT_(pred_format(#v1, v1), \
  8724. on_failure)
  8725. // Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
  8726. // this in your code.
  8727. #define GTEST_PRED1_(pred, v1, on_failure)\
  8728. GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
  8729. #v1, \
  8730. pred, \
  8731. v1), on_failure)
  8732. // Unary predicate assertion macros.
  8733. #define EXPECT_PRED_FORMAT1(pred_format, v1) \
  8734. GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
  8735. #define EXPECT_PRED1(pred, v1) \
  8736. GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
  8737. #define ASSERT_PRED_FORMAT1(pred_format, v1) \
  8738. GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
  8739. #define ASSERT_PRED1(pred, v1) \
  8740. GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
  8741. // Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
  8742. // this in your code.
  8743. template <typename Pred,
  8744. typename T1,
  8745. typename T2>
  8746. AssertionResult AssertPred2Helper(const char* pred_text,
  8747. const char* e1,
  8748. const char* e2,
  8749. Pred pred,
  8750. const T1& v1,
  8751. const T2& v2) {
  8752. if (pred(v1, v2)) return AssertionSuccess();
  8753. return AssertionFailure()
  8754. << pred_text << "(" << e1 << ", " << e2
  8755. << ") evaluates to false, where"
  8756. << "\n"
  8757. << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
  8758. << e2 << " evaluates to " << ::testing::PrintToString(v2);
  8759. }
  8760. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
  8761. // Don't use this in your code.
  8762. #define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\
  8763. GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \
  8764. on_failure)
  8765. // Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
  8766. // this in your code.
  8767. #define GTEST_PRED2_(pred, v1, v2, on_failure)\
  8768. GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
  8769. #v1, \
  8770. #v2, \
  8771. pred, \
  8772. v1, \
  8773. v2), on_failure)
  8774. // Binary predicate assertion macros.
  8775. #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
  8776. GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_)
  8777. #define EXPECT_PRED2(pred, v1, v2) \
  8778. GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_)
  8779. #define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \
  8780. GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_)
  8781. #define ASSERT_PRED2(pred, v1, v2) \
  8782. GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
  8783. // Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
  8784. // this in your code.
  8785. template <typename Pred,
  8786. typename T1,
  8787. typename T2,
  8788. typename T3>
  8789. AssertionResult AssertPred3Helper(const char* pred_text,
  8790. const char* e1,
  8791. const char* e2,
  8792. const char* e3,
  8793. Pred pred,
  8794. const T1& v1,
  8795. const T2& v2,
  8796. const T3& v3) {
  8797. if (pred(v1, v2, v3)) return AssertionSuccess();
  8798. return AssertionFailure()
  8799. << pred_text << "(" << e1 << ", " << e2 << ", " << e3
  8800. << ") evaluates to false, where"
  8801. << "\n"
  8802. << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
  8803. << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
  8804. << e3 << " evaluates to " << ::testing::PrintToString(v3);
  8805. }
  8806. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
  8807. // Don't use this in your code.
  8808. #define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\
  8809. GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \
  8810. on_failure)
  8811. // Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
  8812. // this in your code.
  8813. #define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\
  8814. GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
  8815. #v1, \
  8816. #v2, \
  8817. #v3, \
  8818. pred, \
  8819. v1, \
  8820. v2, \
  8821. v3), on_failure)
  8822. // Ternary predicate assertion macros.
  8823. #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
  8824. GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
  8825. #define EXPECT_PRED3(pred, v1, v2, v3) \
  8826. GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
  8827. #define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \
  8828. GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_)
  8829. #define ASSERT_PRED3(pred, v1, v2, v3) \
  8830. GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
  8831. // Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
  8832. // this in your code.
  8833. template <typename Pred,
  8834. typename T1,
  8835. typename T2,
  8836. typename T3,
  8837. typename T4>
  8838. AssertionResult AssertPred4Helper(const char* pred_text,
  8839. const char* e1,
  8840. const char* e2,
  8841. const char* e3,
  8842. const char* e4,
  8843. Pred pred,
  8844. const T1& v1,
  8845. const T2& v2,
  8846. const T3& v3,
  8847. const T4& v4) {
  8848. if (pred(v1, v2, v3, v4)) return AssertionSuccess();
  8849. return AssertionFailure()
  8850. << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
  8851. << ") evaluates to false, where"
  8852. << "\n"
  8853. << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
  8854. << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
  8855. << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
  8856. << e4 << " evaluates to " << ::testing::PrintToString(v4);
  8857. }
  8858. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
  8859. // Don't use this in your code.
  8860. #define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\
  8861. GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \
  8862. on_failure)
  8863. // Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
  8864. // this in your code.
  8865. #define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\
  8866. GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
  8867. #v1, \
  8868. #v2, \
  8869. #v3, \
  8870. #v4, \
  8871. pred, \
  8872. v1, \
  8873. v2, \
  8874. v3, \
  8875. v4), on_failure)
  8876. // 4-ary predicate assertion macros.
  8877. #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
  8878. GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
  8879. #define EXPECT_PRED4(pred, v1, v2, v3, v4) \
  8880. GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
  8881. #define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
  8882. GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
  8883. #define ASSERT_PRED4(pred, v1, v2, v3, v4) \
  8884. GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
  8885. // Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
  8886. // this in your code.
  8887. template <typename Pred,
  8888. typename T1,
  8889. typename T2,
  8890. typename T3,
  8891. typename T4,
  8892. typename T5>
  8893. AssertionResult AssertPred5Helper(const char* pred_text,
  8894. const char* e1,
  8895. const char* e2,
  8896. const char* e3,
  8897. const char* e4,
  8898. const char* e5,
  8899. Pred pred,
  8900. const T1& v1,
  8901. const T2& v2,
  8902. const T3& v3,
  8903. const T4& v4,
  8904. const T5& v5) {
  8905. if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
  8906. return AssertionFailure()
  8907. << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
  8908. << ", " << e5 << ") evaluates to false, where"
  8909. << "\n"
  8910. << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
  8911. << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
  8912. << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
  8913. << e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n"
  8914. << e5 << " evaluates to " << ::testing::PrintToString(v5);
  8915. }
  8916. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
  8917. // Don't use this in your code.
  8918. #define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\
  8919. GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \
  8920. on_failure)
  8921. // Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
  8922. // this in your code.
  8923. #define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\
  8924. GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
  8925. #v1, \
  8926. #v2, \
  8927. #v3, \
  8928. #v4, \
  8929. #v5, \
  8930. pred, \
  8931. v1, \
  8932. v2, \
  8933. v3, \
  8934. v4, \
  8935. v5), on_failure)
  8936. // 5-ary predicate assertion macros.
  8937. #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
  8938. GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
  8939. #define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \
  8940. GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
  8941. #define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
  8942. GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
  8943. #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
  8944. GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
  8945. } // namespace testing
  8946. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
  8947. namespace testing {
  8948. // The abstract class that all tests inherit from.
  8949. //
  8950. // In Google Test, a unit test program contains one or many TestSuites, and
  8951. // each TestSuite contains one or many Tests.
  8952. //
  8953. // When you define a test using the TEST macro, you don't need to
  8954. // explicitly derive from Test - the TEST macro automatically does
  8955. // this for you.
  8956. //
  8957. // The only time you derive from Test is when defining a test fixture
  8958. // to be used in a TEST_F. For example:
  8959. //
  8960. // class FooTest : public testing::Test {
  8961. // protected:
  8962. // void SetUp() override { ... }
  8963. // void TearDown() override { ... }
  8964. // ...
  8965. // };
  8966. //
  8967. // TEST_F(FooTest, Bar) { ... }
  8968. // TEST_F(FooTest, Baz) { ... }
  8969. //
  8970. // Test is not copyable.
  8971. class GTEST_API_ Test {
  8972. public:
  8973. friend class TestInfo;
  8974. // The d'tor is virtual as we intend to inherit from Test.
  8975. virtual ~Test();
  8976. // Sets up the stuff shared by all tests in this test suite.
  8977. //
  8978. // Google Test will call Foo::SetUpTestSuite() before running the first
  8979. // test in test suite Foo. Hence a sub-class can define its own
  8980. // SetUpTestSuite() method to shadow the one defined in the super
  8981. // class.
  8982. static void SetUpTestSuite() {}
  8983. // Tears down the stuff shared by all tests in this test suite.
  8984. //
  8985. // Google Test will call Foo::TearDownTestSuite() after running the last
  8986. // test in test suite Foo. Hence a sub-class can define its own
  8987. // TearDownTestSuite() method to shadow the one defined in the super
  8988. // class.
  8989. static void TearDownTestSuite() {}
  8990. // Legacy API is deprecated but still available. Use SetUpTestSuite and
  8991. // TearDownTestSuite instead.
  8992. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8993. static void TearDownTestCase() {}
  8994. static void SetUpTestCase() {}
  8995. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  8996. // Returns true if and only if the current test has a fatal failure.
  8997. static bool HasFatalFailure();
  8998. // Returns true if and only if the current test has a non-fatal failure.
  8999. static bool HasNonfatalFailure();
  9000. // Returns true if and only if the current test was skipped.
  9001. static bool IsSkipped();
  9002. // Returns true if and only if the current test has a (either fatal or
  9003. // non-fatal) failure.
  9004. static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
  9005. // Logs a property for the current test, test suite, or for the entire
  9006. // invocation of the test program when used outside of the context of a
  9007. // test suite. Only the last value for a given key is remembered. These
  9008. // are public static so they can be called from utility functions that are
  9009. // not members of the test fixture. Calls to RecordProperty made during
  9010. // lifespan of the test (from the moment its constructor starts to the
  9011. // moment its destructor finishes) will be output in XML as attributes of
  9012. // the <testcase> element. Properties recorded from fixture's
  9013. // SetUpTestSuite or TearDownTestSuite are logged as attributes of the
  9014. // corresponding <testsuite> element. Calls to RecordProperty made in the
  9015. // global context (before or after invocation of RUN_ALL_TESTS and from
  9016. // SetUp/TearDown method of Environment objects registered with Google
  9017. // Test) will be output as attributes of the <testsuites> element.
  9018. static void RecordProperty(const std::string& key, const std::string& value);
  9019. static void RecordProperty(const std::string& key, int value);
  9020. protected:
  9021. // Creates a Test object.
  9022. Test();
  9023. // Sets up the test fixture.
  9024. virtual void SetUp();
  9025. // Tears down the test fixture.
  9026. virtual void TearDown();
  9027. private:
  9028. // Returns true if and only if the current test has the same fixture class
  9029. // as the first test in the current test suite.
  9030. static bool HasSameFixtureClass();
  9031. // Runs the test after the test fixture has been set up.
  9032. //
  9033. // A sub-class must implement this to define the test logic.
  9034. //
  9035. // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
  9036. // Instead, use the TEST or TEST_F macro.
  9037. virtual void TestBody() = 0;
  9038. // Sets up, executes, and tears down the test.
  9039. void Run();
  9040. // Deletes self. We deliberately pick an unusual name for this
  9041. // internal method to avoid clashing with names used in user TESTs.
  9042. void DeleteSelf_() { delete this; }
  9043. const std::unique_ptr<GTEST_FLAG_SAVER_> gtest_flag_saver_;
  9044. // Often a user misspells SetUp() as Setup() and spends a long time
  9045. // wondering why it is never called by Google Test. The declaration of
  9046. // the following method is solely for catching such an error at
  9047. // compile time:
  9048. //
  9049. // - The return type is deliberately chosen to be not void, so it
  9050. // will be a conflict if void Setup() is declared in the user's
  9051. // test fixture.
  9052. //
  9053. // - This method is private, so it will be another compiler error
  9054. // if the method is called from the user's test fixture.
  9055. //
  9056. // DO NOT OVERRIDE THIS FUNCTION.
  9057. //
  9058. // If you see an error about overriding the following function or
  9059. // about it being private, you have mis-spelled SetUp() as Setup().
  9060. struct Setup_should_be_spelled_SetUp {};
  9061. virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
  9062. // We disallow copying Tests.
  9063. GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
  9064. };
  9065. typedef internal::TimeInMillis TimeInMillis;
  9066. // A copyable object representing a user specified test property which can be
  9067. // output as a key/value string pair.
  9068. //
  9069. // Don't inherit from TestProperty as its destructor is not virtual.
  9070. class TestProperty {
  9071. public:
  9072. // C'tor. TestProperty does NOT have a default constructor.
  9073. // Always use this constructor (with parameters) to create a
  9074. // TestProperty object.
  9075. TestProperty(const std::string& a_key, const std::string& a_value) :
  9076. key_(a_key), value_(a_value) {
  9077. }
  9078. // Gets the user supplied key.
  9079. const char* key() const {
  9080. return key_.c_str();
  9081. }
  9082. // Gets the user supplied value.
  9083. const char* value() const {
  9084. return value_.c_str();
  9085. }
  9086. // Sets a new value, overriding the one supplied in the constructor.
  9087. void SetValue(const std::string& new_value) {
  9088. value_ = new_value;
  9089. }
  9090. private:
  9091. // The key supplied by the user.
  9092. std::string key_;
  9093. // The value supplied by the user.
  9094. std::string value_;
  9095. };
  9096. // The result of a single Test. This includes a list of
  9097. // TestPartResults, a list of TestProperties, a count of how many
  9098. // death tests there are in the Test, and how much time it took to run
  9099. // the Test.
  9100. //
  9101. // TestResult is not copyable.
  9102. class GTEST_API_ TestResult {
  9103. public:
  9104. // Creates an empty TestResult.
  9105. TestResult();
  9106. // D'tor. Do not inherit from TestResult.
  9107. ~TestResult();
  9108. // Gets the number of all test parts. This is the sum of the number
  9109. // of successful test parts and the number of failed test parts.
  9110. int total_part_count() const;
  9111. // Returns the number of the test properties.
  9112. int test_property_count() const;
  9113. // Returns true if and only if the test passed (i.e. no test part failed).
  9114. bool Passed() const { return !Skipped() && !Failed(); }
  9115. // Returns true if and only if the test was skipped.
  9116. bool Skipped() const;
  9117. // Returns true if and only if the test failed.
  9118. bool Failed() const;
  9119. // Returns true if and only if the test fatally failed.
  9120. bool HasFatalFailure() const;
  9121. // Returns true if and only if the test has a non-fatal failure.
  9122. bool HasNonfatalFailure() const;
  9123. // Returns the elapsed time, in milliseconds.
  9124. TimeInMillis elapsed_time() const { return elapsed_time_; }
  9125. // Gets the time of the test case start, in ms from the start of the
  9126. // UNIX epoch.
  9127. TimeInMillis start_timestamp() const { return start_timestamp_; }
  9128. // Returns the i-th test part result among all the results. i can range from 0
  9129. // to total_part_count() - 1. If i is not in that range, aborts the program.
  9130. const TestPartResult& GetTestPartResult(int i) const;
  9131. // Returns the i-th test property. i can range from 0 to
  9132. // test_property_count() - 1. If i is not in that range, aborts the
  9133. // program.
  9134. const TestProperty& GetTestProperty(int i) const;
  9135. private:
  9136. friend class TestInfo;
  9137. friend class TestSuite;
  9138. friend class UnitTest;
  9139. friend class internal::DefaultGlobalTestPartResultReporter;
  9140. friend class internal::ExecDeathTest;
  9141. friend class internal::TestResultAccessor;
  9142. friend class internal::UnitTestImpl;
  9143. friend class internal::WindowsDeathTest;
  9144. friend class internal::FuchsiaDeathTest;
  9145. // Gets the vector of TestPartResults.
  9146. const std::vector<TestPartResult>& test_part_results() const {
  9147. return test_part_results_;
  9148. }
  9149. // Gets the vector of TestProperties.
  9150. const std::vector<TestProperty>& test_properties() const {
  9151. return test_properties_;
  9152. }
  9153. // Sets the start time.
  9154. void set_start_timestamp(TimeInMillis start) { start_timestamp_ = start; }
  9155. // Sets the elapsed time.
  9156. void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
  9157. // Adds a test property to the list. The property is validated and may add
  9158. // a non-fatal failure if invalid (e.g., if it conflicts with reserved
  9159. // key names). If a property is already recorded for the same key, the
  9160. // value will be updated, rather than storing multiple values for the same
  9161. // key. xml_element specifies the element for which the property is being
  9162. // recorded and is used for validation.
  9163. void RecordProperty(const std::string& xml_element,
  9164. const TestProperty& test_property);
  9165. // Adds a failure if the key is a reserved attribute of Google Test
  9166. // testsuite tags. Returns true if the property is valid.
  9167. // FIXME: Validate attribute names are legal and human readable.
  9168. static bool ValidateTestProperty(const std::string& xml_element,
  9169. const TestProperty& test_property);
  9170. // Adds a test part result to the list.
  9171. void AddTestPartResult(const TestPartResult& test_part_result);
  9172. // Returns the death test count.
  9173. int death_test_count() const { return death_test_count_; }
  9174. // Increments the death test count, returning the new count.
  9175. int increment_death_test_count() { return ++death_test_count_; }
  9176. // Clears the test part results.
  9177. void ClearTestPartResults();
  9178. // Clears the object.
  9179. void Clear();
  9180. // Protects mutable state of the property vector and of owned
  9181. // properties, whose values may be updated.
  9182. internal::Mutex test_properties_mutex_;
  9183. // The vector of TestPartResults
  9184. std::vector<TestPartResult> test_part_results_;
  9185. // The vector of TestProperties
  9186. std::vector<TestProperty> test_properties_;
  9187. // Running count of death tests.
  9188. int death_test_count_;
  9189. // The start time, in milliseconds since UNIX Epoch.
  9190. TimeInMillis start_timestamp_;
  9191. // The elapsed time, in milliseconds.
  9192. TimeInMillis elapsed_time_;
  9193. // We disallow copying TestResult.
  9194. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
  9195. }; // class TestResult
  9196. // A TestInfo object stores the following information about a test:
  9197. //
  9198. // Test suite name
  9199. // Test name
  9200. // Whether the test should be run
  9201. // A function pointer that creates the test object when invoked
  9202. // Test result
  9203. //
  9204. // The constructor of TestInfo registers itself with the UnitTest
  9205. // singleton such that the RUN_ALL_TESTS() macro knows which tests to
  9206. // run.
  9207. class GTEST_API_ TestInfo {
  9208. public:
  9209. // Destructs a TestInfo object. This function is not virtual, so
  9210. // don't inherit from TestInfo.
  9211. ~TestInfo();
  9212. // Returns the test suite name.
  9213. const char* test_suite_name() const { return test_suite_name_.c_str(); }
  9214. // Legacy API is deprecated but still available
  9215. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9216. const char* test_case_name() const { return test_suite_name(); }
  9217. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9218. // Returns the test name.
  9219. const char* name() const { return name_.c_str(); }
  9220. // Returns the name of the parameter type, or NULL if this is not a typed
  9221. // or a type-parameterized test.
  9222. const char* type_param() const {
  9223. if (type_param_.get() != nullptr) return type_param_->c_str();
  9224. return nullptr;
  9225. }
  9226. // Returns the text representation of the value parameter, or NULL if this
  9227. // is not a value-parameterized test.
  9228. const char* value_param() const {
  9229. if (value_param_.get() != nullptr) return value_param_->c_str();
  9230. return nullptr;
  9231. }
  9232. // Returns the file name where this test is defined.
  9233. const char* file() const { return location_.file.c_str(); }
  9234. // Returns the line where this test is defined.
  9235. int line() const { return location_.line; }
  9236. // Return true if this test should not be run because it's in another shard.
  9237. bool is_in_another_shard() const { return is_in_another_shard_; }
  9238. // Returns true if this test should run, that is if the test is not
  9239. // disabled (or it is disabled but the also_run_disabled_tests flag has
  9240. // been specified) and its full name matches the user-specified filter.
  9241. //
  9242. // Google Test allows the user to filter the tests by their full names.
  9243. // The full name of a test Bar in test suite Foo is defined as
  9244. // "Foo.Bar". Only the tests that match the filter will run.
  9245. //
  9246. // A filter is a colon-separated list of glob (not regex) patterns,
  9247. // optionally followed by a '-' and a colon-separated list of
  9248. // negative patterns (tests to exclude). A test is run if it
  9249. // matches one of the positive patterns and does not match any of
  9250. // the negative patterns.
  9251. //
  9252. // For example, *A*:Foo.* is a filter that matches any string that
  9253. // contains the character 'A' or starts with "Foo.".
  9254. bool should_run() const { return should_run_; }
  9255. // Returns true if and only if this test will appear in the XML report.
  9256. bool is_reportable() const {
  9257. // The XML report includes tests matching the filter, excluding those
  9258. // run in other shards.
  9259. return matches_filter_ && !is_in_another_shard_;
  9260. }
  9261. // Returns the result of the test.
  9262. const TestResult* result() const { return &result_; }
  9263. private:
  9264. #if GTEST_HAS_DEATH_TEST
  9265. friend class internal::DefaultDeathTestFactory;
  9266. #endif // GTEST_HAS_DEATH_TEST
  9267. friend class Test;
  9268. friend class TestSuite;
  9269. friend class internal::UnitTestImpl;
  9270. friend class internal::StreamingListenerTest;
  9271. friend TestInfo* internal::MakeAndRegisterTestInfo(
  9272. const char* test_suite_name, const char* name, const char* type_param,
  9273. const char* value_param, internal::CodeLocation code_location,
  9274. internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc,
  9275. internal::TearDownTestSuiteFunc tear_down_tc,
  9276. internal::TestFactoryBase* factory);
  9277. // Constructs a TestInfo object. The newly constructed instance assumes
  9278. // ownership of the factory object.
  9279. TestInfo(const std::string& test_suite_name, const std::string& name,
  9280. const char* a_type_param, // NULL if not a type-parameterized test
  9281. const char* a_value_param, // NULL if not a value-parameterized test
  9282. internal::CodeLocation a_code_location,
  9283. internal::TypeId fixture_class_id,
  9284. internal::TestFactoryBase* factory);
  9285. // Increments the number of death tests encountered in this test so
  9286. // far.
  9287. int increment_death_test_count() {
  9288. return result_.increment_death_test_count();
  9289. }
  9290. // Creates the test object, runs it, records its result, and then
  9291. // deletes it.
  9292. void Run();
  9293. // Skip and records the test result for this object.
  9294. void Skip();
  9295. static void ClearTestResult(TestInfo* test_info) {
  9296. test_info->result_.Clear();
  9297. }
  9298. // These fields are immutable properties of the test.
  9299. const std::string test_suite_name_; // test suite name
  9300. const std::string name_; // Test name
  9301. // Name of the parameter type, or NULL if this is not a typed or a
  9302. // type-parameterized test.
  9303. const std::unique_ptr<const ::std::string> type_param_;
  9304. // Text representation of the value parameter, or NULL if this is not a
  9305. // value-parameterized test.
  9306. const std::unique_ptr<const ::std::string> value_param_;
  9307. internal::CodeLocation location_;
  9308. const internal::TypeId fixture_class_id_; // ID of the test fixture class
  9309. bool should_run_; // True if and only if this test should run
  9310. bool is_disabled_; // True if and only if this test is disabled
  9311. bool matches_filter_; // True if this test matches the
  9312. // user-specified filter.
  9313. bool is_in_another_shard_; // Will be run in another shard.
  9314. internal::TestFactoryBase* const factory_; // The factory that creates
  9315. // the test object
  9316. // This field is mutable and needs to be reset before running the
  9317. // test for the second time.
  9318. TestResult result_;
  9319. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
  9320. };
  9321. // A test suite, which consists of a vector of TestInfos.
  9322. //
  9323. // TestSuite is not copyable.
  9324. class GTEST_API_ TestSuite {
  9325. public:
  9326. // Creates a TestSuite with the given name.
  9327. //
  9328. // TestSuite does NOT have a default constructor. Always use this
  9329. // constructor to create a TestSuite object.
  9330. //
  9331. // Arguments:
  9332. //
  9333. // name: name of the test suite
  9334. // a_type_param: the name of the test's type parameter, or NULL if
  9335. // this is not a type-parameterized test.
  9336. // set_up_tc: pointer to the function that sets up the test suite
  9337. // tear_down_tc: pointer to the function that tears down the test suite
  9338. TestSuite(const char* name, const char* a_type_param,
  9339. internal::SetUpTestSuiteFunc set_up_tc,
  9340. internal::TearDownTestSuiteFunc tear_down_tc);
  9341. // Destructor of TestSuite.
  9342. virtual ~TestSuite();
  9343. // Gets the name of the TestSuite.
  9344. const char* name() const { return name_.c_str(); }
  9345. // Returns the name of the parameter type, or NULL if this is not a
  9346. // type-parameterized test suite.
  9347. const char* type_param() const {
  9348. if (type_param_.get() != nullptr) return type_param_->c_str();
  9349. return nullptr;
  9350. }
  9351. // Returns true if any test in this test suite should run.
  9352. bool should_run() const { return should_run_; }
  9353. // Gets the number of successful tests in this test suite.
  9354. int successful_test_count() const;
  9355. // Gets the number of skipped tests in this test suite.
  9356. int skipped_test_count() const;
  9357. // Gets the number of failed tests in this test suite.
  9358. int failed_test_count() const;
  9359. // Gets the number of disabled tests that will be reported in the XML report.
  9360. int reportable_disabled_test_count() const;
  9361. // Gets the number of disabled tests in this test suite.
  9362. int disabled_test_count() const;
  9363. // Gets the number of tests to be printed in the XML report.
  9364. int reportable_test_count() const;
  9365. // Get the number of tests in this test suite that should run.
  9366. int test_to_run_count() const;
  9367. // Gets the number of all tests in this test suite.
  9368. int total_test_count() const;
  9369. // Returns true if and only if the test suite passed.
  9370. bool Passed() const { return !Failed(); }
  9371. // Returns true if and only if the test suite failed.
  9372. bool Failed() const {
  9373. return failed_test_count() > 0 || ad_hoc_test_result().Failed();
  9374. }
  9375. // Returns the elapsed time, in milliseconds.
  9376. TimeInMillis elapsed_time() const { return elapsed_time_; }
  9377. // Gets the time of the test suite start, in ms from the start of the
  9378. // UNIX epoch.
  9379. TimeInMillis start_timestamp() const { return start_timestamp_; }
  9380. // Returns the i-th test among all the tests. i can range from 0 to
  9381. // total_test_count() - 1. If i is not in that range, returns NULL.
  9382. const TestInfo* GetTestInfo(int i) const;
  9383. // Returns the TestResult that holds test properties recorded during
  9384. // execution of SetUpTestSuite and TearDownTestSuite.
  9385. const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
  9386. private:
  9387. friend class Test;
  9388. friend class internal::UnitTestImpl;
  9389. // Gets the (mutable) vector of TestInfos in this TestSuite.
  9390. std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
  9391. // Gets the (immutable) vector of TestInfos in this TestSuite.
  9392. const std::vector<TestInfo*>& test_info_list() const {
  9393. return test_info_list_;
  9394. }
  9395. // Returns the i-th test among all the tests. i can range from 0 to
  9396. // total_test_count() - 1. If i is not in that range, returns NULL.
  9397. TestInfo* GetMutableTestInfo(int i);
  9398. // Sets the should_run member.
  9399. void set_should_run(bool should) { should_run_ = should; }
  9400. // Adds a TestInfo to this test suite. Will delete the TestInfo upon
  9401. // destruction of the TestSuite object.
  9402. void AddTestInfo(TestInfo * test_info);
  9403. // Clears the results of all tests in this test suite.
  9404. void ClearResult();
  9405. // Clears the results of all tests in the given test suite.
  9406. static void ClearTestSuiteResult(TestSuite* test_suite) {
  9407. test_suite->ClearResult();
  9408. }
  9409. // Runs every test in this TestSuite.
  9410. void Run();
  9411. // Skips the execution of tests under this TestSuite
  9412. void Skip();
  9413. // Runs SetUpTestSuite() for this TestSuite. This wrapper is needed
  9414. // for catching exceptions thrown from SetUpTestSuite().
  9415. void RunSetUpTestSuite() {
  9416. if (set_up_tc_ != nullptr) {
  9417. (*set_up_tc_)();
  9418. }
  9419. }
  9420. // Runs TearDownTestSuite() for this TestSuite. This wrapper is
  9421. // needed for catching exceptions thrown from TearDownTestSuite().
  9422. void RunTearDownTestSuite() {
  9423. if (tear_down_tc_ != nullptr) {
  9424. (*tear_down_tc_)();
  9425. }
  9426. }
  9427. // Returns true if and only if test passed.
  9428. static bool TestPassed(const TestInfo* test_info) {
  9429. return test_info->should_run() && test_info->result()->Passed();
  9430. }
  9431. // Returns true if and only if test skipped.
  9432. static bool TestSkipped(const TestInfo* test_info) {
  9433. return test_info->should_run() && test_info->result()->Skipped();
  9434. }
  9435. // Returns true if and only if test failed.
  9436. static bool TestFailed(const TestInfo* test_info) {
  9437. return test_info->should_run() && test_info->result()->Failed();
  9438. }
  9439. // Returns true if and only if the test is disabled and will be reported in
  9440. // the XML report.
  9441. static bool TestReportableDisabled(const TestInfo* test_info) {
  9442. return test_info->is_reportable() && test_info->is_disabled_;
  9443. }
  9444. // Returns true if and only if test is disabled.
  9445. static bool TestDisabled(const TestInfo* test_info) {
  9446. return test_info->is_disabled_;
  9447. }
  9448. // Returns true if and only if this test will appear in the XML report.
  9449. static bool TestReportable(const TestInfo* test_info) {
  9450. return test_info->is_reportable();
  9451. }
  9452. // Returns true if the given test should run.
  9453. static bool ShouldRunTest(const TestInfo* test_info) {
  9454. return test_info->should_run();
  9455. }
  9456. // Shuffles the tests in this test suite.
  9457. void ShuffleTests(internal::Random* random);
  9458. // Restores the test order to before the first shuffle.
  9459. void UnshuffleTests();
  9460. // Name of the test suite.
  9461. std::string name_;
  9462. // Name of the parameter type, or NULL if this is not a typed or a
  9463. // type-parameterized test.
  9464. const std::unique_ptr<const ::std::string> type_param_;
  9465. // The vector of TestInfos in their original order. It owns the
  9466. // elements in the vector.
  9467. std::vector<TestInfo*> test_info_list_;
  9468. // Provides a level of indirection for the test list to allow easy
  9469. // shuffling and restoring the test order. The i-th element in this
  9470. // vector is the index of the i-th test in the shuffled test list.
  9471. std::vector<int> test_indices_;
  9472. // Pointer to the function that sets up the test suite.
  9473. internal::SetUpTestSuiteFunc set_up_tc_;
  9474. // Pointer to the function that tears down the test suite.
  9475. internal::TearDownTestSuiteFunc tear_down_tc_;
  9476. // True if and only if any test in this test suite should run.
  9477. bool should_run_;
  9478. // The start time, in milliseconds since UNIX Epoch.
  9479. TimeInMillis start_timestamp_;
  9480. // Elapsed time, in milliseconds.
  9481. TimeInMillis elapsed_time_;
  9482. // Holds test properties recorded during execution of SetUpTestSuite and
  9483. // TearDownTestSuite.
  9484. TestResult ad_hoc_test_result_;
  9485. // We disallow copying TestSuites.
  9486. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestSuite);
  9487. };
  9488. // An Environment object is capable of setting up and tearing down an
  9489. // environment. You should subclass this to define your own
  9490. // environment(s).
  9491. //
  9492. // An Environment object does the set-up and tear-down in virtual
  9493. // methods SetUp() and TearDown() instead of the constructor and the
  9494. // destructor, as:
  9495. //
  9496. // 1. You cannot safely throw from a destructor. This is a problem
  9497. // as in some cases Google Test is used where exceptions are enabled, and
  9498. // we may want to implement ASSERT_* using exceptions where they are
  9499. // available.
  9500. // 2. You cannot use ASSERT_* directly in a constructor or
  9501. // destructor.
  9502. class Environment {
  9503. public:
  9504. // The d'tor is virtual as we need to subclass Environment.
  9505. virtual ~Environment() {}
  9506. // Override this to define how to set up the environment.
  9507. virtual void SetUp() {}
  9508. // Override this to define how to tear down the environment.
  9509. virtual void TearDown() {}
  9510. private:
  9511. // If you see an error about overriding the following function or
  9512. // about it being private, you have mis-spelled SetUp() as Setup().
  9513. struct Setup_should_be_spelled_SetUp {};
  9514. virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
  9515. };
  9516. #if GTEST_HAS_EXCEPTIONS
  9517. // Exception which can be thrown from TestEventListener::OnTestPartResult.
  9518. class GTEST_API_ AssertionException
  9519. : public internal::GoogleTestFailureException {
  9520. public:
  9521. explicit AssertionException(const TestPartResult& result)
  9522. : GoogleTestFailureException(result) {}
  9523. };
  9524. #endif // GTEST_HAS_EXCEPTIONS
  9525. // The interface for tracing execution of tests. The methods are organized in
  9526. // the order the corresponding events are fired.
  9527. class TestEventListener {
  9528. public:
  9529. virtual ~TestEventListener() {}
  9530. // Fired before any test activity starts.
  9531. virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
  9532. // Fired before each iteration of tests starts. There may be more than
  9533. // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
  9534. // index, starting from 0.
  9535. virtual void OnTestIterationStart(const UnitTest& unit_test,
  9536. int iteration) = 0;
  9537. // Fired before environment set-up for each iteration of tests starts.
  9538. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
  9539. // Fired after environment set-up for each iteration of tests ends.
  9540. virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
  9541. // Fired before the test suite starts.
  9542. virtual void OnTestSuiteStart(const TestSuite& /*test_suite*/) {}
  9543. // Legacy API is deprecated but still available
  9544. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9545. virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
  9546. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9547. // Fired before the test starts.
  9548. virtual void OnTestStart(const TestInfo& test_info) = 0;
  9549. // Fired after a failed assertion or a SUCCEED() invocation.
  9550. // If you want to throw an exception from this function to skip to the next
  9551. // TEST, it must be AssertionException defined above, or inherited from it.
  9552. virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
  9553. // Fired after the test ends.
  9554. virtual void OnTestEnd(const TestInfo& test_info) = 0;
  9555. // Fired after the test suite ends.
  9556. virtual void OnTestSuiteEnd(const TestSuite& /*test_suite*/) {}
  9557. // Legacy API is deprecated but still available
  9558. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9559. virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
  9560. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9561. // Fired before environment tear-down for each iteration of tests starts.
  9562. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
  9563. // Fired after environment tear-down for each iteration of tests ends.
  9564. virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
  9565. // Fired after each iteration of tests finishes.
  9566. virtual void OnTestIterationEnd(const UnitTest& unit_test,
  9567. int iteration) = 0;
  9568. // Fired after all test activities have ended.
  9569. virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
  9570. };
  9571. // The convenience class for users who need to override just one or two
  9572. // methods and are not concerned that a possible change to a signature of
  9573. // the methods they override will not be caught during the build. For
  9574. // comments about each method please see the definition of TestEventListener
  9575. // above.
  9576. class EmptyTestEventListener : public TestEventListener {
  9577. public:
  9578. void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
  9579. void OnTestIterationStart(const UnitTest& /*unit_test*/,
  9580. int /*iteration*/) override {}
  9581. void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
  9582. void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
  9583. void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
  9584. // Legacy API is deprecated but still available
  9585. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9586. void OnTestCaseStart(const TestCase& /*test_case*/) override {}
  9587. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9588. void OnTestStart(const TestInfo& /*test_info*/) override {}
  9589. void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {}
  9590. void OnTestEnd(const TestInfo& /*test_info*/) override {}
  9591. void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
  9592. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9593. void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
  9594. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9595. void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
  9596. void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
  9597. void OnTestIterationEnd(const UnitTest& /*unit_test*/,
  9598. int /*iteration*/) override {}
  9599. void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
  9600. };
  9601. // TestEventListeners lets users add listeners to track events in Google Test.
  9602. class GTEST_API_ TestEventListeners {
  9603. public:
  9604. TestEventListeners();
  9605. ~TestEventListeners();
  9606. // Appends an event listener to the end of the list. Google Test assumes
  9607. // the ownership of the listener (i.e. it will delete the listener when
  9608. // the test program finishes).
  9609. void Append(TestEventListener* listener);
  9610. // Removes the given event listener from the list and returns it. It then
  9611. // becomes the caller's responsibility to delete the listener. Returns
  9612. // NULL if the listener is not found in the list.
  9613. TestEventListener* Release(TestEventListener* listener);
  9614. // Returns the standard listener responsible for the default console
  9615. // output. Can be removed from the listeners list to shut down default
  9616. // console output. Note that removing this object from the listener list
  9617. // with Release transfers its ownership to the caller and makes this
  9618. // function return NULL the next time.
  9619. TestEventListener* default_result_printer() const {
  9620. return default_result_printer_;
  9621. }
  9622. // Returns the standard listener responsible for the default XML output
  9623. // controlled by the --gtest_output=xml flag. Can be removed from the
  9624. // listeners list by users who want to shut down the default XML output
  9625. // controlled by this flag and substitute it with custom one. Note that
  9626. // removing this object from the listener list with Release transfers its
  9627. // ownership to the caller and makes this function return NULL the next
  9628. // time.
  9629. TestEventListener* default_xml_generator() const {
  9630. return default_xml_generator_;
  9631. }
  9632. private:
  9633. friend class TestSuite;
  9634. friend class TestInfo;
  9635. friend class internal::DefaultGlobalTestPartResultReporter;
  9636. friend class internal::NoExecDeathTest;
  9637. friend class internal::TestEventListenersAccessor;
  9638. friend class internal::UnitTestImpl;
  9639. // Returns repeater that broadcasts the TestEventListener events to all
  9640. // subscribers.
  9641. TestEventListener* repeater();
  9642. // Sets the default_result_printer attribute to the provided listener.
  9643. // The listener is also added to the listener list and previous
  9644. // default_result_printer is removed from it and deleted. The listener can
  9645. // also be NULL in which case it will not be added to the list. Does
  9646. // nothing if the previous and the current listener objects are the same.
  9647. void SetDefaultResultPrinter(TestEventListener* listener);
  9648. // Sets the default_xml_generator attribute to the provided listener. The
  9649. // listener is also added to the listener list and previous
  9650. // default_xml_generator is removed from it and deleted. The listener can
  9651. // also be NULL in which case it will not be added to the list. Does
  9652. // nothing if the previous and the current listener objects are the same.
  9653. void SetDefaultXmlGenerator(TestEventListener* listener);
  9654. // Controls whether events will be forwarded by the repeater to the
  9655. // listeners in the list.
  9656. bool EventForwardingEnabled() const;
  9657. void SuppressEventForwarding();
  9658. // The actual list of listeners.
  9659. internal::TestEventRepeater* repeater_;
  9660. // Listener responsible for the standard result output.
  9661. TestEventListener* default_result_printer_;
  9662. // Listener responsible for the creation of the XML output file.
  9663. TestEventListener* default_xml_generator_;
  9664. // We disallow copying TestEventListeners.
  9665. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
  9666. };
  9667. // A UnitTest consists of a vector of TestSuites.
  9668. //
  9669. // This is a singleton class. The only instance of UnitTest is
  9670. // created when UnitTest::GetInstance() is first called. This
  9671. // instance is never deleted.
  9672. //
  9673. // UnitTest is not copyable.
  9674. //
  9675. // This class is thread-safe as long as the methods are called
  9676. // according to their specification.
  9677. class GTEST_API_ UnitTest {
  9678. public:
  9679. // Gets the singleton UnitTest object. The first time this method
  9680. // is called, a UnitTest object is constructed and returned.
  9681. // Consecutive calls will return the same object.
  9682. static UnitTest* GetInstance();
  9683. // Runs all tests in this UnitTest object and prints the result.
  9684. // Returns 0 if successful, or 1 otherwise.
  9685. //
  9686. // This method can only be called from the main thread.
  9687. //
  9688. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  9689. int Run() GTEST_MUST_USE_RESULT_;
  9690. // Returns the working directory when the first TEST() or TEST_F()
  9691. // was executed. The UnitTest object owns the string.
  9692. const char* original_working_dir() const;
  9693. // Returns the TestSuite object for the test that's currently running,
  9694. // or NULL if no test is running.
  9695. const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_);
  9696. // Legacy API is still available but deprecated
  9697. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9698. const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_);
  9699. #endif
  9700. // Returns the TestInfo object for the test that's currently running,
  9701. // or NULL if no test is running.
  9702. const TestInfo* current_test_info() const
  9703. GTEST_LOCK_EXCLUDED_(mutex_);
  9704. // Returns the random seed used at the start of the current test run.
  9705. int random_seed() const;
  9706. // Returns the ParameterizedTestSuiteRegistry object used to keep track of
  9707. // value-parameterized tests and instantiate and register them.
  9708. //
  9709. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  9710. internal::ParameterizedTestSuiteRegistry& parameterized_test_registry()
  9711. GTEST_LOCK_EXCLUDED_(mutex_);
  9712. // Gets the number of successful test suites.
  9713. int successful_test_suite_count() const;
  9714. // Gets the number of failed test suites.
  9715. int failed_test_suite_count() const;
  9716. // Gets the number of all test suites.
  9717. int total_test_suite_count() const;
  9718. // Gets the number of all test suites that contain at least one test
  9719. // that should run.
  9720. int test_suite_to_run_count() const;
  9721. // Legacy API is deprecated but still available
  9722. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9723. int successful_test_case_count() const;
  9724. int failed_test_case_count() const;
  9725. int total_test_case_count() const;
  9726. int test_case_to_run_count() const;
  9727. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9728. // Gets the number of successful tests.
  9729. int successful_test_count() const;
  9730. // Gets the number of skipped tests.
  9731. int skipped_test_count() const;
  9732. // Gets the number of failed tests.
  9733. int failed_test_count() const;
  9734. // Gets the number of disabled tests that will be reported in the XML report.
  9735. int reportable_disabled_test_count() const;
  9736. // Gets the number of disabled tests.
  9737. int disabled_test_count() const;
  9738. // Gets the number of tests to be printed in the XML report.
  9739. int reportable_test_count() const;
  9740. // Gets the number of all tests.
  9741. int total_test_count() const;
  9742. // Gets the number of tests that should run.
  9743. int test_to_run_count() const;
  9744. // Gets the time of the test program start, in ms from the start of the
  9745. // UNIX epoch.
  9746. TimeInMillis start_timestamp() const;
  9747. // Gets the elapsed time, in milliseconds.
  9748. TimeInMillis elapsed_time() const;
  9749. // Returns true if and only if the unit test passed (i.e. all test suites
  9750. // passed).
  9751. bool Passed() const;
  9752. // Returns true if and only if the unit test failed (i.e. some test suite
  9753. // failed or something outside of all tests failed).
  9754. bool Failed() const;
  9755. // Gets the i-th test suite among all the test suites. i can range from 0 to
  9756. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  9757. const TestSuite* GetTestSuite(int i) const;
  9758. // Legacy API is deprecated but still available
  9759. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9760. const TestCase* GetTestCase(int i) const;
  9761. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  9762. // Returns the TestResult containing information on test failures and
  9763. // properties logged outside of individual test suites.
  9764. const TestResult& ad_hoc_test_result() const;
  9765. // Returns the list of event listeners that can be used to track events
  9766. // inside Google Test.
  9767. TestEventListeners& listeners();
  9768. private:
  9769. // Registers and returns a global test environment. When a test
  9770. // program is run, all global test environments will be set-up in
  9771. // the order they were registered. After all tests in the program
  9772. // have finished, all global test environments will be torn-down in
  9773. // the *reverse* order they were registered.
  9774. //
  9775. // The UnitTest object takes ownership of the given environment.
  9776. //
  9777. // This method can only be called from the main thread.
  9778. Environment* AddEnvironment(Environment* env);
  9779. // Adds a TestPartResult to the current TestResult object. All
  9780. // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
  9781. // eventually call this to report their results. The user code
  9782. // should use the assertion macros instead of calling this directly.
  9783. void AddTestPartResult(TestPartResult::Type result_type,
  9784. const char* file_name,
  9785. int line_number,
  9786. const std::string& message,
  9787. const std::string& os_stack_trace)
  9788. GTEST_LOCK_EXCLUDED_(mutex_);
  9789. // Adds a TestProperty to the current TestResult object when invoked from
  9790. // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
  9791. // from SetUpTestSuite or TearDownTestSuite, or to the global property set
  9792. // when invoked elsewhere. If the result already contains a property with
  9793. // the same key, the value will be updated.
  9794. void RecordProperty(const std::string& key, const std::string& value);
  9795. // Gets the i-th test suite among all the test suites. i can range from 0 to
  9796. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  9797. TestSuite* GetMutableTestSuite(int i);
  9798. // Accessors for the implementation object.
  9799. internal::UnitTestImpl* impl() { return impl_; }
  9800. const internal::UnitTestImpl* impl() const { return impl_; }
  9801. // These classes and functions are friends as they need to access private
  9802. // members of UnitTest.
  9803. friend class ScopedTrace;
  9804. friend class Test;
  9805. friend class internal::AssertHelper;
  9806. friend class internal::StreamingListenerTest;
  9807. friend class internal::UnitTestRecordPropertyTestHelper;
  9808. friend Environment* AddGlobalTestEnvironment(Environment* env);
  9809. friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();
  9810. friend internal::UnitTestImpl* internal::GetUnitTestImpl();
  9811. friend void internal::ReportFailureInUnknownLocation(
  9812. TestPartResult::Type result_type,
  9813. const std::string& message);
  9814. // Creates an empty UnitTest.
  9815. UnitTest();
  9816. // D'tor
  9817. virtual ~UnitTest();
  9818. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  9819. // Google Test trace stack.
  9820. void PushGTestTrace(const internal::TraceInfo& trace)
  9821. GTEST_LOCK_EXCLUDED_(mutex_);
  9822. // Pops a trace from the per-thread Google Test trace stack.
  9823. void PopGTestTrace()
  9824. GTEST_LOCK_EXCLUDED_(mutex_);
  9825. // Protects mutable state in *impl_. This is mutable as some const
  9826. // methods need to lock it too.
  9827. mutable internal::Mutex mutex_;
  9828. // Opaque implementation object. This field is never changed once
  9829. // the object is constructed. We don't mark it as const here, as
  9830. // doing so will cause a warning in the constructor of UnitTest.
  9831. // Mutable state in *impl_ is protected by mutex_.
  9832. internal::UnitTestImpl* impl_;
  9833. // We disallow copying UnitTest.
  9834. GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
  9835. };
  9836. // A convenient wrapper for adding an environment for the test
  9837. // program.
  9838. //
  9839. // You should call this before RUN_ALL_TESTS() is called, probably in
  9840. // main(). If you use gtest_main, you need to call this before main()
  9841. // starts for it to take effect. For example, you can define a global
  9842. // variable like this:
  9843. //
  9844. // testing::Environment* const foo_env =
  9845. // testing::AddGlobalTestEnvironment(new FooEnvironment);
  9846. //
  9847. // However, we strongly recommend you to write your own main() and
  9848. // call AddGlobalTestEnvironment() there, as relying on initialization
  9849. // of global variables makes the code harder to read and may cause
  9850. // problems when you register multiple environments from different
  9851. // translation units and the environments have dependencies among them
  9852. // (remember that the compiler doesn't guarantee the order in which
  9853. // global variables from different translation units are initialized).
  9854. inline Environment* AddGlobalTestEnvironment(Environment* env) {
  9855. return UnitTest::GetInstance()->AddEnvironment(env);
  9856. }
  9857. // Initializes Google Test. This must be called before calling
  9858. // RUN_ALL_TESTS(). In particular, it parses a command line for the
  9859. // flags that Google Test recognizes. Whenever a Google Test flag is
  9860. // seen, it is removed from argv, and *argc is decremented.
  9861. //
  9862. // No value is returned. Instead, the Google Test flag variables are
  9863. // updated.
  9864. //
  9865. // Calling the function for the second time has no user-visible effect.
  9866. GTEST_API_ void InitGoogleTest(int* argc, char** argv);
  9867. // This overloaded version can be used in Windows programs compiled in
  9868. // UNICODE mode.
  9869. GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
  9870. // This overloaded version can be used on Arduino/embedded platforms where
  9871. // there is no argc/argv.
  9872. GTEST_API_ void InitGoogleTest();
  9873. namespace internal {
  9874. // Separate the error generating code from the code path to reduce the stack
  9875. // frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
  9876. // when calling EXPECT_* in a tight loop.
  9877. template <typename T1, typename T2>
  9878. AssertionResult CmpHelperEQFailure(const char* lhs_expression,
  9879. const char* rhs_expression,
  9880. const T1& lhs, const T2& rhs) {
  9881. return EqFailure(lhs_expression,
  9882. rhs_expression,
  9883. FormatForComparisonFailureMessage(lhs, rhs),
  9884. FormatForComparisonFailureMessage(rhs, lhs),
  9885. false);
  9886. }
  9887. // This block of code defines operator==/!=
  9888. // to block lexical scope lookup.
  9889. // It prevents using invalid operator==/!= defined at namespace scope.
  9890. struct faketype {};
  9891. inline bool operator==(faketype, faketype) { return true; }
  9892. inline bool operator!=(faketype, faketype) { return false; }
  9893. // The helper function for {ASSERT|EXPECT}_EQ.
  9894. template <typename T1, typename T2>
  9895. AssertionResult CmpHelperEQ(const char* lhs_expression,
  9896. const char* rhs_expression,
  9897. const T1& lhs,
  9898. const T2& rhs) {
  9899. if (lhs == rhs) {
  9900. return AssertionSuccess();
  9901. }
  9902. return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
  9903. }
  9904. class EqHelper {
  9905. public:
  9906. // This templatized version is for the general case.
  9907. template <
  9908. typename T1, typename T2,
  9909. // Disable this overload for cases where one argument is a pointer
  9910. // and the other is the null pointer constant.
  9911. typename std::enable_if<!std::is_integral<T1>::value ||
  9912. !std::is_pointer<T2>::value>::type* = nullptr>
  9913. static AssertionResult Compare(const char* lhs_expression,
  9914. const char* rhs_expression, const T1& lhs,
  9915. const T2& rhs) {
  9916. return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
  9917. }
  9918. // With this overloaded version, we allow anonymous enums to be used
  9919. // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
  9920. // enums can be implicitly cast to BiggestInt.
  9921. //
  9922. // Even though its body looks the same as the above version, we
  9923. // cannot merge the two, as it will make anonymous enums unhappy.
  9924. static AssertionResult Compare(const char* lhs_expression,
  9925. const char* rhs_expression,
  9926. BiggestInt lhs,
  9927. BiggestInt rhs) {
  9928. return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
  9929. }
  9930. template <typename T>
  9931. static AssertionResult Compare(
  9932. const char* lhs_expression, const char* rhs_expression,
  9933. // Handle cases where '0' is used as a null pointer literal.
  9934. std::nullptr_t /* lhs */, T* rhs) {
  9935. // We already know that 'lhs' is a null pointer.
  9936. return CmpHelperEQ(lhs_expression, rhs_expression, static_cast<T*>(nullptr),
  9937. rhs);
  9938. }
  9939. };
  9940. // Separate the error generating code from the code path to reduce the stack
  9941. // frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
  9942. // when calling EXPECT_OP in a tight loop.
  9943. template <typename T1, typename T2>
  9944. AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
  9945. const T1& val1, const T2& val2,
  9946. const char* op) {
  9947. return AssertionFailure()
  9948. << "Expected: (" << expr1 << ") " << op << " (" << expr2
  9949. << "), actual: " << FormatForComparisonFailureMessage(val1, val2)
  9950. << " vs " << FormatForComparisonFailureMessage(val2, val1);
  9951. }
  9952. // A macro for implementing the helper functions needed to implement
  9953. // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
  9954. // of similar code.
  9955. //
  9956. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  9957. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
  9958. template <typename T1, typename T2>\
  9959. AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
  9960. const T1& val1, const T2& val2) {\
  9961. if (val1 op val2) {\
  9962. return AssertionSuccess();\
  9963. } else {\
  9964. return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
  9965. }\
  9966. }
  9967. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  9968. // Implements the helper function for {ASSERT|EXPECT}_NE
  9969. GTEST_IMPL_CMP_HELPER_(NE, !=)
  9970. // Implements the helper function for {ASSERT|EXPECT}_LE
  9971. GTEST_IMPL_CMP_HELPER_(LE, <=)
  9972. // Implements the helper function for {ASSERT|EXPECT}_LT
  9973. GTEST_IMPL_CMP_HELPER_(LT, <)
  9974. // Implements the helper function for {ASSERT|EXPECT}_GE
  9975. GTEST_IMPL_CMP_HELPER_(GE, >=)
  9976. // Implements the helper function for {ASSERT|EXPECT}_GT
  9977. GTEST_IMPL_CMP_HELPER_(GT, >)
  9978. #undef GTEST_IMPL_CMP_HELPER_
  9979. // The helper function for {ASSERT|EXPECT}_STREQ.
  9980. //
  9981. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  9982. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
  9983. const char* s2_expression,
  9984. const char* s1,
  9985. const char* s2);
  9986. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  9987. //
  9988. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  9989. GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
  9990. const char* s2_expression,
  9991. const char* s1,
  9992. const char* s2);
  9993. // The helper function for {ASSERT|EXPECT}_STRNE.
  9994. //
  9995. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  9996. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
  9997. const char* s2_expression,
  9998. const char* s1,
  9999. const char* s2);
  10000. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  10001. //
  10002. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  10003. GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  10004. const char* s2_expression,
  10005. const char* s1,
  10006. const char* s2);
  10007. // Helper function for *_STREQ on wide strings.
  10008. //
  10009. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  10010. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
  10011. const char* s2_expression,
  10012. const wchar_t* s1,
  10013. const wchar_t* s2);
  10014. // Helper function for *_STRNE on wide strings.
  10015. //
  10016. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  10017. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
  10018. const char* s2_expression,
  10019. const wchar_t* s1,
  10020. const wchar_t* s2);
  10021. } // namespace internal
  10022. // IsSubstring() and IsNotSubstring() are intended to be used as the
  10023. // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
  10024. // themselves. They check whether needle is a substring of haystack
  10025. // (NULL is considered a substring of itself only), and return an
  10026. // appropriate error message when they fail.
  10027. //
  10028. // The {needle,haystack}_expr arguments are the stringified
  10029. // expressions that generated the two real arguments.
  10030. GTEST_API_ AssertionResult IsSubstring(
  10031. const char* needle_expr, const char* haystack_expr,
  10032. const char* needle, const char* haystack);
  10033. GTEST_API_ AssertionResult IsSubstring(
  10034. const char* needle_expr, const char* haystack_expr,
  10035. const wchar_t* needle, const wchar_t* haystack);
  10036. GTEST_API_ AssertionResult IsNotSubstring(
  10037. const char* needle_expr, const char* haystack_expr,
  10038. const char* needle, const char* haystack);
  10039. GTEST_API_ AssertionResult IsNotSubstring(
  10040. const char* needle_expr, const char* haystack_expr,
  10041. const wchar_t* needle, const wchar_t* haystack);
  10042. GTEST_API_ AssertionResult IsSubstring(
  10043. const char* needle_expr, const char* haystack_expr,
  10044. const ::std::string& needle, const ::std::string& haystack);
  10045. GTEST_API_ AssertionResult IsNotSubstring(
  10046. const char* needle_expr, const char* haystack_expr,
  10047. const ::std::string& needle, const ::std::string& haystack);
  10048. #if GTEST_HAS_STD_WSTRING
  10049. GTEST_API_ AssertionResult IsSubstring(
  10050. const char* needle_expr, const char* haystack_expr,
  10051. const ::std::wstring& needle, const ::std::wstring& haystack);
  10052. GTEST_API_ AssertionResult IsNotSubstring(
  10053. const char* needle_expr, const char* haystack_expr,
  10054. const ::std::wstring& needle, const ::std::wstring& haystack);
  10055. #endif // GTEST_HAS_STD_WSTRING
  10056. namespace internal {
  10057. // Helper template function for comparing floating-points.
  10058. //
  10059. // Template parameter:
  10060. //
  10061. // RawType: the raw floating-point type (either float or double)
  10062. //
  10063. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  10064. template <typename RawType>
  10065. AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
  10066. const char* rhs_expression,
  10067. RawType lhs_value,
  10068. RawType rhs_value) {
  10069. const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
  10070. if (lhs.AlmostEquals(rhs)) {
  10071. return AssertionSuccess();
  10072. }
  10073. ::std::stringstream lhs_ss;
  10074. lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  10075. << lhs_value;
  10076. ::std::stringstream rhs_ss;
  10077. rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  10078. << rhs_value;
  10079. return EqFailure(lhs_expression,
  10080. rhs_expression,
  10081. StringStreamToString(&lhs_ss),
  10082. StringStreamToString(&rhs_ss),
  10083. false);
  10084. }
  10085. // Helper function for implementing ASSERT_NEAR.
  10086. //
  10087. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  10088. GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
  10089. const char* expr2,
  10090. const char* abs_error_expr,
  10091. double val1,
  10092. double val2,
  10093. double abs_error);
  10094. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  10095. // A class that enables one to stream messages to assertion macros
  10096. class GTEST_API_ AssertHelper {
  10097. public:
  10098. // Constructor.
  10099. AssertHelper(TestPartResult::Type type,
  10100. const char* file,
  10101. int line,
  10102. const char* message);
  10103. ~AssertHelper();
  10104. // Message assignment is a semantic trick to enable assertion
  10105. // streaming; see the GTEST_MESSAGE_ macro below.
  10106. void operator=(const Message& message) const;
  10107. private:
  10108. // We put our data in a struct so that the size of the AssertHelper class can
  10109. // be as small as possible. This is important because gcc is incapable of
  10110. // re-using stack space even for temporary variables, so every EXPECT_EQ
  10111. // reserves stack space for another AssertHelper.
  10112. struct AssertHelperData {
  10113. AssertHelperData(TestPartResult::Type t,
  10114. const char* srcfile,
  10115. int line_num,
  10116. const char* msg)
  10117. : type(t), file(srcfile), line(line_num), message(msg) { }
  10118. TestPartResult::Type const type;
  10119. const char* const file;
  10120. int const line;
  10121. std::string const message;
  10122. private:
  10123. GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
  10124. };
  10125. AssertHelperData* const data_;
  10126. GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
  10127. };
  10128. } // namespace internal
  10129. // The pure interface class that all value-parameterized tests inherit from.
  10130. // A value-parameterized class must inherit from both ::testing::Test and
  10131. // ::testing::WithParamInterface. In most cases that just means inheriting
  10132. // from ::testing::TestWithParam, but more complicated test hierarchies
  10133. // may need to inherit from Test and WithParamInterface at different levels.
  10134. //
  10135. // This interface has support for accessing the test parameter value via
  10136. // the GetParam() method.
  10137. //
  10138. // Use it with one of the parameter generator defining functions, like Range(),
  10139. // Values(), ValuesIn(), Bool(), and Combine().
  10140. //
  10141. // class FooTest : public ::testing::TestWithParam<int> {
  10142. // protected:
  10143. // FooTest() {
  10144. // // Can use GetParam() here.
  10145. // }
  10146. // ~FooTest() override {
  10147. // // Can use GetParam() here.
  10148. // }
  10149. // void SetUp() override {
  10150. // // Can use GetParam() here.
  10151. // }
  10152. // void TearDown override {
  10153. // // Can use GetParam() here.
  10154. // }
  10155. // };
  10156. // TEST_P(FooTest, DoesBar) {
  10157. // // Can use GetParam() method here.
  10158. // Foo foo;
  10159. // ASSERT_TRUE(foo.DoesBar(GetParam()));
  10160. // }
  10161. // INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
  10162. template <typename T>
  10163. class WithParamInterface {
  10164. public:
  10165. typedef T ParamType;
  10166. virtual ~WithParamInterface() {}
  10167. // The current parameter value. Is also available in the test fixture's
  10168. // constructor.
  10169. static const ParamType& GetParam() {
  10170. GTEST_CHECK_(parameter_ != nullptr)
  10171. << "GetParam() can only be called inside a value-parameterized test "
  10172. << "-- did you intend to write TEST_P instead of TEST_F?";
  10173. return *parameter_;
  10174. }
  10175. private:
  10176. // Sets parameter value. The caller is responsible for making sure the value
  10177. // remains alive and unchanged throughout the current test.
  10178. static void SetParam(const ParamType* parameter) {
  10179. parameter_ = parameter;
  10180. }
  10181. // Static value used for accessing parameter during a test lifetime.
  10182. static const ParamType* parameter_;
  10183. // TestClass must be a subclass of WithParamInterface<T> and Test.
  10184. template <class TestClass> friend class internal::ParameterizedTestFactory;
  10185. };
  10186. template <typename T>
  10187. const T* WithParamInterface<T>::parameter_ = nullptr;
  10188. // Most value-parameterized classes can ignore the existence of
  10189. // WithParamInterface, and can just inherit from ::testing::TestWithParam.
  10190. template <typename T>
  10191. class TestWithParam : public Test, public WithParamInterface<T> {
  10192. };
  10193. // Macros for indicating success/failure in test code.
  10194. // Skips test in runtime.
  10195. // Skipping test aborts current function.
  10196. // Skipped tests are neither successful nor failed.
  10197. #define GTEST_SKIP() GTEST_SKIP_("")
  10198. // ADD_FAILURE unconditionally adds a failure to the current test.
  10199. // SUCCEED generates a success - it doesn't automatically make the
  10200. // current test successful, as a test is only successful when it has
  10201. // no failure.
  10202. //
  10203. // EXPECT_* verifies that a certain condition is satisfied. If not,
  10204. // it behaves like ADD_FAILURE. In particular:
  10205. //
  10206. // EXPECT_TRUE verifies that a Boolean condition is true.
  10207. // EXPECT_FALSE verifies that a Boolean condition is false.
  10208. //
  10209. // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
  10210. // that they will also abort the current function on failure. People
  10211. // usually want the fail-fast behavior of FAIL and ASSERT_*, but those
  10212. // writing data-driven tests often find themselves using ADD_FAILURE
  10213. // and EXPECT_* more.
  10214. // Generates a nonfatal failure with a generic message.
  10215. #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
  10216. // Generates a nonfatal failure at the given source file location with
  10217. // a generic message.
  10218. #define ADD_FAILURE_AT(file, line) \
  10219. GTEST_MESSAGE_AT_(file, line, "Failed", \
  10220. ::testing::TestPartResult::kNonFatalFailure)
  10221. // Generates a fatal failure with a generic message.
  10222. #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
  10223. // Like GTEST_FAIL(), but at the given source file location.
  10224. #define GTEST_FAIL_AT(file, line) \
  10225. GTEST_MESSAGE_AT_(file, line, "Failed", \
  10226. ::testing::TestPartResult::kFatalFailure)
  10227. // Define this macro to 1 to omit the definition of FAIL(), which is a
  10228. // generic name and clashes with some other libraries.
  10229. #if !GTEST_DONT_DEFINE_FAIL
  10230. # define FAIL() GTEST_FAIL()
  10231. #endif
  10232. // Generates a success with a generic message.
  10233. #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
  10234. // Define this macro to 1 to omit the definition of SUCCEED(), which
  10235. // is a generic name and clashes with some other libraries.
  10236. #if !GTEST_DONT_DEFINE_SUCCEED
  10237. # define SUCCEED() GTEST_SUCCEED()
  10238. #endif
  10239. // Macros for testing exceptions.
  10240. //
  10241. // * {ASSERT|EXPECT}_THROW(statement, expected_exception):
  10242. // Tests that the statement throws the expected exception.
  10243. // * {ASSERT|EXPECT}_NO_THROW(statement):
  10244. // Tests that the statement doesn't throw any exception.
  10245. // * {ASSERT|EXPECT}_ANY_THROW(statement):
  10246. // Tests that the statement throws an exception.
  10247. #define EXPECT_THROW(statement, expected_exception) \
  10248. GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
  10249. #define EXPECT_NO_THROW(statement) \
  10250. GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
  10251. #define EXPECT_ANY_THROW(statement) \
  10252. GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
  10253. #define ASSERT_THROW(statement, expected_exception) \
  10254. GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
  10255. #define ASSERT_NO_THROW(statement) \
  10256. GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
  10257. #define ASSERT_ANY_THROW(statement) \
  10258. GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
  10259. // Boolean assertions. Condition can be either a Boolean expression or an
  10260. // AssertionResult. For more information on how to use AssertionResult with
  10261. // these macros see comments on that class.
  10262. #define GTEST_EXPECT_TRUE(condition) \
  10263. GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
  10264. GTEST_NONFATAL_FAILURE_)
  10265. #define GTEST_EXPECT_FALSE(condition) \
  10266. GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
  10267. GTEST_NONFATAL_FAILURE_)
  10268. #define GTEST_ASSERT_TRUE(condition) \
  10269. GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
  10270. GTEST_FATAL_FAILURE_)
  10271. #define GTEST_ASSERT_FALSE(condition) \
  10272. GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
  10273. GTEST_FATAL_FAILURE_)
  10274. // Define these macros to 1 to omit the definition of the corresponding
  10275. // EXPECT or ASSERT, which clashes with some users' own code.
  10276. #if !GTEST_DONT_DEFINE_EXPECT_TRUE
  10277. #define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)
  10278. #endif
  10279. #if !GTEST_DONT_DEFINE_EXPECT_FALSE
  10280. #define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)
  10281. #endif
  10282. #if !GTEST_DONT_DEFINE_ASSERT_TRUE
  10283. #define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)
  10284. #endif
  10285. #if !GTEST_DONT_DEFINE_ASSERT_FALSE
  10286. #define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)
  10287. #endif
  10288. // Macros for testing equalities and inequalities.
  10289. //
  10290. // * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
  10291. // * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
  10292. // * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
  10293. // * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
  10294. // * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
  10295. // * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
  10296. //
  10297. // When they are not, Google Test prints both the tested expressions and
  10298. // their actual values. The values must be compatible built-in types,
  10299. // or you will get a compiler error. By "compatible" we mean that the
  10300. // values can be compared by the respective operator.
  10301. //
  10302. // Note:
  10303. //
  10304. // 1. It is possible to make a user-defined type work with
  10305. // {ASSERT|EXPECT}_??(), but that requires overloading the
  10306. // comparison operators and is thus discouraged by the Google C++
  10307. // Usage Guide. Therefore, you are advised to use the
  10308. // {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
  10309. // equal.
  10310. //
  10311. // 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
  10312. // pointers (in particular, C strings). Therefore, if you use it
  10313. // with two C strings, you are testing how their locations in memory
  10314. // are related, not how their content is related. To compare two C
  10315. // strings by content, use {ASSERT|EXPECT}_STR*().
  10316. //
  10317. // 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to
  10318. // {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you
  10319. // what the actual value is when it fails, and similarly for the
  10320. // other comparisons.
  10321. //
  10322. // 4. Do not depend on the order in which {ASSERT|EXPECT}_??()
  10323. // evaluate their arguments, which is undefined.
  10324. //
  10325. // 5. These macros evaluate their arguments exactly once.
  10326. //
  10327. // Examples:
  10328. //
  10329. // EXPECT_NE(Foo(), 5);
  10330. // EXPECT_EQ(a_pointer, NULL);
  10331. // ASSERT_LT(i, array_size);
  10332. // ASSERT_GT(records.size(), 0) << "There is no record left.";
  10333. #define EXPECT_EQ(val1, val2) \
  10334. EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
  10335. #define EXPECT_NE(val1, val2) \
  10336. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
  10337. #define EXPECT_LE(val1, val2) \
  10338. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
  10339. #define EXPECT_LT(val1, val2) \
  10340. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
  10341. #define EXPECT_GE(val1, val2) \
  10342. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
  10343. #define EXPECT_GT(val1, val2) \
  10344. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
  10345. #define GTEST_ASSERT_EQ(val1, val2) \
  10346. ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
  10347. #define GTEST_ASSERT_NE(val1, val2) \
  10348. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
  10349. #define GTEST_ASSERT_LE(val1, val2) \
  10350. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
  10351. #define GTEST_ASSERT_LT(val1, val2) \
  10352. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
  10353. #define GTEST_ASSERT_GE(val1, val2) \
  10354. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
  10355. #define GTEST_ASSERT_GT(val1, val2) \
  10356. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
  10357. // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
  10358. // ASSERT_XY(), which clashes with some users' own code.
  10359. #if !GTEST_DONT_DEFINE_ASSERT_EQ
  10360. # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
  10361. #endif
  10362. #if !GTEST_DONT_DEFINE_ASSERT_NE
  10363. # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
  10364. #endif
  10365. #if !GTEST_DONT_DEFINE_ASSERT_LE
  10366. # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
  10367. #endif
  10368. #if !GTEST_DONT_DEFINE_ASSERT_LT
  10369. # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
  10370. #endif
  10371. #if !GTEST_DONT_DEFINE_ASSERT_GE
  10372. # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
  10373. #endif
  10374. #if !GTEST_DONT_DEFINE_ASSERT_GT
  10375. # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
  10376. #endif
  10377. // C-string Comparisons. All tests treat NULL and any non-NULL string
  10378. // as different. Two NULLs are equal.
  10379. //
  10380. // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
  10381. // * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2
  10382. // * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
  10383. // * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
  10384. //
  10385. // For wide or narrow string objects, you can use the
  10386. // {ASSERT|EXPECT}_??() macros.
  10387. //
  10388. // Don't depend on the order in which the arguments are evaluated,
  10389. // which is undefined.
  10390. //
  10391. // These macros evaluate their arguments exactly once.
  10392. #define EXPECT_STREQ(s1, s2) \
  10393. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
  10394. #define EXPECT_STRNE(s1, s2) \
  10395. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
  10396. #define EXPECT_STRCASEEQ(s1, s2) \
  10397. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
  10398. #define EXPECT_STRCASENE(s1, s2)\
  10399. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
  10400. #define ASSERT_STREQ(s1, s2) \
  10401. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
  10402. #define ASSERT_STRNE(s1, s2) \
  10403. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
  10404. #define ASSERT_STRCASEEQ(s1, s2) \
  10405. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
  10406. #define ASSERT_STRCASENE(s1, s2)\
  10407. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
  10408. // Macros for comparing floating-point numbers.
  10409. //
  10410. // * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):
  10411. // Tests that two float values are almost equal.
  10412. // * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):
  10413. // Tests that two double values are almost equal.
  10414. // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
  10415. // Tests that v1 and v2 are within the given distance to each other.
  10416. //
  10417. // Google Test uses ULP-based comparison to automatically pick a default
  10418. // error bound that is appropriate for the operands. See the
  10419. // FloatingPoint template class in gtest-internal.h if you are
  10420. // interested in the implementation details.
  10421. #define EXPECT_FLOAT_EQ(val1, val2)\
  10422. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
  10423. val1, val2)
  10424. #define EXPECT_DOUBLE_EQ(val1, val2)\
  10425. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
  10426. val1, val2)
  10427. #define ASSERT_FLOAT_EQ(val1, val2)\
  10428. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
  10429. val1, val2)
  10430. #define ASSERT_DOUBLE_EQ(val1, val2)\
  10431. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
  10432. val1, val2)
  10433. #define EXPECT_NEAR(val1, val2, abs_error)\
  10434. EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
  10435. val1, val2, abs_error)
  10436. #define ASSERT_NEAR(val1, val2, abs_error)\
  10437. ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
  10438. val1, val2, abs_error)
  10439. // These predicate format functions work on floating-point values, and
  10440. // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
  10441. //
  10442. // EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
  10443. // Asserts that val1 is less than, or almost equal to, val2. Fails
  10444. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  10445. GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
  10446. float val1, float val2);
  10447. GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
  10448. double val1, double val2);
  10449. #if GTEST_OS_WINDOWS
  10450. // Macros that test for HRESULT failure and success, these are only useful
  10451. // on Windows, and rely on Windows SDK macros and APIs to compile.
  10452. //
  10453. // * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
  10454. //
  10455. // When expr unexpectedly fails or succeeds, Google Test prints the
  10456. // expected result and the actual result with both a human-readable
  10457. // string representation of the error, if available, as well as the
  10458. // hex result code.
  10459. # define EXPECT_HRESULT_SUCCEEDED(expr) \
  10460. EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
  10461. # define ASSERT_HRESULT_SUCCEEDED(expr) \
  10462. ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
  10463. # define EXPECT_HRESULT_FAILED(expr) \
  10464. EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
  10465. # define ASSERT_HRESULT_FAILED(expr) \
  10466. ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
  10467. #endif // GTEST_OS_WINDOWS
  10468. // Macros that execute statement and check that it doesn't generate new fatal
  10469. // failures in the current thread.
  10470. //
  10471. // * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
  10472. //
  10473. // Examples:
  10474. //
  10475. // EXPECT_NO_FATAL_FAILURE(Process());
  10476. // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
  10477. //
  10478. #define ASSERT_NO_FATAL_FAILURE(statement) \
  10479. GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
  10480. #define EXPECT_NO_FATAL_FAILURE(statement) \
  10481. GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
  10482. // Causes a trace (including the given source file path and line number,
  10483. // and the given message) to be included in every test failure message generated
  10484. // by code in the scope of the lifetime of an instance of this class. The effect
  10485. // is undone with the destruction of the instance.
  10486. //
  10487. // The message argument can be anything streamable to std::ostream.
  10488. //
  10489. // Example:
  10490. // testing::ScopedTrace trace("file.cc", 123, "message");
  10491. //
  10492. class GTEST_API_ ScopedTrace {
  10493. public:
  10494. // The c'tor pushes the given source file location and message onto
  10495. // a trace stack maintained by Google Test.
  10496. // Template version. Uses Message() to convert the values into strings.
  10497. // Slow, but flexible.
  10498. template <typename T>
  10499. ScopedTrace(const char* file, int line, const T& message) {
  10500. PushTrace(file, line, (Message() << message).GetString());
  10501. }
  10502. // Optimize for some known types.
  10503. ScopedTrace(const char* file, int line, const char* message) {
  10504. PushTrace(file, line, message ? message : "(null)");
  10505. }
  10506. ScopedTrace(const char* file, int line, const std::string& message) {
  10507. PushTrace(file, line, message);
  10508. }
  10509. // The d'tor pops the info pushed by the c'tor.
  10510. //
  10511. // Note that the d'tor is not virtual in order to be efficient.
  10512. // Don't inherit from ScopedTrace!
  10513. ~ScopedTrace();
  10514. private:
  10515. void PushTrace(const char* file, int line, std::string message);
  10516. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
  10517. } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
  10518. // c'tor and d'tor. Therefore it doesn't
  10519. // need to be used otherwise.
  10520. // Causes a trace (including the source file path, the current line
  10521. // number, and the given message) to be included in every test failure
  10522. // message generated by code in the current scope. The effect is
  10523. // undone when the control leaves the current scope.
  10524. //
  10525. // The message argument can be anything streamable to std::ostream.
  10526. //
  10527. // In the implementation, we include the current line number as part
  10528. // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
  10529. // to appear in the same block - as long as they are on different
  10530. // lines.
  10531. //
  10532. // Assuming that each thread maintains its own stack of traces.
  10533. // Therefore, a SCOPED_TRACE() would (correctly) only affect the
  10534. // assertions in its own thread.
  10535. #define SCOPED_TRACE(message) \
  10536. ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
  10537. __FILE__, __LINE__, (message))
  10538. // Compile-time assertion for type equality.
  10539. // StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2
  10540. // are the same type. The value it returns is not interesting.
  10541. //
  10542. // Instead of making StaticAssertTypeEq a class template, we make it a
  10543. // function template that invokes a helper class template. This
  10544. // prevents a user from misusing StaticAssertTypeEq<T1, T2> by
  10545. // defining objects of that type.
  10546. //
  10547. // CAVEAT:
  10548. //
  10549. // When used inside a method of a class template,
  10550. // StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
  10551. // instantiated. For example, given:
  10552. //
  10553. // template <typename T> class Foo {
  10554. // public:
  10555. // void Bar() { testing::StaticAssertTypeEq<int, T>(); }
  10556. // };
  10557. //
  10558. // the code:
  10559. //
  10560. // void Test1() { Foo<bool> foo; }
  10561. //
  10562. // will NOT generate a compiler error, as Foo<bool>::Bar() is never
  10563. // actually instantiated. Instead, you need:
  10564. //
  10565. // void Test2() { Foo<bool> foo; foo.Bar(); }
  10566. //
  10567. // to cause a compiler error.
  10568. template <typename T1, typename T2>
  10569. constexpr bool StaticAssertTypeEq() noexcept {
  10570. static_assert(std::is_same<T1, T2>::value, "T1 and T2 are not the same type");
  10571. return true;
  10572. }
  10573. // Defines a test.
  10574. //
  10575. // The first parameter is the name of the test suite, and the second
  10576. // parameter is the name of the test within the test suite.
  10577. //
  10578. // The convention is to end the test suite name with "Test". For
  10579. // example, a test suite for the Foo class can be named FooTest.
  10580. //
  10581. // Test code should appear between braces after an invocation of
  10582. // this macro. Example:
  10583. //
  10584. // TEST(FooTest, InitializesCorrectly) {
  10585. // Foo foo;
  10586. // EXPECT_TRUE(foo.StatusIsOK());
  10587. // }
  10588. // Note that we call GetTestTypeId() instead of GetTypeId<
  10589. // ::testing::Test>() here to get the type ID of testing::Test. This
  10590. // is to work around a suspected linker bug when using Google Test as
  10591. // a framework on Mac OS X. The bug causes GetTypeId<
  10592. // ::testing::Test>() to return different values depending on whether
  10593. // the call is from the Google Test framework itself or from user test
  10594. // code. GetTestTypeId() is guaranteed to always return the same
  10595. // value, as it always calls GetTypeId<>() from the Google Test
  10596. // framework.
  10597. #define GTEST_TEST(test_suite_name, test_name) \
  10598. GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \
  10599. ::testing::internal::GetTestTypeId())
  10600. // Define this macro to 1 to omit the definition of TEST(), which
  10601. // is a generic name and clashes with some other libraries.
  10602. #if !GTEST_DONT_DEFINE_TEST
  10603. #define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
  10604. #endif
  10605. // Defines a test that uses a test fixture.
  10606. //
  10607. // The first parameter is the name of the test fixture class, which
  10608. // also doubles as the test suite name. The second parameter is the
  10609. // name of the test within the test suite.
  10610. //
  10611. // A test fixture class must be declared earlier. The user should put
  10612. // the test code between braces after using this macro. Example:
  10613. //
  10614. // class FooTest : public testing::Test {
  10615. // protected:
  10616. // void SetUp() override { b_.AddElement(3); }
  10617. //
  10618. // Foo a_;
  10619. // Foo b_;
  10620. // };
  10621. //
  10622. // TEST_F(FooTest, InitializesCorrectly) {
  10623. // EXPECT_TRUE(a_.StatusIsOK());
  10624. // }
  10625. //
  10626. // TEST_F(FooTest, ReturnsElementCountCorrectly) {
  10627. // EXPECT_EQ(a_.size(), 0);
  10628. // EXPECT_EQ(b_.size(), 1);
  10629. // }
  10630. //
  10631. // GOOGLETEST_CM0011 DO NOT DELETE
  10632. #if !GTEST_DONT_DEFINE_TEST
  10633. #define TEST_F(test_fixture, test_name)\
  10634. GTEST_TEST_(test_fixture, test_name, test_fixture, \
  10635. ::testing::internal::GetTypeId<test_fixture>())
  10636. #endif // !GTEST_DONT_DEFINE_TEST
  10637. // Returns a path to temporary directory.
  10638. // Tries to determine an appropriate directory for the platform.
  10639. GTEST_API_ std::string TempDir();
  10640. #ifdef _MSC_VER
  10641. # pragma warning(pop)
  10642. #endif
  10643. // Dynamically registers a test with the framework.
  10644. //
  10645. // This is an advanced API only to be used when the `TEST` macros are
  10646. // insufficient. The macros should be preferred when possible, as they avoid
  10647. // most of the complexity of calling this function.
  10648. //
  10649. // The `factory` argument is a factory callable (move-constructible) object or
  10650. // function pointer that creates a new instance of the Test object. It
  10651. // handles ownership to the caller. The signature of the callable is
  10652. // `Fixture*()`, where `Fixture` is the test fixture class for the test. All
  10653. // tests registered with the same `test_suite_name` must return the same
  10654. // fixture type. This is checked at runtime.
  10655. //
  10656. // The framework will infer the fixture class from the factory and will call
  10657. // the `SetUpTestSuite` and `TearDownTestSuite` for it.
  10658. //
  10659. // Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is
  10660. // undefined.
  10661. //
  10662. // Use case example:
  10663. //
  10664. // class MyFixture : public ::testing::Test {
  10665. // public:
  10666. // // All of these optional, just like in regular macro usage.
  10667. // static void SetUpTestSuite() { ... }
  10668. // static void TearDownTestSuite() { ... }
  10669. // void SetUp() override { ... }
  10670. // void TearDown() override { ... }
  10671. // };
  10672. //
  10673. // class MyTest : public MyFixture {
  10674. // public:
  10675. // explicit MyTest(int data) : data_(data) {}
  10676. // void TestBody() override { ... }
  10677. //
  10678. // private:
  10679. // int data_;
  10680. // };
  10681. //
  10682. // void RegisterMyTests(const std::vector<int>& values) {
  10683. // for (int v : values) {
  10684. // ::testing::RegisterTest(
  10685. // "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
  10686. // std::to_string(v).c_str(),
  10687. // __FILE__, __LINE__,
  10688. // // Important to use the fixture type as the return type here.
  10689. // [=]() -> MyFixture* { return new MyTest(v); });
  10690. // }
  10691. // }
  10692. // ...
  10693. // int main(int argc, char** argv) {
  10694. // std::vector<int> values_to_test = LoadValuesFromConfig();
  10695. // RegisterMyTests(values_to_test);
  10696. // ...
  10697. // return RUN_ALL_TESTS();
  10698. // }
  10699. //
  10700. template <int&... ExplicitParameterBarrier, typename Factory>
  10701. TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
  10702. const char* type_param, const char* value_param,
  10703. const char* file, int line, Factory factory) {
  10704. using TestT = typename std::remove_pointer<decltype(factory())>::type;
  10705. class FactoryImpl : public internal::TestFactoryBase {
  10706. public:
  10707. explicit FactoryImpl(Factory f) : factory_(std::move(f)) {}
  10708. Test* CreateTest() override { return factory_(); }
  10709. private:
  10710. Factory factory_;
  10711. };
  10712. return internal::MakeAndRegisterTestInfo(
  10713. test_suite_name, test_name, type_param, value_param,
  10714. internal::CodeLocation(file, line), internal::GetTypeId<TestT>(),
  10715. internal::SuiteApiResolver<TestT>::GetSetUpCaseOrSuite(file, line),
  10716. internal::SuiteApiResolver<TestT>::GetTearDownCaseOrSuite(file, line),
  10717. new FactoryImpl{std::move(factory)});
  10718. }
  10719. } // namespace testing
  10720. // Use this function in main() to run all tests. It returns 0 if all
  10721. // tests are successful, or 1 otherwise.
  10722. //
  10723. // RUN_ALL_TESTS() should be invoked after the command line has been
  10724. // parsed by InitGoogleTest().
  10725. //
  10726. // This function was formerly a macro; thus, it is in the global
  10727. // namespace and has an all-caps name.
  10728. int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
  10729. inline int RUN_ALL_TESTS() {
  10730. return ::testing::UnitTest::GetInstance()->Run();
  10731. }
  10732. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  10733. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_H_