catch.hpp 642 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976
  1. /*
  2. * Catch v2.13.10
  3. * Generated: 2022-10-16 11:01:23.452308
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2022 Two Blue Cubes Ltd. All rights reserved.
  7. *
  8. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  9. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  10. */
  11. #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  12. #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  13. // start catch.hpp
  14. #define CATCH_VERSION_MAJOR 2
  15. #define CATCH_VERSION_MINOR 13
  16. #define CATCH_VERSION_PATCH 10
  17. #ifdef __clang__
  18. # pragma clang system_header
  19. #elif defined __GNUC__
  20. # pragma GCC system_header
  21. #endif
  22. // start catch_suppress_warnings.h
  23. #ifdef __clang__
  24. # ifdef __ICC // icpc defines the __clang__ macro
  25. # pragma warning(push)
  26. # pragma warning(disable: 161 1682)
  27. # else // __ICC
  28. # pragma clang diagnostic push
  29. # pragma clang diagnostic ignored "-Wpadded"
  30. # pragma clang diagnostic ignored "-Wswitch-enum"
  31. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  32. # endif
  33. #elif defined __GNUC__
  34. // Because REQUIREs trigger GCC's -Wparentheses, and because still
  35. // supported version of g++ have only buggy support for _Pragmas,
  36. // Wparentheses have to be suppressed globally.
  37. # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
  38. # pragma GCC diagnostic push
  39. # pragma GCC diagnostic ignored "-Wunused-variable"
  40. # pragma GCC diagnostic ignored "-Wpadded"
  41. #endif
  42. // end catch_suppress_warnings.h
  43. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  44. # define CATCH_IMPL
  45. # define CATCH_CONFIG_ALL_PARTS
  46. #endif
  47. // In the impl file, we want to have access to all parts of the headers
  48. // Can also be used to sanely support PCHs
  49. #if defined(CATCH_CONFIG_ALL_PARTS)
  50. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  51. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  52. # undef CATCH_CONFIG_DISABLE_MATCHERS
  53. # endif
  54. # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  55. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  56. # endif
  57. #endif
  58. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  59. // start catch_platform.h
  60. // See e.g.:
  61. // https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html
  62. #ifdef __APPLE__
  63. # include <TargetConditionals.h>
  64. # if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \
  65. (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1)
  66. # define CATCH_PLATFORM_MAC
  67. # elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1)
  68. # define CATCH_PLATFORM_IPHONE
  69. # endif
  70. #elif defined(linux) || defined(__linux) || defined(__linux__)
  71. # define CATCH_PLATFORM_LINUX
  72. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
  73. # define CATCH_PLATFORM_WINDOWS
  74. #endif
  75. // end catch_platform.h
  76. #ifdef CATCH_IMPL
  77. # ifndef CLARA_CONFIG_MAIN
  78. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  79. # define CLARA_CONFIG_MAIN
  80. # endif
  81. #endif
  82. // start catch_user_interfaces.h
  83. namespace Catch {
  84. unsigned int rngSeed();
  85. }
  86. // end catch_user_interfaces.h
  87. // start catch_tag_alias_autoregistrar.h
  88. // start catch_common.h
  89. // start catch_compiler_capabilities.h
  90. // Detect a number of compiler features - by compiler
  91. // The following features are defined:
  92. //
  93. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  94. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  95. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  96. // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
  97. // ****************
  98. // Note to maintainers: if new toggles are added please document them
  99. // in configuration.md, too
  100. // ****************
  101. // In general each macro has a _NO_<feature name> form
  102. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  103. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  104. // can be combined, en-mass, with the _NO_ forms later.
  105. #ifdef __cplusplus
  106. # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
  107. # define CATCH_CPP14_OR_GREATER
  108. # endif
  109. # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
  110. # define CATCH_CPP17_OR_GREATER
  111. # endif
  112. #endif
  113. // Only GCC compiler should be used in this block, so other compilers trying to
  114. // mask themselves as GCC should be ignored.
  115. #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__)
  116. # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" )
  117. # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" )
  118. # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
  119. #endif
  120. #if defined(__clang__)
  121. # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" )
  122. # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" )
  123. // As of this writing, IBM XL's implementation of __builtin_constant_p has a bug
  124. // which results in calls to destructors being emitted for each temporary,
  125. // without a matching initialization. In practice, this can result in something
  126. // like `std::string::~string` being called on an uninitialized value.
  127. //
  128. // For example, this code will likely segfault under IBM XL:
  129. // ```
  130. // REQUIRE(std::string("12") + "34" == "1234")
  131. // ```
  132. //
  133. // Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented.
  134. # if !defined(__ibmxl__) && !defined(__CUDACC__)
  135. # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */
  136. # endif
  137. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  138. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  139. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  140. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  141. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  142. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  143. _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
  144. # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  145. _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
  146. # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  147. _Pragma( "clang diagnostic ignored \"-Wunused-template\"" )
  148. #endif // __clang__
  149. ////////////////////////////////////////////////////////////////////////////////
  150. // Assume that non-Windows platforms support posix signals by default
  151. #if !defined(CATCH_PLATFORM_WINDOWS)
  152. #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
  153. #endif
  154. ////////////////////////////////////////////////////////////////////////////////
  155. // We know some environments not to support full POSIX signals
  156. #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
  157. #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  158. #endif
  159. #ifdef __OS400__
  160. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  161. # define CATCH_CONFIG_COLOUR_NONE
  162. #endif
  163. ////////////////////////////////////////////////////////////////////////////////
  164. // Android somehow still does not support std::to_string
  165. #if defined(__ANDROID__)
  166. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  167. # define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
  168. #endif
  169. ////////////////////////////////////////////////////////////////////////////////
  170. // Not all Windows environments support SEH properly
  171. #if defined(__MINGW32__)
  172. # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  173. #endif
  174. ////////////////////////////////////////////////////////////////////////////////
  175. // PS4
  176. #if defined(__ORBIS__)
  177. # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
  178. #endif
  179. ////////////////////////////////////////////////////////////////////////////////
  180. // Cygwin
  181. #ifdef __CYGWIN__
  182. // Required for some versions of Cygwin to declare gettimeofday
  183. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  184. # define _BSD_SOURCE
  185. // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
  186. // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
  187. # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
  188. && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
  189. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  190. # endif
  191. #endif // __CYGWIN__
  192. ////////////////////////////////////////////////////////////////////////////////
  193. // Visual C++
  194. #if defined(_MSC_VER)
  195. // Universal Windows platform does not support SEH
  196. // Or console colours (or console at all...)
  197. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  198. # define CATCH_CONFIG_COLOUR_NONE
  199. # else
  200. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  201. # endif
  202. # if !defined(__clang__) // Handle Clang masquerading for msvc
  203. // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
  204. // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
  205. // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
  206. # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
  207. # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  208. # endif // MSVC_TRADITIONAL
  209. // Only do this if we're not using clang on Windows, which uses `diagnostic push` & `diagnostic pop`
  210. # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
  211. # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) )
  212. # endif // __clang__
  213. #endif // _MSC_VER
  214. #if defined(_REENTRANT) || defined(_MSC_VER)
  215. // Enable async processing, as -pthread is specified or no additional linking is required
  216. # define CATCH_INTERNAL_CONFIG_USE_ASYNC
  217. #endif // _MSC_VER
  218. ////////////////////////////////////////////////////////////////////////////////
  219. // Check if we are compiled with -fno-exceptions or equivalent
  220. #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
  221. # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
  222. #endif
  223. ////////////////////////////////////////////////////////////////////////////////
  224. // DJGPP
  225. #ifdef __DJGPP__
  226. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  227. #endif // __DJGPP__
  228. ////////////////////////////////////////////////////////////////////////////////
  229. // Embarcadero C++Build
  230. #if defined(__BORLANDC__)
  231. #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
  232. #endif
  233. ////////////////////////////////////////////////////////////////////////////////
  234. // Use of __COUNTER__ is suppressed during code analysis in
  235. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  236. // handled by it.
  237. // Otherwise all supported compilers support COUNTER macro,
  238. // but user still might want to turn it off
  239. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  240. #define CATCH_INTERNAL_CONFIG_COUNTER
  241. #endif
  242. ////////////////////////////////////////////////////////////////////////////////
  243. // RTX is a special version of Windows that is real time.
  244. // This means that it is detected as Windows, but does not provide
  245. // the same set of capabilities as real Windows does.
  246. #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
  247. #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  248. #define CATCH_INTERNAL_CONFIG_NO_ASYNC
  249. #define CATCH_CONFIG_COLOUR_NONE
  250. #endif
  251. #if !defined(_GLIBCXX_USE_C99_MATH_TR1)
  252. #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
  253. #endif
  254. // Various stdlib support checks that require __has_include
  255. #if defined(__has_include)
  256. // Check if string_view is available and usable
  257. #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
  258. # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
  259. #endif
  260. // Check if optional is available and usable
  261. # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  262. # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
  263. # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  264. // Check if byte is available and usable
  265. # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
  266. # include <cstddef>
  267. # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0)
  268. # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
  269. # endif
  270. # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
  271. // Check if variant is available and usable
  272. # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  273. # if defined(__clang__) && (__clang_major__ < 8)
  274. // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
  275. // fix should be in clang 8, workaround in libstdc++ 8.2
  276. # include <ciso646>
  277. # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  278. # define CATCH_CONFIG_NO_CPP17_VARIANT
  279. # else
  280. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  281. # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  282. # else
  283. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  284. # endif // defined(__clang__) && (__clang_major__ < 8)
  285. # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  286. #endif // defined(__has_include)
  287. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  288. # define CATCH_CONFIG_COUNTER
  289. #endif
  290. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
  291. # define CATCH_CONFIG_WINDOWS_SEH
  292. #endif
  293. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  294. #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
  295. # define CATCH_CONFIG_POSIX_SIGNALS
  296. #endif
  297. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  298. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  299. # define CATCH_CONFIG_WCHAR
  300. #endif
  301. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  302. # define CATCH_CONFIG_CPP11_TO_STRING
  303. #endif
  304. #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
  305. # define CATCH_CONFIG_CPP17_OPTIONAL
  306. #endif
  307. #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
  308. # define CATCH_CONFIG_CPP17_STRING_VIEW
  309. #endif
  310. #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
  311. # define CATCH_CONFIG_CPP17_VARIANT
  312. #endif
  313. #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
  314. # define CATCH_CONFIG_CPP17_BYTE
  315. #endif
  316. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  317. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  318. #endif
  319. #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
  320. # define CATCH_CONFIG_NEW_CAPTURE
  321. #endif
  322. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  323. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  324. #endif
  325. #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  326. # define CATCH_CONFIG_POLYFILL_ISNAN
  327. #endif
  328. #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
  329. # define CATCH_CONFIG_USE_ASYNC
  330. #endif
  331. #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
  332. # define CATCH_CONFIG_ANDROID_LOGWRITE
  333. #endif
  334. #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  335. # define CATCH_CONFIG_GLOBAL_NEXTAFTER
  336. #endif
  337. // Even if we do not think the compiler has that warning, we still have
  338. // to provide a macro that can be used by the code.
  339. #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
  340. # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
  341. #endif
  342. #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
  343. # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  344. #endif
  345. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  346. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  347. #endif
  348. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  349. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  350. #endif
  351. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  352. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  353. #endif
  354. #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
  355. # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
  356. #endif
  357. // The goal of this macro is to avoid evaluation of the arguments, but
  358. // still have the compiler warn on problems inside...
  359. #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
  360. # define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
  361. #endif
  362. #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
  363. # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
  364. #elif defined(__clang__) && (__clang_major__ < 5)
  365. # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
  366. #endif
  367. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
  368. # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
  369. #endif
  370. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  371. #define CATCH_TRY if ((true))
  372. #define CATCH_CATCH_ALL if ((false))
  373. #define CATCH_CATCH_ANON(type) if ((false))
  374. #else
  375. #define CATCH_TRY try
  376. #define CATCH_CATCH_ALL catch (...)
  377. #define CATCH_CATCH_ANON(type) catch (type)
  378. #endif
  379. #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
  380. #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  381. #endif
  382. // end catch_compiler_capabilities.h
  383. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  384. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  385. #ifdef CATCH_CONFIG_COUNTER
  386. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  387. #else
  388. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  389. #endif
  390. #include <iosfwd>
  391. #include <string>
  392. #include <cstdint>
  393. // We need a dummy global operator<< so we can bring it into Catch namespace later
  394. struct Catch_global_namespace_dummy {};
  395. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  396. namespace Catch {
  397. struct CaseSensitive { enum Choice {
  398. Yes,
  399. No
  400. }; };
  401. class NonCopyable {
  402. NonCopyable( NonCopyable const& ) = delete;
  403. NonCopyable( NonCopyable && ) = delete;
  404. NonCopyable& operator = ( NonCopyable const& ) = delete;
  405. NonCopyable& operator = ( NonCopyable && ) = delete;
  406. protected:
  407. NonCopyable();
  408. virtual ~NonCopyable();
  409. };
  410. struct SourceLineInfo {
  411. SourceLineInfo() = delete;
  412. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  413. : file( _file ),
  414. line( _line )
  415. {}
  416. SourceLineInfo( SourceLineInfo const& other ) = default;
  417. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  418. SourceLineInfo( SourceLineInfo&& ) noexcept = default;
  419. SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
  420. bool empty() const noexcept { return file[0] == '\0'; }
  421. bool operator == ( SourceLineInfo const& other ) const noexcept;
  422. bool operator < ( SourceLineInfo const& other ) const noexcept;
  423. char const* file;
  424. std::size_t line;
  425. };
  426. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  427. // Bring in operator<< from global namespace into Catch namespace
  428. // This is necessary because the overload of operator<< above makes
  429. // lookup stop at namespace Catch
  430. using ::operator<<;
  431. // Use this in variadic streaming macros to allow
  432. // >> +StreamEndStop
  433. // as well as
  434. // >> stuff +StreamEndStop
  435. struct StreamEndStop {
  436. std::string operator+() const;
  437. };
  438. template<typename T>
  439. T const& operator + ( T const& value, StreamEndStop ) {
  440. return value;
  441. }
  442. }
  443. #define CATCH_INTERNAL_LINEINFO \
  444. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  445. // end catch_common.h
  446. namespace Catch {
  447. struct RegistrarForTagAliases {
  448. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  449. };
  450. } // end namespace Catch
  451. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  452. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  453. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  454. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  455. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  456. // end catch_tag_alias_autoregistrar.h
  457. // start catch_test_registry.h
  458. // start catch_interfaces_testcase.h
  459. #include <vector>
  460. namespace Catch {
  461. class TestSpec;
  462. struct ITestInvoker {
  463. virtual void invoke () const = 0;
  464. virtual ~ITestInvoker();
  465. };
  466. class TestCase;
  467. struct IConfig;
  468. struct ITestCaseRegistry {
  469. virtual ~ITestCaseRegistry();
  470. virtual std::vector<TestCase> const& getAllTests() const = 0;
  471. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  472. };
  473. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  474. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  475. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  476. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  477. }
  478. // end catch_interfaces_testcase.h
  479. // start catch_stringref.h
  480. #include <cstddef>
  481. #include <string>
  482. #include <iosfwd>
  483. #include <cassert>
  484. namespace Catch {
  485. /// A non-owning string class (similar to the forthcoming std::string_view)
  486. /// Note that, because a StringRef may be a substring of another string,
  487. /// it may not be null terminated.
  488. class StringRef {
  489. public:
  490. using size_type = std::size_t;
  491. using const_iterator = const char*;
  492. private:
  493. static constexpr char const* const s_empty = "";
  494. char const* m_start = s_empty;
  495. size_type m_size = 0;
  496. public: // construction
  497. constexpr StringRef() noexcept = default;
  498. StringRef( char const* rawChars ) noexcept;
  499. constexpr StringRef( char const* rawChars, size_type size ) noexcept
  500. : m_start( rawChars ),
  501. m_size( size )
  502. {}
  503. StringRef( std::string const& stdString ) noexcept
  504. : m_start( stdString.c_str() ),
  505. m_size( stdString.size() )
  506. {}
  507. explicit operator std::string() const {
  508. return std::string(m_start, m_size);
  509. }
  510. public: // operators
  511. auto operator == ( StringRef const& other ) const noexcept -> bool;
  512. auto operator != (StringRef const& other) const noexcept -> bool {
  513. return !(*this == other);
  514. }
  515. auto operator[] ( size_type index ) const noexcept -> char {
  516. assert(index < m_size);
  517. return m_start[index];
  518. }
  519. public: // named queries
  520. constexpr auto empty() const noexcept -> bool {
  521. return m_size == 0;
  522. }
  523. constexpr auto size() const noexcept -> size_type {
  524. return m_size;
  525. }
  526. // Returns the current start pointer. If the StringRef is not
  527. // null-terminated, throws std::domain_exception
  528. auto c_str() const -> char const*;
  529. public: // substrings and searches
  530. // Returns a substring of [start, start + length).
  531. // If start + length > size(), then the substring is [start, size()).
  532. // If start > size(), then the substring is empty.
  533. auto substr( size_type start, size_type length ) const noexcept -> StringRef;
  534. // Returns the current start pointer. May not be null-terminated.
  535. auto data() const noexcept -> char const*;
  536. constexpr auto isNullTerminated() const noexcept -> bool {
  537. return m_start[m_size] == '\0';
  538. }
  539. public: // iterators
  540. constexpr const_iterator begin() const { return m_start; }
  541. constexpr const_iterator end() const { return m_start + m_size; }
  542. };
  543. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  544. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  545. constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  546. return StringRef( rawChars, size );
  547. }
  548. } // namespace Catch
  549. constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
  550. return Catch::StringRef( rawChars, size );
  551. }
  552. // end catch_stringref.h
  553. // start catch_preprocessor.hpp
  554. #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
  555. #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
  556. #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
  557. #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
  558. #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
  559. #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
  560. #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  561. #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
  562. // MSVC needs more evaluations
  563. #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
  564. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
  565. #else
  566. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
  567. #endif
  568. #define CATCH_REC_END(...)
  569. #define CATCH_REC_OUT
  570. #define CATCH_EMPTY()
  571. #define CATCH_DEFER(id) id CATCH_EMPTY()
  572. #define CATCH_REC_GET_END2() 0, CATCH_REC_END
  573. #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
  574. #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
  575. #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
  576. #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
  577. #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
  578. #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  579. #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
  580. #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  581. #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
  582. #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )
  583. #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
  584. // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
  585. // and passes userdata as the first parameter to each invocation,
  586. // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
  587. #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  588. #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  589. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  590. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  591. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  592. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  593. #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
  594. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  595. #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
  596. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
  597. #else
  598. // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  599. #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
  600. #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
  601. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
  602. #endif
  603. #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
  604. #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
  605. #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
  606. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  607. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
  608. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
  609. #else
  610. #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
  611. #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
  612. #endif
  613. #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
  614. CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
  615. #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
  616. #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
  617. #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
  618. #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
  619. #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
  620. #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
  621. #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
  622. #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
  623. #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
  624. #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
  625. #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
  626. #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
  627. #define INTERNAL_CATCH_TYPE_GEN\
  628. template<typename...> struct TypeList {};\
  629. template<typename...Ts>\
  630. constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
  631. template<template<typename...> class...> struct TemplateTypeList{};\
  632. template<template<typename...> class...Cs>\
  633. constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\
  634. template<typename...>\
  635. struct append;\
  636. template<typename...>\
  637. struct rewrap;\
  638. template<template<typename...> class, typename...>\
  639. struct create;\
  640. template<template<typename...> class, typename>\
  641. struct convert;\
  642. \
  643. template<typename T> \
  644. struct append<T> { using type = T; };\
  645. template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
  646. struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\
  647. template< template<typename...> class L1, typename...E1, typename...Rest>\
  648. struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\
  649. \
  650. template< template<typename...> class Container, template<typename...> class List, typename...elems>\
  651. struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\
  652. template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
  653. struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\
  654. \
  655. template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
  656. struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\
  657. template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
  658. struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };
  659. #define INTERNAL_CATCH_NTTP_1(signature, ...)\
  660. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
  661. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  662. constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
  663. template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\
  664. template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\
  665. constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \
  666. \
  667. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  668. struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\
  669. template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
  670. struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\
  671. template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
  672. struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };
  673. #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
  674. #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
  675. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  676. static void TestName()
  677. #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
  678. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  679. static void TestName()
  680. #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
  681. #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
  682. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  683. static void TestName()
  684. #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
  685. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  686. static void TestName()
  687. #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
  688. template<typename Type>\
  689. void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
  690. {\
  691. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  692. }
  693. #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
  694. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  695. void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
  696. {\
  697. Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
  698. }
  699. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
  700. template<typename Type>\
  701. void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  702. {\
  703. Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  704. }
  705. #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
  706. template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
  707. void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
  708. {\
  709. Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
  710. }
  711. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
  712. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
  713. template<typename TestType> \
  714. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
  715. void test();\
  716. }
  717. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
  718. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  719. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
  720. void test();\
  721. }
  722. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
  723. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
  724. template<typename TestType> \
  725. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
  726. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
  727. template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
  728. void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
  729. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  730. #define INTERNAL_CATCH_NTTP_0
  731. #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0)
  732. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)
  733. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)
  734. #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)
  735. #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)
  736. #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)
  737. #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)
  738. #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)
  739. #else
  740. #define INTERNAL_CATCH_NTTP_0(signature)
  741. #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__))
  742. #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
  743. #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
  744. #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
  745. #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
  746. #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
  747. #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
  748. #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
  749. #endif
  750. // end catch_preprocessor.hpp
  751. // start catch_meta.hpp
  752. #include <type_traits>
  753. namespace Catch {
  754. template<typename T>
  755. struct always_false : std::false_type {};
  756. template <typename> struct true_given : std::true_type {};
  757. struct is_callable_tester {
  758. template <typename Fun, typename... Args>
  759. true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
  760. template <typename...>
  761. std::false_type static test(...);
  762. };
  763. template <typename T>
  764. struct is_callable;
  765. template <typename Fun, typename... Args>
  766. struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
  767. #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
  768. // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
  769. // replaced with std::invoke_result here.
  770. template <typename Func, typename... U>
  771. using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
  772. #else
  773. // Keep ::type here because we still support C++11
  774. template <typename Func, typename... U>
  775. using FunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type;
  776. #endif
  777. } // namespace Catch
  778. namespace mpl_{
  779. struct na;
  780. }
  781. // end catch_meta.hpp
  782. namespace Catch {
  783. template<typename C>
  784. class TestInvokerAsMethod : public ITestInvoker {
  785. void (C::*m_testAsMethod)();
  786. public:
  787. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  788. void invoke() const override {
  789. C obj;
  790. (obj.*m_testAsMethod)();
  791. }
  792. };
  793. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  794. template<typename C>
  795. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  796. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  797. }
  798. struct NameAndTags {
  799. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  800. StringRef name;
  801. StringRef tags;
  802. };
  803. struct AutoReg : NonCopyable {
  804. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  805. ~AutoReg();
  806. };
  807. } // end namespace Catch
  808. #if defined(CATCH_CONFIG_DISABLE)
  809. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  810. static void TestName()
  811. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  812. namespace{ \
  813. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  814. void test(); \
  815. }; \
  816. } \
  817. void TestName::test()
  818. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
  819. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  820. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  821. namespace{ \
  822. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  823. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  824. } \
  825. } \
  826. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  827. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  828. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  829. INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename TestType, __VA_ARGS__ )
  830. #else
  831. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
  832. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
  833. #endif
  834. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  835. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  836. INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ )
  837. #else
  838. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
  839. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ ) )
  840. #endif
  841. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  842. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  843. INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
  844. #else
  845. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
  846. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
  847. #endif
  848. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  849. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  850. INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
  851. #else
  852. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
  853. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
  854. #endif
  855. #endif
  856. ///////////////////////////////////////////////////////////////////////////////
  857. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  858. static void TestName(); \
  859. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  860. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  861. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  862. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  863. static void TestName()
  864. #define INTERNAL_CATCH_TESTCASE( ... ) \
  865. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), __VA_ARGS__ )
  866. ///////////////////////////////////////////////////////////////////////////////
  867. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  868. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  869. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  870. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  871. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  872. ///////////////////////////////////////////////////////////////////////////////
  873. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  874. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  875. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  876. namespace{ \
  877. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  878. void test(); \
  879. }; \
  880. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  881. } \
  882. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  883. void TestName::test()
  884. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  885. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), ClassName, __VA_ARGS__ )
  886. ///////////////////////////////////////////////////////////////////////////////
  887. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  888. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  889. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  890. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  891. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  892. ///////////////////////////////////////////////////////////////////////////////
  893. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
  894. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  895. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  896. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  897. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  898. INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  899. namespace {\
  900. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  901. INTERNAL_CATCH_TYPE_GEN\
  902. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  903. INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  904. template<typename...Types> \
  905. struct TestName{\
  906. TestName(){\
  907. int index = 0; \
  908. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  909. using expander = int[];\
  910. (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
  911. }\
  912. };\
  913. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  914. TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  915. return 0;\
  916. }();\
  917. }\
  918. }\
  919. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  920. INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
  921. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  922. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  923. INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename TestType, __VA_ARGS__ )
  924. #else
  925. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  926. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
  927. #endif
  928. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  929. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  930. INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ )
  931. #else
  932. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
  933. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ ) )
  934. #endif
  935. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
  936. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  937. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  938. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  939. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  940. template<typename TestType> static void TestFuncName(); \
  941. namespace {\
  942. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
  943. INTERNAL_CATCH_TYPE_GEN \
  944. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
  945. template<typename... Types> \
  946. struct TestName { \
  947. void reg_tests() { \
  948. int index = 0; \
  949. using expander = int[]; \
  950. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  951. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  952. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  953. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */\
  954. } \
  955. }; \
  956. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  957. using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
  958. TestInit t; \
  959. t.reg_tests(); \
  960. return 0; \
  961. }(); \
  962. } \
  963. } \
  964. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  965. template<typename TestType> \
  966. static void TestFuncName()
  967. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  968. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  969. INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename T,__VA_ARGS__)
  970. #else
  971. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  972. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename T, __VA_ARGS__ ) )
  973. #endif
  974. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  975. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  976. INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__)
  977. #else
  978. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
  979. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ ) )
  980. #endif
  981. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
  982. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  983. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  984. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  985. template<typename TestType> static void TestFunc(); \
  986. namespace {\
  987. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
  988. INTERNAL_CATCH_TYPE_GEN\
  989. template<typename... Types> \
  990. struct TestName { \
  991. void reg_tests() { \
  992. int index = 0; \
  993. using expander = int[]; \
  994. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */\
  995. } \
  996. };\
  997. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  998. using TestInit = typename convert<TestName, TmplList>::type; \
  999. TestInit t; \
  1000. t.reg_tests(); \
  1001. return 0; \
  1002. }(); \
  1003. }}\
  1004. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  1005. template<typename TestType> \
  1006. static void TestFunc()
  1007. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
  1008. INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, TmplList )
  1009. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
  1010. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  1011. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1012. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  1013. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  1014. namespace {\
  1015. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  1016. INTERNAL_CATCH_TYPE_GEN\
  1017. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1018. INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
  1019. INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1020. template<typename...Types> \
  1021. struct TestNameClass{\
  1022. TestNameClass(){\
  1023. int index = 0; \
  1024. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
  1025. using expander = int[];\
  1026. (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
  1027. }\
  1028. };\
  1029. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1030. TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
  1031. return 0;\
  1032. }();\
  1033. }\
  1034. }\
  1035. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  1036. INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
  1037. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1038. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  1039. INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
  1040. #else
  1041. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  1042. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
  1043. #endif
  1044. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1045. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1046. INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
  1047. #else
  1048. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
  1049. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
  1050. #endif
  1051. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
  1052. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  1053. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1054. CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
  1055. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  1056. template<typename TestType> \
  1057. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1058. void test();\
  1059. };\
  1060. namespace {\
  1061. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
  1062. INTERNAL_CATCH_TYPE_GEN \
  1063. INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
  1064. template<typename...Types>\
  1065. struct TestNameClass{\
  1066. void reg_tests(){\
  1067. int index = 0;\
  1068. using expander = int[];\
  1069. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  1070. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  1071. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  1072. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */ \
  1073. }\
  1074. };\
  1075. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1076. using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\
  1077. TestInit t;\
  1078. t.reg_tests();\
  1079. return 0;\
  1080. }(); \
  1081. }\
  1082. }\
  1083. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  1084. template<typename TestType> \
  1085. void TestName<TestType>::test()
  1086. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1087. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1088. INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, typename T, __VA_ARGS__ )
  1089. #else
  1090. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  1091. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) )
  1092. #endif
  1093. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  1094. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1095. INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, Signature, __VA_ARGS__ )
  1096. #else
  1097. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
  1098. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) )
  1099. #endif
  1100. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
  1101. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  1102. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1103. CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
  1104. template<typename TestType> \
  1105. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  1106. void test();\
  1107. };\
  1108. namespace {\
  1109. namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
  1110. INTERNAL_CATCH_TYPE_GEN\
  1111. template<typename...Types>\
  1112. struct TestNameClass{\
  1113. void reg_tests(){\
  1114. int index = 0;\
  1115. using expander = int[];\
  1116. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */ \
  1117. }\
  1118. };\
  1119. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  1120. using TestInit = typename convert<TestNameClass, TmplList>::type;\
  1121. TestInit t;\
  1122. t.reg_tests();\
  1123. return 0;\
  1124. }(); \
  1125. }}\
  1126. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  1127. template<typename TestType> \
  1128. void TestName<TestType>::test()
  1129. #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
  1130. INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, TmplList )
  1131. // end catch_test_registry.h
  1132. // start catch_capture.hpp
  1133. // start catch_assertionhandler.h
  1134. // start catch_assertioninfo.h
  1135. // start catch_result_type.h
  1136. namespace Catch {
  1137. // ResultWas::OfType enum
  1138. struct ResultWas { enum OfType {
  1139. Unknown = -1,
  1140. Ok = 0,
  1141. Info = 1,
  1142. Warning = 2,
  1143. FailureBit = 0x10,
  1144. ExpressionFailed = FailureBit | 1,
  1145. ExplicitFailure = FailureBit | 2,
  1146. Exception = 0x100 | FailureBit,
  1147. ThrewException = Exception | 1,
  1148. DidntThrowException = Exception | 2,
  1149. FatalErrorCondition = 0x200 | FailureBit
  1150. }; };
  1151. bool isOk( ResultWas::OfType resultType );
  1152. bool isJustInfo( int flags );
  1153. // ResultDisposition::Flags enum
  1154. struct ResultDisposition { enum Flags {
  1155. Normal = 0x01,
  1156. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  1157. FalseTest = 0x04, // Prefix expression with !
  1158. SuppressFail = 0x08 // Failures are reported but do not fail the test
  1159. }; };
  1160. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  1161. bool shouldContinueOnFailure( int flags );
  1162. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  1163. bool shouldSuppressFailure( int flags );
  1164. } // end namespace Catch
  1165. // end catch_result_type.h
  1166. namespace Catch {
  1167. struct AssertionInfo
  1168. {
  1169. StringRef macroName;
  1170. SourceLineInfo lineInfo;
  1171. StringRef capturedExpression;
  1172. ResultDisposition::Flags resultDisposition;
  1173. // We want to delete this constructor but a compiler bug in 4.8 means
  1174. // the struct is then treated as non-aggregate
  1175. //AssertionInfo() = delete;
  1176. };
  1177. } // end namespace Catch
  1178. // end catch_assertioninfo.h
  1179. // start catch_decomposer.h
  1180. // start catch_tostring.h
  1181. #include <vector>
  1182. #include <cstddef>
  1183. #include <type_traits>
  1184. #include <string>
  1185. // start catch_stream.h
  1186. #include <iosfwd>
  1187. #include <cstddef>
  1188. #include <ostream>
  1189. namespace Catch {
  1190. std::ostream& cout();
  1191. std::ostream& cerr();
  1192. std::ostream& clog();
  1193. class StringRef;
  1194. struct IStream {
  1195. virtual ~IStream();
  1196. virtual std::ostream& stream() const = 0;
  1197. };
  1198. auto makeStream( StringRef const &filename ) -> IStream const*;
  1199. class ReusableStringStream : NonCopyable {
  1200. std::size_t m_index;
  1201. std::ostream* m_oss;
  1202. public:
  1203. ReusableStringStream();
  1204. ~ReusableStringStream();
  1205. auto str() const -> std::string;
  1206. template<typename T>
  1207. auto operator << ( T const& value ) -> ReusableStringStream& {
  1208. *m_oss << value;
  1209. return *this;
  1210. }
  1211. auto get() -> std::ostream& { return *m_oss; }
  1212. };
  1213. }
  1214. // end catch_stream.h
  1215. // start catch_interfaces_enum_values_registry.h
  1216. #include <vector>
  1217. namespace Catch {
  1218. namespace Detail {
  1219. struct EnumInfo {
  1220. StringRef m_name;
  1221. std::vector<std::pair<int, StringRef>> m_values;
  1222. ~EnumInfo();
  1223. StringRef lookup( int value ) const;
  1224. };
  1225. } // namespace Detail
  1226. struct IMutableEnumValuesRegistry {
  1227. virtual ~IMutableEnumValuesRegistry();
  1228. virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
  1229. template<typename E>
  1230. Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
  1231. static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
  1232. std::vector<int> intValues;
  1233. intValues.reserve( values.size() );
  1234. for( auto enumValue : values )
  1235. intValues.push_back( static_cast<int>( enumValue ) );
  1236. return registerEnum( enumName, allEnums, intValues );
  1237. }
  1238. };
  1239. } // Catch
  1240. // end catch_interfaces_enum_values_registry.h
  1241. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1242. #include <string_view>
  1243. #endif
  1244. #ifdef __OBJC__
  1245. // start catch_objc_arc.hpp
  1246. #import <Foundation/Foundation.h>
  1247. #ifdef __has_feature
  1248. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  1249. #else
  1250. #define CATCH_ARC_ENABLED 0
  1251. #endif
  1252. void arcSafeRelease( NSObject* obj );
  1253. id performOptionalSelector( id obj, SEL sel );
  1254. #if !CATCH_ARC_ENABLED
  1255. inline void arcSafeRelease( NSObject* obj ) {
  1256. [obj release];
  1257. }
  1258. inline id performOptionalSelector( id obj, SEL sel ) {
  1259. if( [obj respondsToSelector: sel] )
  1260. return [obj performSelector: sel];
  1261. return nil;
  1262. }
  1263. #define CATCH_UNSAFE_UNRETAINED
  1264. #define CATCH_ARC_STRONG
  1265. #else
  1266. inline void arcSafeRelease( NSObject* ){}
  1267. inline id performOptionalSelector( id obj, SEL sel ) {
  1268. #ifdef __clang__
  1269. #pragma clang diagnostic push
  1270. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  1271. #endif
  1272. if( [obj respondsToSelector: sel] )
  1273. return [obj performSelector: sel];
  1274. #ifdef __clang__
  1275. #pragma clang diagnostic pop
  1276. #endif
  1277. return nil;
  1278. }
  1279. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  1280. #define CATCH_ARC_STRONG __strong
  1281. #endif
  1282. // end catch_objc_arc.hpp
  1283. #endif
  1284. #ifdef _MSC_VER
  1285. #pragma warning(push)
  1286. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  1287. #endif
  1288. namespace Catch {
  1289. namespace Detail {
  1290. extern const std::string unprintableString;
  1291. std::string rawMemoryToString( const void *object, std::size_t size );
  1292. template<typename T>
  1293. std::string rawMemoryToString( const T& object ) {
  1294. return rawMemoryToString( &object, sizeof(object) );
  1295. }
  1296. template<typename T>
  1297. class IsStreamInsertable {
  1298. template<typename Stream, typename U>
  1299. static auto test(int)
  1300. -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
  1301. template<typename, typename>
  1302. static auto test(...)->std::false_type;
  1303. public:
  1304. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  1305. };
  1306. template<typename E>
  1307. std::string convertUnknownEnumToString( E e );
  1308. template<typename T>
  1309. typename std::enable_if<
  1310. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  1311. std::string>::type convertUnstreamable( T const& ) {
  1312. return Detail::unprintableString;
  1313. }
  1314. template<typename T>
  1315. typename std::enable_if<
  1316. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  1317. std::string>::type convertUnstreamable(T const& ex) {
  1318. return ex.what();
  1319. }
  1320. template<typename T>
  1321. typename std::enable_if<
  1322. std::is_enum<T>::value
  1323. , std::string>::type convertUnstreamable( T const& value ) {
  1324. return convertUnknownEnumToString( value );
  1325. }
  1326. #if defined(_MANAGED)
  1327. //! Convert a CLR string to a utf8 std::string
  1328. template<typename T>
  1329. std::string clrReferenceToString( T^ ref ) {
  1330. if (ref == nullptr)
  1331. return std::string("null");
  1332. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  1333. cli::pin_ptr<System::Byte> p = &bytes[0];
  1334. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  1335. }
  1336. #endif
  1337. } // namespace Detail
  1338. // If we decide for C++14, change these to enable_if_ts
  1339. template <typename T, typename = void>
  1340. struct StringMaker {
  1341. template <typename Fake = T>
  1342. static
  1343. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1344. convert(const Fake& value) {
  1345. ReusableStringStream rss;
  1346. // NB: call using the function-like syntax to avoid ambiguity with
  1347. // user-defined templated operator<< under clang.
  1348. rss.operator<<(value);
  1349. return rss.str();
  1350. }
  1351. template <typename Fake = T>
  1352. static
  1353. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1354. convert( const Fake& value ) {
  1355. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  1356. return Detail::convertUnstreamable(value);
  1357. #else
  1358. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  1359. #endif
  1360. }
  1361. };
  1362. namespace Detail {
  1363. // This function dispatches all stringification requests inside of Catch.
  1364. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  1365. template <typename T>
  1366. std::string stringify(const T& e) {
  1367. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  1368. }
  1369. template<typename E>
  1370. std::string convertUnknownEnumToString( E e ) {
  1371. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  1372. }
  1373. #if defined(_MANAGED)
  1374. template <typename T>
  1375. std::string stringify( T^ e ) {
  1376. return ::Catch::StringMaker<T^>::convert(e);
  1377. }
  1378. #endif
  1379. } // namespace Detail
  1380. // Some predefined specializations
  1381. template<>
  1382. struct StringMaker<std::string> {
  1383. static std::string convert(const std::string& str);
  1384. };
  1385. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1386. template<>
  1387. struct StringMaker<std::string_view> {
  1388. static std::string convert(std::string_view str);
  1389. };
  1390. #endif
  1391. template<>
  1392. struct StringMaker<char const *> {
  1393. static std::string convert(char const * str);
  1394. };
  1395. template<>
  1396. struct StringMaker<char *> {
  1397. static std::string convert(char * str);
  1398. };
  1399. #ifdef CATCH_CONFIG_WCHAR
  1400. template<>
  1401. struct StringMaker<std::wstring> {
  1402. static std::string convert(const std::wstring& wstr);
  1403. };
  1404. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1405. template<>
  1406. struct StringMaker<std::wstring_view> {
  1407. static std::string convert(std::wstring_view str);
  1408. };
  1409. # endif
  1410. template<>
  1411. struct StringMaker<wchar_t const *> {
  1412. static std::string convert(wchar_t const * str);
  1413. };
  1414. template<>
  1415. struct StringMaker<wchar_t *> {
  1416. static std::string convert(wchar_t * str);
  1417. };
  1418. #endif
  1419. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  1420. // while keeping string semantics?
  1421. template<int SZ>
  1422. struct StringMaker<char[SZ]> {
  1423. static std::string convert(char const* str) {
  1424. return ::Catch::Detail::stringify(std::string{ str });
  1425. }
  1426. };
  1427. template<int SZ>
  1428. struct StringMaker<signed char[SZ]> {
  1429. static std::string convert(signed char const* str) {
  1430. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1431. }
  1432. };
  1433. template<int SZ>
  1434. struct StringMaker<unsigned char[SZ]> {
  1435. static std::string convert(unsigned char const* str) {
  1436. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1437. }
  1438. };
  1439. #if defined(CATCH_CONFIG_CPP17_BYTE)
  1440. template<>
  1441. struct StringMaker<std::byte> {
  1442. static std::string convert(std::byte value);
  1443. };
  1444. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  1445. template<>
  1446. struct StringMaker<int> {
  1447. static std::string convert(int value);
  1448. };
  1449. template<>
  1450. struct StringMaker<long> {
  1451. static std::string convert(long value);
  1452. };
  1453. template<>
  1454. struct StringMaker<long long> {
  1455. static std::string convert(long long value);
  1456. };
  1457. template<>
  1458. struct StringMaker<unsigned int> {
  1459. static std::string convert(unsigned int value);
  1460. };
  1461. template<>
  1462. struct StringMaker<unsigned long> {
  1463. static std::string convert(unsigned long value);
  1464. };
  1465. template<>
  1466. struct StringMaker<unsigned long long> {
  1467. static std::string convert(unsigned long long value);
  1468. };
  1469. template<>
  1470. struct StringMaker<bool> {
  1471. static std::string convert(bool b);
  1472. };
  1473. template<>
  1474. struct StringMaker<char> {
  1475. static std::string convert(char c);
  1476. };
  1477. template<>
  1478. struct StringMaker<signed char> {
  1479. static std::string convert(signed char c);
  1480. };
  1481. template<>
  1482. struct StringMaker<unsigned char> {
  1483. static std::string convert(unsigned char c);
  1484. };
  1485. template<>
  1486. struct StringMaker<std::nullptr_t> {
  1487. static std::string convert(std::nullptr_t);
  1488. };
  1489. template<>
  1490. struct StringMaker<float> {
  1491. static std::string convert(float value);
  1492. static int precision;
  1493. };
  1494. template<>
  1495. struct StringMaker<double> {
  1496. static std::string convert(double value);
  1497. static int precision;
  1498. };
  1499. template <typename T>
  1500. struct StringMaker<T*> {
  1501. template <typename U>
  1502. static std::string convert(U* p) {
  1503. if (p) {
  1504. return ::Catch::Detail::rawMemoryToString(p);
  1505. } else {
  1506. return "nullptr";
  1507. }
  1508. }
  1509. };
  1510. template <typename R, typename C>
  1511. struct StringMaker<R C::*> {
  1512. static std::string convert(R C::* p) {
  1513. if (p) {
  1514. return ::Catch::Detail::rawMemoryToString(p);
  1515. } else {
  1516. return "nullptr";
  1517. }
  1518. }
  1519. };
  1520. #if defined(_MANAGED)
  1521. template <typename T>
  1522. struct StringMaker<T^> {
  1523. static std::string convert( T^ ref ) {
  1524. return ::Catch::Detail::clrReferenceToString(ref);
  1525. }
  1526. };
  1527. #endif
  1528. namespace Detail {
  1529. template<typename InputIterator, typename Sentinel = InputIterator>
  1530. std::string rangeToString(InputIterator first, Sentinel last) {
  1531. ReusableStringStream rss;
  1532. rss << "{ ";
  1533. if (first != last) {
  1534. rss << ::Catch::Detail::stringify(*first);
  1535. for (++first; first != last; ++first)
  1536. rss << ", " << ::Catch::Detail::stringify(*first);
  1537. }
  1538. rss << " }";
  1539. return rss.str();
  1540. }
  1541. }
  1542. #ifdef __OBJC__
  1543. template<>
  1544. struct StringMaker<NSString*> {
  1545. static std::string convert(NSString * nsstring) {
  1546. if (!nsstring)
  1547. return "nil";
  1548. return std::string("@") + [nsstring UTF8String];
  1549. }
  1550. };
  1551. template<>
  1552. struct StringMaker<NSObject*> {
  1553. static std::string convert(NSObject* nsObject) {
  1554. return ::Catch::Detail::stringify([nsObject description]);
  1555. }
  1556. };
  1557. namespace Detail {
  1558. inline std::string stringify( NSString* nsstring ) {
  1559. return StringMaker<NSString*>::convert( nsstring );
  1560. }
  1561. } // namespace Detail
  1562. #endif // __OBJC__
  1563. } // namespace Catch
  1564. //////////////////////////////////////////////////////
  1565. // Separate std-lib types stringification, so it can be selectively enabled
  1566. // This means that we do not bring in
  1567. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  1568. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1569. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1570. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1571. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1572. # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1573. #endif
  1574. // Separate std::pair specialization
  1575. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  1576. #include <utility>
  1577. namespace Catch {
  1578. template<typename T1, typename T2>
  1579. struct StringMaker<std::pair<T1, T2> > {
  1580. static std::string convert(const std::pair<T1, T2>& pair) {
  1581. ReusableStringStream rss;
  1582. rss << "{ "
  1583. << ::Catch::Detail::stringify(pair.first)
  1584. << ", "
  1585. << ::Catch::Detail::stringify(pair.second)
  1586. << " }";
  1587. return rss.str();
  1588. }
  1589. };
  1590. }
  1591. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1592. #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
  1593. #include <optional>
  1594. namespace Catch {
  1595. template<typename T>
  1596. struct StringMaker<std::optional<T> > {
  1597. static std::string convert(const std::optional<T>& optional) {
  1598. ReusableStringStream rss;
  1599. if (optional.has_value()) {
  1600. rss << ::Catch::Detail::stringify(*optional);
  1601. } else {
  1602. rss << "{ }";
  1603. }
  1604. return rss.str();
  1605. }
  1606. };
  1607. }
  1608. #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1609. // Separate std::tuple specialization
  1610. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  1611. #include <tuple>
  1612. namespace Catch {
  1613. namespace Detail {
  1614. template<
  1615. typename Tuple,
  1616. std::size_t N = 0,
  1617. bool = (N < std::tuple_size<Tuple>::value)
  1618. >
  1619. struct TupleElementPrinter {
  1620. static void print(const Tuple& tuple, std::ostream& os) {
  1621. os << (N ? ", " : " ")
  1622. << ::Catch::Detail::stringify(std::get<N>(tuple));
  1623. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  1624. }
  1625. };
  1626. template<
  1627. typename Tuple,
  1628. std::size_t N
  1629. >
  1630. struct TupleElementPrinter<Tuple, N, false> {
  1631. static void print(const Tuple&, std::ostream&) {}
  1632. };
  1633. }
  1634. template<typename ...Types>
  1635. struct StringMaker<std::tuple<Types...>> {
  1636. static std::string convert(const std::tuple<Types...>& tuple) {
  1637. ReusableStringStream rss;
  1638. rss << '{';
  1639. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1640. rss << " }";
  1641. return rss.str();
  1642. }
  1643. };
  1644. }
  1645. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1646. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1647. #include <variant>
  1648. namespace Catch {
  1649. template<>
  1650. struct StringMaker<std::monostate> {
  1651. static std::string convert(const std::monostate&) {
  1652. return "{ }";
  1653. }
  1654. };
  1655. template<typename... Elements>
  1656. struct StringMaker<std::variant<Elements...>> {
  1657. static std::string convert(const std::variant<Elements...>& variant) {
  1658. if (variant.valueless_by_exception()) {
  1659. return "{valueless variant}";
  1660. } else {
  1661. return std::visit(
  1662. [](const auto& value) {
  1663. return ::Catch::Detail::stringify(value);
  1664. },
  1665. variant
  1666. );
  1667. }
  1668. }
  1669. };
  1670. }
  1671. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1672. namespace Catch {
  1673. // Import begin/ end from std here
  1674. using std::begin;
  1675. using std::end;
  1676. namespace detail {
  1677. template <typename...>
  1678. struct void_type {
  1679. using type = void;
  1680. };
  1681. template <typename T, typename = void>
  1682. struct is_range_impl : std::false_type {
  1683. };
  1684. template <typename T>
  1685. struct is_range_impl<T, typename void_type<decltype(begin(std::declval<T>()))>::type> : std::true_type {
  1686. };
  1687. } // namespace detail
  1688. template <typename T>
  1689. struct is_range : detail::is_range_impl<T> {
  1690. };
  1691. #if defined(_MANAGED) // Managed types are never ranges
  1692. template <typename T>
  1693. struct is_range<T^> {
  1694. static const bool value = false;
  1695. };
  1696. #endif
  1697. template<typename Range>
  1698. std::string rangeToString( Range const& range ) {
  1699. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  1700. }
  1701. // Handle vector<bool> specially
  1702. template<typename Allocator>
  1703. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  1704. ReusableStringStream rss;
  1705. rss << "{ ";
  1706. bool first = true;
  1707. for( bool b : v ) {
  1708. if( first )
  1709. first = false;
  1710. else
  1711. rss << ", ";
  1712. rss << ::Catch::Detail::stringify( b );
  1713. }
  1714. rss << " }";
  1715. return rss.str();
  1716. }
  1717. template<typename R>
  1718. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1719. static std::string convert( R const& range ) {
  1720. return rangeToString( range );
  1721. }
  1722. };
  1723. template <typename T, int SZ>
  1724. struct StringMaker<T[SZ]> {
  1725. static std::string convert(T const(&arr)[SZ]) {
  1726. return rangeToString(arr);
  1727. }
  1728. };
  1729. } // namespace Catch
  1730. // Separate std::chrono::duration specialization
  1731. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1732. #include <ctime>
  1733. #include <ratio>
  1734. #include <chrono>
  1735. namespace Catch {
  1736. template <class Ratio>
  1737. struct ratio_string {
  1738. static std::string symbol();
  1739. };
  1740. template <class Ratio>
  1741. std::string ratio_string<Ratio>::symbol() {
  1742. Catch::ReusableStringStream rss;
  1743. rss << '[' << Ratio::num << '/'
  1744. << Ratio::den << ']';
  1745. return rss.str();
  1746. }
  1747. template <>
  1748. struct ratio_string<std::atto> {
  1749. static std::string symbol();
  1750. };
  1751. template <>
  1752. struct ratio_string<std::femto> {
  1753. static std::string symbol();
  1754. };
  1755. template <>
  1756. struct ratio_string<std::pico> {
  1757. static std::string symbol();
  1758. };
  1759. template <>
  1760. struct ratio_string<std::nano> {
  1761. static std::string symbol();
  1762. };
  1763. template <>
  1764. struct ratio_string<std::micro> {
  1765. static std::string symbol();
  1766. };
  1767. template <>
  1768. struct ratio_string<std::milli> {
  1769. static std::string symbol();
  1770. };
  1771. ////////////
  1772. // std::chrono::duration specializations
  1773. template<typename Value, typename Ratio>
  1774. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1775. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1776. ReusableStringStream rss;
  1777. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1778. return rss.str();
  1779. }
  1780. };
  1781. template<typename Value>
  1782. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1783. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1784. ReusableStringStream rss;
  1785. rss << duration.count() << " s";
  1786. return rss.str();
  1787. }
  1788. };
  1789. template<typename Value>
  1790. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1791. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1792. ReusableStringStream rss;
  1793. rss << duration.count() << " m";
  1794. return rss.str();
  1795. }
  1796. };
  1797. template<typename Value>
  1798. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1799. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1800. ReusableStringStream rss;
  1801. rss << duration.count() << " h";
  1802. return rss.str();
  1803. }
  1804. };
  1805. ////////////
  1806. // std::chrono::time_point specialization
  1807. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1808. template<typename Clock, typename Duration>
  1809. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1810. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1811. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1812. }
  1813. };
  1814. // std::chrono::time_point<system_clock> specialization
  1815. template<typename Duration>
  1816. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1817. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1818. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1819. #ifdef _MSC_VER
  1820. std::tm timeInfo = {};
  1821. gmtime_s(&timeInfo, &converted);
  1822. #else
  1823. std::tm* timeInfo = std::gmtime(&converted);
  1824. #endif
  1825. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1826. char timeStamp[timeStampSize];
  1827. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1828. #ifdef _MSC_VER
  1829. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1830. #else
  1831. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1832. #endif
  1833. return std::string(timeStamp);
  1834. }
  1835. };
  1836. }
  1837. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1838. #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
  1839. namespace Catch { \
  1840. template<> struct StringMaker<enumName> { \
  1841. static std::string convert( enumName value ) { \
  1842. static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
  1843. return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
  1844. } \
  1845. }; \
  1846. }
  1847. #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
  1848. #ifdef _MSC_VER
  1849. #pragma warning(pop)
  1850. #endif
  1851. // end catch_tostring.h
  1852. #include <iosfwd>
  1853. #ifdef _MSC_VER
  1854. #pragma warning(push)
  1855. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1856. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1857. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1858. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1859. #pragma warning(disable:4800) // Forcing result to true or false
  1860. #endif
  1861. namespace Catch {
  1862. struct ITransientExpression {
  1863. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1864. auto getResult() const -> bool { return m_result; }
  1865. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1866. ITransientExpression( bool isBinaryExpression, bool result )
  1867. : m_isBinaryExpression( isBinaryExpression ),
  1868. m_result( result )
  1869. {}
  1870. // We don't actually need a virtual destructor, but many static analysers
  1871. // complain if it's not here :-(
  1872. virtual ~ITransientExpression();
  1873. bool m_isBinaryExpression;
  1874. bool m_result;
  1875. };
  1876. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1877. template<typename LhsT, typename RhsT>
  1878. class BinaryExpr : public ITransientExpression {
  1879. LhsT m_lhs;
  1880. StringRef m_op;
  1881. RhsT m_rhs;
  1882. void streamReconstructedExpression( std::ostream &os ) const override {
  1883. formatReconstructedExpression
  1884. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1885. }
  1886. public:
  1887. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1888. : ITransientExpression{ true, comparisonResult },
  1889. m_lhs( lhs ),
  1890. m_op( op ),
  1891. m_rhs( rhs )
  1892. {}
  1893. template<typename T>
  1894. auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1895. static_assert(always_false<T>::value,
  1896. "chained comparisons are not supported inside assertions, "
  1897. "wrap the expression inside parentheses, or decompose it");
  1898. }
  1899. template<typename T>
  1900. auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1901. static_assert(always_false<T>::value,
  1902. "chained comparisons are not supported inside assertions, "
  1903. "wrap the expression inside parentheses, or decompose it");
  1904. }
  1905. template<typename T>
  1906. auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1907. static_assert(always_false<T>::value,
  1908. "chained comparisons are not supported inside assertions, "
  1909. "wrap the expression inside parentheses, or decompose it");
  1910. }
  1911. template<typename T>
  1912. auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1913. static_assert(always_false<T>::value,
  1914. "chained comparisons are not supported inside assertions, "
  1915. "wrap the expression inside parentheses, or decompose it");
  1916. }
  1917. template<typename T>
  1918. auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1919. static_assert(always_false<T>::value,
  1920. "chained comparisons are not supported inside assertions, "
  1921. "wrap the expression inside parentheses, or decompose it");
  1922. }
  1923. template<typename T>
  1924. auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1925. static_assert(always_false<T>::value,
  1926. "chained comparisons are not supported inside assertions, "
  1927. "wrap the expression inside parentheses, or decompose it");
  1928. }
  1929. template<typename T>
  1930. auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1931. static_assert(always_false<T>::value,
  1932. "chained comparisons are not supported inside assertions, "
  1933. "wrap the expression inside parentheses, or decompose it");
  1934. }
  1935. template<typename T>
  1936. auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1937. static_assert(always_false<T>::value,
  1938. "chained comparisons are not supported inside assertions, "
  1939. "wrap the expression inside parentheses, or decompose it");
  1940. }
  1941. };
  1942. template<typename LhsT>
  1943. class UnaryExpr : public ITransientExpression {
  1944. LhsT m_lhs;
  1945. void streamReconstructedExpression( std::ostream &os ) const override {
  1946. os << Catch::Detail::stringify( m_lhs );
  1947. }
  1948. public:
  1949. explicit UnaryExpr( LhsT lhs )
  1950. : ITransientExpression{ false, static_cast<bool>(lhs) },
  1951. m_lhs( lhs )
  1952. {}
  1953. };
  1954. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1955. template<typename LhsT, typename RhsT>
  1956. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1957. template<typename T>
  1958. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1959. template<typename T>
  1960. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1961. template<typename T>
  1962. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1963. template<typename T>
  1964. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1965. template<typename LhsT, typename RhsT>
  1966. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1967. template<typename T>
  1968. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1969. template<typename T>
  1970. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1971. template<typename T>
  1972. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1973. template<typename T>
  1974. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1975. template<typename LhsT>
  1976. class ExprLhs {
  1977. LhsT m_lhs;
  1978. public:
  1979. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1980. template<typename RhsT>
  1981. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1982. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1983. }
  1984. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1985. return { m_lhs == rhs, m_lhs, "==", rhs };
  1986. }
  1987. template<typename RhsT>
  1988. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1989. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1990. }
  1991. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1992. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1993. }
  1994. template<typename RhsT>
  1995. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1996. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1997. }
  1998. template<typename RhsT>
  1999. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  2000. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  2001. }
  2002. template<typename RhsT>
  2003. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  2004. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  2005. }
  2006. template<typename RhsT>
  2007. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  2008. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  2009. }
  2010. template <typename RhsT>
  2011. auto operator | (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
  2012. return { static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs };
  2013. }
  2014. template <typename RhsT>
  2015. auto operator & (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
  2016. return { static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs };
  2017. }
  2018. template <typename RhsT>
  2019. auto operator ^ (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
  2020. return { static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs };
  2021. }
  2022. template<typename RhsT>
  2023. auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  2024. static_assert(always_false<RhsT>::value,
  2025. "operator&& is not supported inside assertions, "
  2026. "wrap the expression inside parentheses, or decompose it");
  2027. }
  2028. template<typename RhsT>
  2029. auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  2030. static_assert(always_false<RhsT>::value,
  2031. "operator|| is not supported inside assertions, "
  2032. "wrap the expression inside parentheses, or decompose it");
  2033. }
  2034. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  2035. return UnaryExpr<LhsT>{ m_lhs };
  2036. }
  2037. };
  2038. void handleExpression( ITransientExpression const& expr );
  2039. template<typename T>
  2040. void handleExpression( ExprLhs<T> const& expr ) {
  2041. handleExpression( expr.makeUnaryExpr() );
  2042. }
  2043. struct Decomposer {
  2044. template<typename T>
  2045. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  2046. return ExprLhs<T const&>{ lhs };
  2047. }
  2048. auto operator <=( bool value ) -> ExprLhs<bool> {
  2049. return ExprLhs<bool>{ value };
  2050. }
  2051. };
  2052. } // end namespace Catch
  2053. #ifdef _MSC_VER
  2054. #pragma warning(pop)
  2055. #endif
  2056. // end catch_decomposer.h
  2057. // start catch_interfaces_capture.h
  2058. #include <string>
  2059. #include <chrono>
  2060. namespace Catch {
  2061. class AssertionResult;
  2062. struct AssertionInfo;
  2063. struct SectionInfo;
  2064. struct SectionEndInfo;
  2065. struct MessageInfo;
  2066. struct MessageBuilder;
  2067. struct Counts;
  2068. struct AssertionReaction;
  2069. struct SourceLineInfo;
  2070. struct ITransientExpression;
  2071. struct IGeneratorTracker;
  2072. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2073. struct BenchmarkInfo;
  2074. template <typename Duration = std::chrono::duration<double, std::nano>>
  2075. struct BenchmarkStats;
  2076. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2077. struct IResultCapture {
  2078. virtual ~IResultCapture();
  2079. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  2080. Counts& assertions ) = 0;
  2081. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  2082. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  2083. virtual auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
  2084. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  2085. virtual void benchmarkPreparing( std::string const& name ) = 0;
  2086. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  2087. virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
  2088. virtual void benchmarkFailed( std::string const& error ) = 0;
  2089. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  2090. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  2091. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  2092. virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
  2093. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  2094. virtual void handleExpr
  2095. ( AssertionInfo const& info,
  2096. ITransientExpression const& expr,
  2097. AssertionReaction& reaction ) = 0;
  2098. virtual void handleMessage
  2099. ( AssertionInfo const& info,
  2100. ResultWas::OfType resultType,
  2101. StringRef const& message,
  2102. AssertionReaction& reaction ) = 0;
  2103. virtual void handleUnexpectedExceptionNotThrown
  2104. ( AssertionInfo const& info,
  2105. AssertionReaction& reaction ) = 0;
  2106. virtual void handleUnexpectedInflightException
  2107. ( AssertionInfo const& info,
  2108. std::string const& message,
  2109. AssertionReaction& reaction ) = 0;
  2110. virtual void handleIncomplete
  2111. ( AssertionInfo const& info ) = 0;
  2112. virtual void handleNonExpr
  2113. ( AssertionInfo const &info,
  2114. ResultWas::OfType resultType,
  2115. AssertionReaction &reaction ) = 0;
  2116. virtual bool lastAssertionPassed() = 0;
  2117. virtual void assertionPassed() = 0;
  2118. // Deprecated, do not use:
  2119. virtual std::string getCurrentTestName() const = 0;
  2120. virtual const AssertionResult* getLastResult() const = 0;
  2121. virtual void exceptionEarlyReported() = 0;
  2122. };
  2123. IResultCapture& getResultCapture();
  2124. }
  2125. // end catch_interfaces_capture.h
  2126. namespace Catch {
  2127. struct TestFailureException{};
  2128. struct AssertionResultData;
  2129. struct IResultCapture;
  2130. class RunContext;
  2131. class LazyExpression {
  2132. friend class AssertionHandler;
  2133. friend struct AssertionStats;
  2134. friend class RunContext;
  2135. ITransientExpression const* m_transientExpression = nullptr;
  2136. bool m_isNegated;
  2137. public:
  2138. LazyExpression( bool isNegated );
  2139. LazyExpression( LazyExpression const& other );
  2140. LazyExpression& operator = ( LazyExpression const& ) = delete;
  2141. explicit operator bool() const;
  2142. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  2143. };
  2144. struct AssertionReaction {
  2145. bool shouldDebugBreak = false;
  2146. bool shouldThrow = false;
  2147. };
  2148. class AssertionHandler {
  2149. AssertionInfo m_assertionInfo;
  2150. AssertionReaction m_reaction;
  2151. bool m_completed = false;
  2152. IResultCapture& m_resultCapture;
  2153. public:
  2154. AssertionHandler
  2155. ( StringRef const& macroName,
  2156. SourceLineInfo const& lineInfo,
  2157. StringRef capturedExpression,
  2158. ResultDisposition::Flags resultDisposition );
  2159. ~AssertionHandler() {
  2160. if ( !m_completed ) {
  2161. m_resultCapture.handleIncomplete( m_assertionInfo );
  2162. }
  2163. }
  2164. template<typename T>
  2165. void handleExpr( ExprLhs<T> const& expr ) {
  2166. handleExpr( expr.makeUnaryExpr() );
  2167. }
  2168. void handleExpr( ITransientExpression const& expr );
  2169. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  2170. void handleExceptionThrownAsExpected();
  2171. void handleUnexpectedExceptionNotThrown();
  2172. void handleExceptionNotThrownAsExpected();
  2173. void handleThrowingCallSkipped();
  2174. void handleUnexpectedInflightException();
  2175. void complete();
  2176. void setCompleted();
  2177. // query
  2178. auto allowThrows() const -> bool;
  2179. };
  2180. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
  2181. } // namespace Catch
  2182. // end catch_assertionhandler.h
  2183. // start catch_message.h
  2184. #include <string>
  2185. #include <vector>
  2186. namespace Catch {
  2187. struct MessageInfo {
  2188. MessageInfo( StringRef const& _macroName,
  2189. SourceLineInfo const& _lineInfo,
  2190. ResultWas::OfType _type );
  2191. StringRef macroName;
  2192. std::string message;
  2193. SourceLineInfo lineInfo;
  2194. ResultWas::OfType type;
  2195. unsigned int sequence;
  2196. bool operator == ( MessageInfo const& other ) const;
  2197. bool operator < ( MessageInfo const& other ) const;
  2198. private:
  2199. static unsigned int globalCount;
  2200. };
  2201. struct MessageStream {
  2202. template<typename T>
  2203. MessageStream& operator << ( T const& value ) {
  2204. m_stream << value;
  2205. return *this;
  2206. }
  2207. ReusableStringStream m_stream;
  2208. };
  2209. struct MessageBuilder : MessageStream {
  2210. MessageBuilder( StringRef const& macroName,
  2211. SourceLineInfo const& lineInfo,
  2212. ResultWas::OfType type );
  2213. template<typename T>
  2214. MessageBuilder& operator << ( T const& value ) {
  2215. m_stream << value;
  2216. return *this;
  2217. }
  2218. MessageInfo m_info;
  2219. };
  2220. class ScopedMessage {
  2221. public:
  2222. explicit ScopedMessage( MessageBuilder const& builder );
  2223. ScopedMessage( ScopedMessage& duplicate ) = delete;
  2224. ScopedMessage( ScopedMessage&& old );
  2225. ~ScopedMessage();
  2226. MessageInfo m_info;
  2227. bool m_moved;
  2228. };
  2229. class Capturer {
  2230. std::vector<MessageInfo> m_messages;
  2231. IResultCapture& m_resultCapture = getResultCapture();
  2232. size_t m_captured = 0;
  2233. public:
  2234. Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
  2235. ~Capturer();
  2236. void captureValue( size_t index, std::string const& value );
  2237. template<typename T>
  2238. void captureValues( size_t index, T const& value ) {
  2239. captureValue( index, Catch::Detail::stringify( value ) );
  2240. }
  2241. template<typename T, typename... Ts>
  2242. void captureValues( size_t index, T const& value, Ts const&... values ) {
  2243. captureValue( index, Catch::Detail::stringify(value) );
  2244. captureValues( index+1, values... );
  2245. }
  2246. };
  2247. } // end namespace Catch
  2248. // end catch_message.h
  2249. #if !defined(CATCH_CONFIG_DISABLE)
  2250. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  2251. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  2252. #else
  2253. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  2254. #endif
  2255. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2256. ///////////////////////////////////////////////////////////////////////////////
  2257. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  2258. // macros.
  2259. #define INTERNAL_CATCH_TRY
  2260. #define INTERNAL_CATCH_CATCH( capturer )
  2261. #else // CATCH_CONFIG_FAST_COMPILE
  2262. #define INTERNAL_CATCH_TRY try
  2263. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  2264. #endif
  2265. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  2266. ///////////////////////////////////////////////////////////////////////////////
  2267. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  2268. do { \
  2269. CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
  2270. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2271. INTERNAL_CATCH_TRY { \
  2272. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  2273. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  2274. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  2275. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  2276. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2277. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2278. } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) )
  2279. ///////////////////////////////////////////////////////////////////////////////
  2280. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  2281. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2282. if( Catch::getResultCapture().lastAssertionPassed() )
  2283. ///////////////////////////////////////////////////////////////////////////////
  2284. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  2285. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  2286. if( !Catch::getResultCapture().lastAssertionPassed() )
  2287. ///////////////////////////////////////////////////////////////////////////////
  2288. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  2289. do { \
  2290. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  2291. try { \
  2292. static_cast<void>(__VA_ARGS__); \
  2293. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  2294. } \
  2295. catch( ... ) { \
  2296. catchAssertionHandler.handleUnexpectedInflightException(); \
  2297. } \
  2298. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2299. } while( false )
  2300. ///////////////////////////////////////////////////////////////////////////////
  2301. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  2302. do { \
  2303. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  2304. if( catchAssertionHandler.allowThrows() ) \
  2305. try { \
  2306. static_cast<void>(__VA_ARGS__); \
  2307. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2308. } \
  2309. catch( ... ) { \
  2310. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2311. } \
  2312. else \
  2313. catchAssertionHandler.handleThrowingCallSkipped(); \
  2314. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2315. } while( false )
  2316. ///////////////////////////////////////////////////////////////////////////////
  2317. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  2318. do { \
  2319. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  2320. if( catchAssertionHandler.allowThrows() ) \
  2321. try { \
  2322. static_cast<void>(expr); \
  2323. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2324. } \
  2325. catch( exceptionType const& ) { \
  2326. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  2327. } \
  2328. catch( ... ) { \
  2329. catchAssertionHandler.handleUnexpectedInflightException(); \
  2330. } \
  2331. else \
  2332. catchAssertionHandler.handleThrowingCallSkipped(); \
  2333. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2334. } while( false )
  2335. ///////////////////////////////////////////////////////////////////////////////
  2336. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  2337. do { \
  2338. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  2339. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  2340. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2341. } while( false )
  2342. ///////////////////////////////////////////////////////////////////////////////
  2343. #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
  2344. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  2345. varName.captureValues( 0, __VA_ARGS__ )
  2346. ///////////////////////////////////////////////////////////////////////////////
  2347. #define INTERNAL_CATCH_INFO( macroName, log ) \
  2348. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  2349. ///////////////////////////////////////////////////////////////////////////////
  2350. #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
  2351. Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
  2352. ///////////////////////////////////////////////////////////////////////////////
  2353. // Although this is matcher-based, it can be used with just a string
  2354. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  2355. do { \
  2356. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2357. if( catchAssertionHandler.allowThrows() ) \
  2358. try { \
  2359. static_cast<void>(__VA_ARGS__); \
  2360. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2361. } \
  2362. catch( ... ) { \
  2363. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  2364. } \
  2365. else \
  2366. catchAssertionHandler.handleThrowingCallSkipped(); \
  2367. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2368. } while( false )
  2369. #endif // CATCH_CONFIG_DISABLE
  2370. // end catch_capture.hpp
  2371. // start catch_section.h
  2372. // start catch_section_info.h
  2373. // start catch_totals.h
  2374. #include <cstddef>
  2375. namespace Catch {
  2376. struct Counts {
  2377. Counts operator - ( Counts const& other ) const;
  2378. Counts& operator += ( Counts const& other );
  2379. std::size_t total() const;
  2380. bool allPassed() const;
  2381. bool allOk() const;
  2382. std::size_t passed = 0;
  2383. std::size_t failed = 0;
  2384. std::size_t failedButOk = 0;
  2385. };
  2386. struct Totals {
  2387. Totals operator - ( Totals const& other ) const;
  2388. Totals& operator += ( Totals const& other );
  2389. Totals delta( Totals const& prevTotals ) const;
  2390. int error = 0;
  2391. Counts assertions;
  2392. Counts testCases;
  2393. };
  2394. }
  2395. // end catch_totals.h
  2396. #include <string>
  2397. namespace Catch {
  2398. struct SectionInfo {
  2399. SectionInfo
  2400. ( SourceLineInfo const& _lineInfo,
  2401. std::string const& _name );
  2402. // Deprecated
  2403. SectionInfo
  2404. ( SourceLineInfo const& _lineInfo,
  2405. std::string const& _name,
  2406. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  2407. std::string name;
  2408. std::string description; // !Deprecated: this will always be empty
  2409. SourceLineInfo lineInfo;
  2410. };
  2411. struct SectionEndInfo {
  2412. SectionInfo sectionInfo;
  2413. Counts prevAssertions;
  2414. double durationInSeconds;
  2415. };
  2416. } // end namespace Catch
  2417. // end catch_section_info.h
  2418. // start catch_timer.h
  2419. #include <cstdint>
  2420. namespace Catch {
  2421. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  2422. auto getEstimatedClockResolution() -> uint64_t;
  2423. class Timer {
  2424. uint64_t m_nanoseconds = 0;
  2425. public:
  2426. void start();
  2427. auto getElapsedNanoseconds() const -> uint64_t;
  2428. auto getElapsedMicroseconds() const -> uint64_t;
  2429. auto getElapsedMilliseconds() const -> unsigned int;
  2430. auto getElapsedSeconds() const -> double;
  2431. };
  2432. } // namespace Catch
  2433. // end catch_timer.h
  2434. #include <string>
  2435. namespace Catch {
  2436. class Section : NonCopyable {
  2437. public:
  2438. Section( SectionInfo const& info );
  2439. ~Section();
  2440. // This indicates whether the section should be executed or not
  2441. explicit operator bool() const;
  2442. private:
  2443. SectionInfo m_info;
  2444. std::string m_name;
  2445. Counts m_assertions;
  2446. bool m_sectionIncluded;
  2447. Timer m_timer;
  2448. };
  2449. } // end namespace Catch
  2450. #define INTERNAL_CATCH_SECTION( ... ) \
  2451. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  2452. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2453. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  2454. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  2455. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  2456. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  2457. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2458. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  2459. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  2460. // end catch_section.h
  2461. // start catch_interfaces_exception.h
  2462. // start catch_interfaces_registry_hub.h
  2463. #include <string>
  2464. #include <memory>
  2465. namespace Catch {
  2466. class TestCase;
  2467. struct ITestCaseRegistry;
  2468. struct IExceptionTranslatorRegistry;
  2469. struct IExceptionTranslator;
  2470. struct IReporterRegistry;
  2471. struct IReporterFactory;
  2472. struct ITagAliasRegistry;
  2473. struct IMutableEnumValuesRegistry;
  2474. class StartupExceptionRegistry;
  2475. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2476. struct IRegistryHub {
  2477. virtual ~IRegistryHub();
  2478. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  2479. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  2480. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  2481. virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
  2482. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  2483. };
  2484. struct IMutableRegistryHub {
  2485. virtual ~IMutableRegistryHub();
  2486. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  2487. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  2488. virtual void registerTest( TestCase const& testInfo ) = 0;
  2489. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  2490. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  2491. virtual void registerStartupException() noexcept = 0;
  2492. virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
  2493. };
  2494. IRegistryHub const& getRegistryHub();
  2495. IMutableRegistryHub& getMutableRegistryHub();
  2496. void cleanUp();
  2497. std::string translateActiveException();
  2498. }
  2499. // end catch_interfaces_registry_hub.h
  2500. #if defined(CATCH_CONFIG_DISABLE)
  2501. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  2502. static std::string translatorName( signature )
  2503. #endif
  2504. #include <exception>
  2505. #include <string>
  2506. #include <vector>
  2507. namespace Catch {
  2508. using exceptionTranslateFunction = std::string(*)();
  2509. struct IExceptionTranslator;
  2510. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  2511. struct IExceptionTranslator {
  2512. virtual ~IExceptionTranslator();
  2513. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  2514. };
  2515. struct IExceptionTranslatorRegistry {
  2516. virtual ~IExceptionTranslatorRegistry();
  2517. virtual std::string translateActiveException() const = 0;
  2518. };
  2519. class ExceptionTranslatorRegistrar {
  2520. template<typename T>
  2521. class ExceptionTranslator : public IExceptionTranslator {
  2522. public:
  2523. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  2524. : m_translateFunction( translateFunction )
  2525. {}
  2526. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  2527. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2528. return "";
  2529. #else
  2530. try {
  2531. if( it == itEnd )
  2532. std::rethrow_exception(std::current_exception());
  2533. else
  2534. return (*it)->translate( it+1, itEnd );
  2535. }
  2536. catch( T& ex ) {
  2537. return m_translateFunction( ex );
  2538. }
  2539. #endif
  2540. }
  2541. protected:
  2542. std::string(*m_translateFunction)( T& );
  2543. };
  2544. public:
  2545. template<typename T>
  2546. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  2547. getMutableRegistryHub().registerTranslator
  2548. ( new ExceptionTranslator<T>( translateFunction ) );
  2549. }
  2550. };
  2551. }
  2552. ///////////////////////////////////////////////////////////////////////////////
  2553. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  2554. static std::string translatorName( signature ); \
  2555. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  2556. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2557. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  2558. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
  2559. static std::string translatorName( signature )
  2560. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  2561. // end catch_interfaces_exception.h
  2562. // start catch_approx.h
  2563. #include <type_traits>
  2564. namespace Catch {
  2565. namespace Detail {
  2566. class Approx {
  2567. private:
  2568. bool equalityComparisonImpl(double other) const;
  2569. // Validates the new margin (margin >= 0)
  2570. // out-of-line to avoid including stdexcept in the header
  2571. void setMargin(double margin);
  2572. // Validates the new epsilon (0 < epsilon < 1)
  2573. // out-of-line to avoid including stdexcept in the header
  2574. void setEpsilon(double epsilon);
  2575. public:
  2576. explicit Approx ( double value );
  2577. static Approx custom();
  2578. Approx operator-() const;
  2579. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2580. Approx operator()( T const& value ) const {
  2581. Approx approx( static_cast<double>(value) );
  2582. approx.m_epsilon = m_epsilon;
  2583. approx.m_margin = m_margin;
  2584. approx.m_scale = m_scale;
  2585. return approx;
  2586. }
  2587. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2588. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  2589. {}
  2590. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2591. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  2592. auto lhs_v = static_cast<double>(lhs);
  2593. return rhs.equalityComparisonImpl(lhs_v);
  2594. }
  2595. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2596. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  2597. return operator==( rhs, lhs );
  2598. }
  2599. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2600. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  2601. return !operator==( lhs, rhs );
  2602. }
  2603. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2604. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  2605. return !operator==( rhs, lhs );
  2606. }
  2607. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2608. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  2609. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  2610. }
  2611. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2612. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  2613. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  2614. }
  2615. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2616. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  2617. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  2618. }
  2619. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2620. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  2621. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  2622. }
  2623. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2624. Approx& epsilon( T const& newEpsilon ) {
  2625. double epsilonAsDouble = static_cast<double>(newEpsilon);
  2626. setEpsilon(epsilonAsDouble);
  2627. return *this;
  2628. }
  2629. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2630. Approx& margin( T const& newMargin ) {
  2631. double marginAsDouble = static_cast<double>(newMargin);
  2632. setMargin(marginAsDouble);
  2633. return *this;
  2634. }
  2635. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2636. Approx& scale( T const& newScale ) {
  2637. m_scale = static_cast<double>(newScale);
  2638. return *this;
  2639. }
  2640. std::string toString() const;
  2641. private:
  2642. double m_epsilon;
  2643. double m_margin;
  2644. double m_scale;
  2645. double m_value;
  2646. };
  2647. } // end namespace Detail
  2648. namespace literals {
  2649. Detail::Approx operator "" _a(long double val);
  2650. Detail::Approx operator "" _a(unsigned long long val);
  2651. } // end namespace literals
  2652. template<>
  2653. struct StringMaker<Catch::Detail::Approx> {
  2654. static std::string convert(Catch::Detail::Approx const& value);
  2655. };
  2656. } // end namespace Catch
  2657. // end catch_approx.h
  2658. // start catch_string_manip.h
  2659. #include <string>
  2660. #include <iosfwd>
  2661. #include <vector>
  2662. namespace Catch {
  2663. bool startsWith( std::string const& s, std::string const& prefix );
  2664. bool startsWith( std::string const& s, char prefix );
  2665. bool endsWith( std::string const& s, std::string const& suffix );
  2666. bool endsWith( std::string const& s, char suffix );
  2667. bool contains( std::string const& s, std::string const& infix );
  2668. void toLowerInPlace( std::string& s );
  2669. std::string toLower( std::string const& s );
  2670. //! Returns a new string without whitespace at the start/end
  2671. std::string trim( std::string const& str );
  2672. //! Returns a substring of the original ref without whitespace. Beware lifetimes!
  2673. StringRef trim(StringRef ref);
  2674. // !!! Be aware, returns refs into original string - make sure original string outlives them
  2675. std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
  2676. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  2677. struct pluralise {
  2678. pluralise( std::size_t count, std::string const& label );
  2679. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  2680. std::size_t m_count;
  2681. std::string m_label;
  2682. };
  2683. }
  2684. // end catch_string_manip.h
  2685. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  2686. // start catch_capture_matchers.h
  2687. // start catch_matchers.h
  2688. #include <string>
  2689. #include <vector>
  2690. namespace Catch {
  2691. namespace Matchers {
  2692. namespace Impl {
  2693. template<typename ArgT> struct MatchAllOf;
  2694. template<typename ArgT> struct MatchAnyOf;
  2695. template<typename ArgT> struct MatchNotOf;
  2696. class MatcherUntypedBase {
  2697. public:
  2698. MatcherUntypedBase() = default;
  2699. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  2700. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  2701. std::string toString() const;
  2702. protected:
  2703. virtual ~MatcherUntypedBase();
  2704. virtual std::string describe() const = 0;
  2705. mutable std::string m_cachedToString;
  2706. };
  2707. #ifdef __clang__
  2708. # pragma clang diagnostic push
  2709. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  2710. #endif
  2711. template<typename ObjectT>
  2712. struct MatcherMethod {
  2713. virtual bool match( ObjectT const& arg ) const = 0;
  2714. };
  2715. #if defined(__OBJC__)
  2716. // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
  2717. // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
  2718. template<>
  2719. struct MatcherMethod<NSString*> {
  2720. virtual bool match( NSString* arg ) const = 0;
  2721. };
  2722. #endif
  2723. #ifdef __clang__
  2724. # pragma clang diagnostic pop
  2725. #endif
  2726. template<typename T>
  2727. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  2728. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  2729. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  2730. MatchNotOf<T> operator ! () const;
  2731. };
  2732. template<typename ArgT>
  2733. struct MatchAllOf : MatcherBase<ArgT> {
  2734. bool match( ArgT const& arg ) const override {
  2735. for( auto matcher : m_matchers ) {
  2736. if (!matcher->match(arg))
  2737. return false;
  2738. }
  2739. return true;
  2740. }
  2741. std::string describe() const override {
  2742. std::string description;
  2743. description.reserve( 4 + m_matchers.size()*32 );
  2744. description += "( ";
  2745. bool first = true;
  2746. for( auto matcher : m_matchers ) {
  2747. if( first )
  2748. first = false;
  2749. else
  2750. description += " and ";
  2751. description += matcher->toString();
  2752. }
  2753. description += " )";
  2754. return description;
  2755. }
  2756. MatchAllOf<ArgT> operator && ( MatcherBase<ArgT> const& other ) {
  2757. auto copy(*this);
  2758. copy.m_matchers.push_back( &other );
  2759. return copy;
  2760. }
  2761. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2762. };
  2763. template<typename ArgT>
  2764. struct MatchAnyOf : MatcherBase<ArgT> {
  2765. bool match( ArgT const& arg ) const override {
  2766. for( auto matcher : m_matchers ) {
  2767. if (matcher->match(arg))
  2768. return true;
  2769. }
  2770. return false;
  2771. }
  2772. std::string describe() const override {
  2773. std::string description;
  2774. description.reserve( 4 + m_matchers.size()*32 );
  2775. description += "( ";
  2776. bool first = true;
  2777. for( auto matcher : m_matchers ) {
  2778. if( first )
  2779. first = false;
  2780. else
  2781. description += " or ";
  2782. description += matcher->toString();
  2783. }
  2784. description += " )";
  2785. return description;
  2786. }
  2787. MatchAnyOf<ArgT> operator || ( MatcherBase<ArgT> const& other ) {
  2788. auto copy(*this);
  2789. copy.m_matchers.push_back( &other );
  2790. return copy;
  2791. }
  2792. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2793. };
  2794. template<typename ArgT>
  2795. struct MatchNotOf : MatcherBase<ArgT> {
  2796. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  2797. bool match( ArgT const& arg ) const override {
  2798. return !m_underlyingMatcher.match( arg );
  2799. }
  2800. std::string describe() const override {
  2801. return "not " + m_underlyingMatcher.toString();
  2802. }
  2803. MatcherBase<ArgT> const& m_underlyingMatcher;
  2804. };
  2805. template<typename T>
  2806. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  2807. return MatchAllOf<T>() && *this && other;
  2808. }
  2809. template<typename T>
  2810. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  2811. return MatchAnyOf<T>() || *this || other;
  2812. }
  2813. template<typename T>
  2814. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  2815. return MatchNotOf<T>( *this );
  2816. }
  2817. } // namespace Impl
  2818. } // namespace Matchers
  2819. using namespace Matchers;
  2820. using Matchers::Impl::MatcherBase;
  2821. } // namespace Catch
  2822. // end catch_matchers.h
  2823. // start catch_matchers_exception.hpp
  2824. namespace Catch {
  2825. namespace Matchers {
  2826. namespace Exception {
  2827. class ExceptionMessageMatcher : public MatcherBase<std::exception> {
  2828. std::string m_message;
  2829. public:
  2830. ExceptionMessageMatcher(std::string const& message):
  2831. m_message(message)
  2832. {}
  2833. bool match(std::exception const& ex) const override;
  2834. std::string describe() const override;
  2835. };
  2836. } // namespace Exception
  2837. Exception::ExceptionMessageMatcher Message(std::string const& message);
  2838. } // namespace Matchers
  2839. } // namespace Catch
  2840. // end catch_matchers_exception.hpp
  2841. // start catch_matchers_floating.h
  2842. namespace Catch {
  2843. namespace Matchers {
  2844. namespace Floating {
  2845. enum class FloatingPointKind : uint8_t;
  2846. struct WithinAbsMatcher : MatcherBase<double> {
  2847. WithinAbsMatcher(double target, double margin);
  2848. bool match(double const& matchee) const override;
  2849. std::string describe() const override;
  2850. private:
  2851. double m_target;
  2852. double m_margin;
  2853. };
  2854. struct WithinUlpsMatcher : MatcherBase<double> {
  2855. WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
  2856. bool match(double const& matchee) const override;
  2857. std::string describe() const override;
  2858. private:
  2859. double m_target;
  2860. uint64_t m_ulps;
  2861. FloatingPointKind m_type;
  2862. };
  2863. // Given IEEE-754 format for floats and doubles, we can assume
  2864. // that float -> double promotion is lossless. Given this, we can
  2865. // assume that if we do the standard relative comparison of
  2866. // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
  2867. // the same result if we do this for floats, as if we do this for
  2868. // doubles that were promoted from floats.
  2869. struct WithinRelMatcher : MatcherBase<double> {
  2870. WithinRelMatcher(double target, double epsilon);
  2871. bool match(double const& matchee) const override;
  2872. std::string describe() const override;
  2873. private:
  2874. double m_target;
  2875. double m_epsilon;
  2876. };
  2877. } // namespace Floating
  2878. // The following functions create the actual matcher objects.
  2879. // This allows the types to be inferred
  2880. Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
  2881. Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
  2882. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2883. Floating::WithinRelMatcher WithinRel(double target, double eps);
  2884. // defaults epsilon to 100*numeric_limits<double>::epsilon()
  2885. Floating::WithinRelMatcher WithinRel(double target);
  2886. Floating::WithinRelMatcher WithinRel(float target, float eps);
  2887. // defaults epsilon to 100*numeric_limits<float>::epsilon()
  2888. Floating::WithinRelMatcher WithinRel(float target);
  2889. } // namespace Matchers
  2890. } // namespace Catch
  2891. // end catch_matchers_floating.h
  2892. // start catch_matchers_generic.hpp
  2893. #include <functional>
  2894. #include <string>
  2895. namespace Catch {
  2896. namespace Matchers {
  2897. namespace Generic {
  2898. namespace Detail {
  2899. std::string finalizeDescription(const std::string& desc);
  2900. }
  2901. template <typename T>
  2902. class PredicateMatcher : public MatcherBase<T> {
  2903. std::function<bool(T const&)> m_predicate;
  2904. std::string m_description;
  2905. public:
  2906. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2907. :m_predicate(std::move(elem)),
  2908. m_description(Detail::finalizeDescription(descr))
  2909. {}
  2910. bool match( T const& item ) const override {
  2911. return m_predicate(item);
  2912. }
  2913. std::string describe() const override {
  2914. return m_description;
  2915. }
  2916. };
  2917. } // namespace Generic
  2918. // The following functions create the actual matcher objects.
  2919. // The user has to explicitly specify type to the function, because
  2920. // inferring std::function<bool(T const&)> is hard (but possible) and
  2921. // requires a lot of TMP.
  2922. template<typename T>
  2923. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2924. return Generic::PredicateMatcher<T>(predicate, description);
  2925. }
  2926. } // namespace Matchers
  2927. } // namespace Catch
  2928. // end catch_matchers_generic.hpp
  2929. // start catch_matchers_string.h
  2930. #include <string>
  2931. namespace Catch {
  2932. namespace Matchers {
  2933. namespace StdString {
  2934. struct CasedString
  2935. {
  2936. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2937. std::string adjustString( std::string const& str ) const;
  2938. std::string caseSensitivitySuffix() const;
  2939. CaseSensitive::Choice m_caseSensitivity;
  2940. std::string m_str;
  2941. };
  2942. struct StringMatcherBase : MatcherBase<std::string> {
  2943. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2944. std::string describe() const override;
  2945. CasedString m_comparator;
  2946. std::string m_operation;
  2947. };
  2948. struct EqualsMatcher : StringMatcherBase {
  2949. EqualsMatcher( CasedString const& comparator );
  2950. bool match( std::string const& source ) const override;
  2951. };
  2952. struct ContainsMatcher : StringMatcherBase {
  2953. ContainsMatcher( CasedString const& comparator );
  2954. bool match( std::string const& source ) const override;
  2955. };
  2956. struct StartsWithMatcher : StringMatcherBase {
  2957. StartsWithMatcher( CasedString const& comparator );
  2958. bool match( std::string const& source ) const override;
  2959. };
  2960. struct EndsWithMatcher : StringMatcherBase {
  2961. EndsWithMatcher( CasedString const& comparator );
  2962. bool match( std::string const& source ) const override;
  2963. };
  2964. struct RegexMatcher : MatcherBase<std::string> {
  2965. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2966. bool match( std::string const& matchee ) const override;
  2967. std::string describe() const override;
  2968. private:
  2969. std::string m_regex;
  2970. CaseSensitive::Choice m_caseSensitivity;
  2971. };
  2972. } // namespace StdString
  2973. // The following functions create the actual matcher objects.
  2974. // This allows the types to be inferred
  2975. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2976. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2977. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2978. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2979. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2980. } // namespace Matchers
  2981. } // namespace Catch
  2982. // end catch_matchers_string.h
  2983. // start catch_matchers_vector.h
  2984. #include <algorithm>
  2985. namespace Catch {
  2986. namespace Matchers {
  2987. namespace Vector {
  2988. template<typename T, typename Alloc>
  2989. struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> {
  2990. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2991. bool match(std::vector<T, Alloc> const &v) const override {
  2992. for (auto const& el : v) {
  2993. if (el == m_comparator) {
  2994. return true;
  2995. }
  2996. }
  2997. return false;
  2998. }
  2999. std::string describe() const override {
  3000. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  3001. }
  3002. T const& m_comparator;
  3003. };
  3004. template<typename T, typename AllocComp, typename AllocMatch>
  3005. struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
  3006. ContainsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
  3007. bool match(std::vector<T, AllocMatch> const &v) const override {
  3008. // !TBD: see note in EqualsMatcher
  3009. if (m_comparator.size() > v.size())
  3010. return false;
  3011. for (auto const& comparator : m_comparator) {
  3012. auto present = false;
  3013. for (const auto& el : v) {
  3014. if (el == comparator) {
  3015. present = true;
  3016. break;
  3017. }
  3018. }
  3019. if (!present) {
  3020. return false;
  3021. }
  3022. }
  3023. return true;
  3024. }
  3025. std::string describe() const override {
  3026. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  3027. }
  3028. std::vector<T, AllocComp> const& m_comparator;
  3029. };
  3030. template<typename T, typename AllocComp, typename AllocMatch>
  3031. struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
  3032. EqualsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
  3033. bool match(std::vector<T, AllocMatch> const &v) const override {
  3034. // !TBD: This currently works if all elements can be compared using !=
  3035. // - a more general approach would be via a compare template that defaults
  3036. // to using !=. but could be specialised for, e.g. std::vector<T, Alloc> etc
  3037. // - then just call that directly
  3038. if (m_comparator.size() != v.size())
  3039. return false;
  3040. for (std::size_t i = 0; i < v.size(); ++i)
  3041. if (m_comparator[i] != v[i])
  3042. return false;
  3043. return true;
  3044. }
  3045. std::string describe() const override {
  3046. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  3047. }
  3048. std::vector<T, AllocComp> const& m_comparator;
  3049. };
  3050. template<typename T, typename AllocComp, typename AllocMatch>
  3051. struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> {
  3052. ApproxMatcher(std::vector<T, AllocComp> const& comparator) : m_comparator( comparator ) {}
  3053. bool match(std::vector<T, AllocMatch> const &v) const override {
  3054. if (m_comparator.size() != v.size())
  3055. return false;
  3056. for (std::size_t i = 0; i < v.size(); ++i)
  3057. if (m_comparator[i] != approx(v[i]))
  3058. return false;
  3059. return true;
  3060. }
  3061. std::string describe() const override {
  3062. return "is approx: " + ::Catch::Detail::stringify( m_comparator );
  3063. }
  3064. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3065. ApproxMatcher& epsilon( T const& newEpsilon ) {
  3066. approx.epsilon(newEpsilon);
  3067. return *this;
  3068. }
  3069. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3070. ApproxMatcher& margin( T const& newMargin ) {
  3071. approx.margin(newMargin);
  3072. return *this;
  3073. }
  3074. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  3075. ApproxMatcher& scale( T const& newScale ) {
  3076. approx.scale(newScale);
  3077. return *this;
  3078. }
  3079. std::vector<T, AllocComp> const& m_comparator;
  3080. mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
  3081. };
  3082. template<typename T, typename AllocComp, typename AllocMatch>
  3083. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
  3084. UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target) : m_target(target) {}
  3085. bool match(std::vector<T, AllocMatch> const& vec) const override {
  3086. if (m_target.size() != vec.size()) {
  3087. return false;
  3088. }
  3089. return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
  3090. }
  3091. std::string describe() const override {
  3092. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  3093. }
  3094. private:
  3095. std::vector<T, AllocComp> const& m_target;
  3096. };
  3097. } // namespace Vector
  3098. // The following functions create the actual matcher objects.
  3099. // This allows the types to be inferred
  3100. template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
  3101. Vector::ContainsMatcher<T, AllocComp, AllocMatch> Contains( std::vector<T, AllocComp> const& comparator ) {
  3102. return Vector::ContainsMatcher<T, AllocComp, AllocMatch>( comparator );
  3103. }
  3104. template<typename T, typename Alloc = std::allocator<T>>
  3105. Vector::ContainsElementMatcher<T, Alloc> VectorContains( T const& comparator ) {
  3106. return Vector::ContainsElementMatcher<T, Alloc>( comparator );
  3107. }
  3108. template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
  3109. Vector::EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp> const& comparator ) {
  3110. return Vector::EqualsMatcher<T, AllocComp, AllocMatch>( comparator );
  3111. }
  3112. template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
  3113. Vector::ApproxMatcher<T, AllocComp, AllocMatch> Approx( std::vector<T, AllocComp> const& comparator ) {
  3114. return Vector::ApproxMatcher<T, AllocComp, AllocMatch>( comparator );
  3115. }
  3116. template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
  3117. Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp> const& target) {
  3118. return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>( target );
  3119. }
  3120. } // namespace Matchers
  3121. } // namespace Catch
  3122. // end catch_matchers_vector.h
  3123. namespace Catch {
  3124. template<typename ArgT, typename MatcherT>
  3125. class MatchExpr : public ITransientExpression {
  3126. ArgT const& m_arg;
  3127. MatcherT m_matcher;
  3128. StringRef m_matcherString;
  3129. public:
  3130. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  3131. : ITransientExpression{ true, matcher.match( arg ) },
  3132. m_arg( arg ),
  3133. m_matcher( matcher ),
  3134. m_matcherString( matcherString )
  3135. {}
  3136. void streamReconstructedExpression( std::ostream &os ) const override {
  3137. auto matcherAsString = m_matcher.toString();
  3138. os << Catch::Detail::stringify( m_arg ) << ' ';
  3139. if( matcherAsString == Detail::unprintableString )
  3140. os << m_matcherString;
  3141. else
  3142. os << matcherAsString;
  3143. }
  3144. };
  3145. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3146. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  3147. template<typename ArgT, typename MatcherT>
  3148. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  3149. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  3150. }
  3151. } // namespace Catch
  3152. ///////////////////////////////////////////////////////////////////////////////
  3153. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  3154. do { \
  3155. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3156. INTERNAL_CATCH_TRY { \
  3157. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  3158. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  3159. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3160. } while( false )
  3161. ///////////////////////////////////////////////////////////////////////////////
  3162. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  3163. do { \
  3164. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  3165. if( catchAssertionHandler.allowThrows() ) \
  3166. try { \
  3167. static_cast<void>(__VA_ARGS__ ); \
  3168. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  3169. } \
  3170. catch( exceptionType const& ex ) { \
  3171. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  3172. } \
  3173. catch( ... ) { \
  3174. catchAssertionHandler.handleUnexpectedInflightException(); \
  3175. } \
  3176. else \
  3177. catchAssertionHandler.handleThrowingCallSkipped(); \
  3178. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  3179. } while( false )
  3180. // end catch_capture_matchers.h
  3181. #endif
  3182. // start catch_generators.hpp
  3183. // start catch_interfaces_generatortracker.h
  3184. #include <memory>
  3185. namespace Catch {
  3186. namespace Generators {
  3187. class GeneratorUntypedBase {
  3188. public:
  3189. GeneratorUntypedBase() = default;
  3190. virtual ~GeneratorUntypedBase();
  3191. // Attempts to move the generator to the next element
  3192. //
  3193. // Returns true iff the move succeeded (and a valid element
  3194. // can be retrieved).
  3195. virtual bool next() = 0;
  3196. };
  3197. using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
  3198. } // namespace Generators
  3199. struct IGeneratorTracker {
  3200. virtual ~IGeneratorTracker();
  3201. virtual auto hasGenerator() const -> bool = 0;
  3202. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  3203. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  3204. };
  3205. } // namespace Catch
  3206. // end catch_interfaces_generatortracker.h
  3207. // start catch_enforce.h
  3208. #include <exception>
  3209. namespace Catch {
  3210. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  3211. template <typename Ex>
  3212. [[noreturn]]
  3213. void throw_exception(Ex const& e) {
  3214. throw e;
  3215. }
  3216. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  3217. [[noreturn]]
  3218. void throw_exception(std::exception const& e);
  3219. #endif
  3220. [[noreturn]]
  3221. void throw_logic_error(std::string const& msg);
  3222. [[noreturn]]
  3223. void throw_domain_error(std::string const& msg);
  3224. [[noreturn]]
  3225. void throw_runtime_error(std::string const& msg);
  3226. } // namespace Catch;
  3227. #define CATCH_MAKE_MSG(...) \
  3228. (Catch::ReusableStringStream() << __VA_ARGS__).str()
  3229. #define CATCH_INTERNAL_ERROR(...) \
  3230. Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
  3231. #define CATCH_ERROR(...) \
  3232. Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
  3233. #define CATCH_RUNTIME_ERROR(...) \
  3234. Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
  3235. #define CATCH_ENFORCE( condition, ... ) \
  3236. do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
  3237. // end catch_enforce.h
  3238. #include <memory>
  3239. #include <vector>
  3240. #include <cassert>
  3241. #include <utility>
  3242. #include <exception>
  3243. namespace Catch {
  3244. class GeneratorException : public std::exception {
  3245. const char* const m_msg = "";
  3246. public:
  3247. GeneratorException(const char* msg):
  3248. m_msg(msg)
  3249. {}
  3250. const char* what() const noexcept override final;
  3251. };
  3252. namespace Generators {
  3253. // !TBD move this into its own location?
  3254. namespace pf{
  3255. template<typename T, typename... Args>
  3256. std::unique_ptr<T> make_unique( Args&&... args ) {
  3257. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  3258. }
  3259. }
  3260. template<typename T>
  3261. struct IGenerator : GeneratorUntypedBase {
  3262. virtual ~IGenerator() = default;
  3263. // Returns the current element of the generator
  3264. //
  3265. // \Precondition The generator is either freshly constructed,
  3266. // or the last call to `next()` returned true
  3267. virtual T const& get() const = 0;
  3268. using type = T;
  3269. };
  3270. template<typename T>
  3271. class SingleValueGenerator final : public IGenerator<T> {
  3272. T m_value;
  3273. public:
  3274. SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
  3275. T const& get() const override {
  3276. return m_value;
  3277. }
  3278. bool next() override {
  3279. return false;
  3280. }
  3281. };
  3282. template<typename T>
  3283. class FixedValuesGenerator final : public IGenerator<T> {
  3284. static_assert(!std::is_same<T, bool>::value,
  3285. "FixedValuesGenerator does not support bools because of std::vector<bool>"
  3286. "specialization, use SingleValue Generator instead.");
  3287. std::vector<T> m_values;
  3288. size_t m_idx = 0;
  3289. public:
  3290. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  3291. T const& get() const override {
  3292. return m_values[m_idx];
  3293. }
  3294. bool next() override {
  3295. ++m_idx;
  3296. return m_idx < m_values.size();
  3297. }
  3298. };
  3299. template <typename T>
  3300. class GeneratorWrapper final {
  3301. std::unique_ptr<IGenerator<T>> m_generator;
  3302. public:
  3303. GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
  3304. m_generator(std::move(generator))
  3305. {}
  3306. T const& get() const {
  3307. return m_generator->get();
  3308. }
  3309. bool next() {
  3310. return m_generator->next();
  3311. }
  3312. };
  3313. template <typename T>
  3314. GeneratorWrapper<T> value(T&& value) {
  3315. return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
  3316. }
  3317. template <typename T>
  3318. GeneratorWrapper<T> values(std::initializer_list<T> values) {
  3319. return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
  3320. }
  3321. template<typename T>
  3322. class Generators : public IGenerator<T> {
  3323. std::vector<GeneratorWrapper<T>> m_generators;
  3324. size_t m_current = 0;
  3325. void populate(GeneratorWrapper<T>&& generator) {
  3326. m_generators.emplace_back(std::move(generator));
  3327. }
  3328. void populate(T&& val) {
  3329. m_generators.emplace_back(value(std::forward<T>(val)));
  3330. }
  3331. template<typename U>
  3332. void populate(U&& val) {
  3333. populate(T(std::forward<U>(val)));
  3334. }
  3335. template<typename U, typename... Gs>
  3336. void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
  3337. populate(std::forward<U>(valueOrGenerator));
  3338. populate(std::forward<Gs>(moreGenerators)...);
  3339. }
  3340. public:
  3341. template <typename... Gs>
  3342. Generators(Gs &&... moreGenerators) {
  3343. m_generators.reserve(sizeof...(Gs));
  3344. populate(std::forward<Gs>(moreGenerators)...);
  3345. }
  3346. T const& get() const override {
  3347. return m_generators[m_current].get();
  3348. }
  3349. bool next() override {
  3350. if (m_current >= m_generators.size()) {
  3351. return false;
  3352. }
  3353. const bool current_status = m_generators[m_current].next();
  3354. if (!current_status) {
  3355. ++m_current;
  3356. }
  3357. return m_current < m_generators.size();
  3358. }
  3359. };
  3360. template<typename... Ts>
  3361. GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
  3362. return values<std::tuple<Ts...>>( tuples );
  3363. }
  3364. // Tag type to signal that a generator sequence should convert arguments to a specific type
  3365. template <typename T>
  3366. struct as {};
  3367. template<typename T, typename... Gs>
  3368. auto makeGenerators( GeneratorWrapper<T>&& generator, Gs &&... moreGenerators ) -> Generators<T> {
  3369. return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
  3370. }
  3371. template<typename T>
  3372. auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
  3373. return Generators<T>(std::move(generator));
  3374. }
  3375. template<typename T, typename... Gs>
  3376. auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<T> {
  3377. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  3378. }
  3379. template<typename T, typename U, typename... Gs>
  3380. auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> {
  3381. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  3382. }
  3383. auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  3384. template<typename L>
  3385. // Note: The type after -> is weird, because VS2015 cannot parse
  3386. // the expression used in the typedef inside, when it is in
  3387. // return type. Yeah.
  3388. auto generate( StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
  3389. using UnderlyingType = typename decltype(generatorExpression())::type;
  3390. IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo );
  3391. if (!tracker.hasGenerator()) {
  3392. tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
  3393. }
  3394. auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
  3395. return generator.get();
  3396. }
  3397. } // namespace Generators
  3398. } // namespace Catch
  3399. #define GENERATE( ... ) \
  3400. Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
  3401. CATCH_INTERNAL_LINEINFO, \
  3402. [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
  3403. #define GENERATE_COPY( ... ) \
  3404. Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
  3405. CATCH_INTERNAL_LINEINFO, \
  3406. [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
  3407. #define GENERATE_REF( ... ) \
  3408. Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
  3409. CATCH_INTERNAL_LINEINFO, \
  3410. [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
  3411. // end catch_generators.hpp
  3412. // start catch_generators_generic.hpp
  3413. namespace Catch {
  3414. namespace Generators {
  3415. template <typename T>
  3416. class TakeGenerator : public IGenerator<T> {
  3417. GeneratorWrapper<T> m_generator;
  3418. size_t m_returned = 0;
  3419. size_t m_target;
  3420. public:
  3421. TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
  3422. m_generator(std::move(generator)),
  3423. m_target(target)
  3424. {
  3425. assert(target != 0 && "Empty generators are not allowed");
  3426. }
  3427. T const& get() const override {
  3428. return m_generator.get();
  3429. }
  3430. bool next() override {
  3431. ++m_returned;
  3432. if (m_returned >= m_target) {
  3433. return false;
  3434. }
  3435. const auto success = m_generator.next();
  3436. // If the underlying generator does not contain enough values
  3437. // then we cut short as well
  3438. if (!success) {
  3439. m_returned = m_target;
  3440. }
  3441. return success;
  3442. }
  3443. };
  3444. template <typename T>
  3445. GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
  3446. return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
  3447. }
  3448. template <typename T, typename Predicate>
  3449. class FilterGenerator : public IGenerator<T> {
  3450. GeneratorWrapper<T> m_generator;
  3451. Predicate m_predicate;
  3452. public:
  3453. template <typename P = Predicate>
  3454. FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
  3455. m_generator(std::move(generator)),
  3456. m_predicate(std::forward<P>(pred))
  3457. {
  3458. if (!m_predicate(m_generator.get())) {
  3459. // It might happen that there are no values that pass the
  3460. // filter. In that case we throw an exception.
  3461. auto has_initial_value = nextImpl();
  3462. if (!has_initial_value) {
  3463. Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
  3464. }
  3465. }
  3466. }
  3467. T const& get() const override {
  3468. return m_generator.get();
  3469. }
  3470. bool next() override {
  3471. return nextImpl();
  3472. }
  3473. private:
  3474. bool nextImpl() {
  3475. bool success = m_generator.next();
  3476. if (!success) {
  3477. return false;
  3478. }
  3479. while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
  3480. return success;
  3481. }
  3482. };
  3483. template <typename T, typename Predicate>
  3484. GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
  3485. return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
  3486. }
  3487. template <typename T>
  3488. class RepeatGenerator : public IGenerator<T> {
  3489. static_assert(!std::is_same<T, bool>::value,
  3490. "RepeatGenerator currently does not support bools"
  3491. "because of std::vector<bool> specialization");
  3492. GeneratorWrapper<T> m_generator;
  3493. mutable std::vector<T> m_returned;
  3494. size_t m_target_repeats;
  3495. size_t m_current_repeat = 0;
  3496. size_t m_repeat_index = 0;
  3497. public:
  3498. RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
  3499. m_generator(std::move(generator)),
  3500. m_target_repeats(repeats)
  3501. {
  3502. assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
  3503. }
  3504. T const& get() const override {
  3505. if (m_current_repeat == 0) {
  3506. m_returned.push_back(m_generator.get());
  3507. return m_returned.back();
  3508. }
  3509. return m_returned[m_repeat_index];
  3510. }
  3511. bool next() override {
  3512. // There are 2 basic cases:
  3513. // 1) We are still reading the generator
  3514. // 2) We are reading our own cache
  3515. // In the first case, we need to poke the underlying generator.
  3516. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
  3517. if (m_current_repeat == 0) {
  3518. const auto success = m_generator.next();
  3519. if (!success) {
  3520. ++m_current_repeat;
  3521. }
  3522. return m_current_repeat < m_target_repeats;
  3523. }
  3524. // In the second case, we need to move indices forward and check that we haven't run up against the end
  3525. ++m_repeat_index;
  3526. if (m_repeat_index == m_returned.size()) {
  3527. m_repeat_index = 0;
  3528. ++m_current_repeat;
  3529. }
  3530. return m_current_repeat < m_target_repeats;
  3531. }
  3532. };
  3533. template <typename T>
  3534. GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
  3535. return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
  3536. }
  3537. template <typename T, typename U, typename Func>
  3538. class MapGenerator : public IGenerator<T> {
  3539. // TBD: provide static assert for mapping function, for friendly error message
  3540. GeneratorWrapper<U> m_generator;
  3541. Func m_function;
  3542. // To avoid returning dangling reference, we have to save the values
  3543. T m_cache;
  3544. public:
  3545. template <typename F2 = Func>
  3546. MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
  3547. m_generator(std::move(generator)),
  3548. m_function(std::forward<F2>(function)),
  3549. m_cache(m_function(m_generator.get()))
  3550. {}
  3551. T const& get() const override {
  3552. return m_cache;
  3553. }
  3554. bool next() override {
  3555. const auto success = m_generator.next();
  3556. if (success) {
  3557. m_cache = m_function(m_generator.get());
  3558. }
  3559. return success;
  3560. }
  3561. };
  3562. template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
  3563. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3564. return GeneratorWrapper<T>(
  3565. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3566. );
  3567. }
  3568. template <typename T, typename U, typename Func>
  3569. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3570. return GeneratorWrapper<T>(
  3571. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3572. );
  3573. }
  3574. template <typename T>
  3575. class ChunkGenerator final : public IGenerator<std::vector<T>> {
  3576. std::vector<T> m_chunk;
  3577. size_t m_chunk_size;
  3578. GeneratorWrapper<T> m_generator;
  3579. bool m_used_up = false;
  3580. public:
  3581. ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
  3582. m_chunk_size(size), m_generator(std::move(generator))
  3583. {
  3584. m_chunk.reserve(m_chunk_size);
  3585. if (m_chunk_size != 0) {
  3586. m_chunk.push_back(m_generator.get());
  3587. for (size_t i = 1; i < m_chunk_size; ++i) {
  3588. if (!m_generator.next()) {
  3589. Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
  3590. }
  3591. m_chunk.push_back(m_generator.get());
  3592. }
  3593. }
  3594. }
  3595. std::vector<T> const& get() const override {
  3596. return m_chunk;
  3597. }
  3598. bool next() override {
  3599. m_chunk.clear();
  3600. for (size_t idx = 0; idx < m_chunk_size; ++idx) {
  3601. if (!m_generator.next()) {
  3602. return false;
  3603. }
  3604. m_chunk.push_back(m_generator.get());
  3605. }
  3606. return true;
  3607. }
  3608. };
  3609. template <typename T>
  3610. GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
  3611. return GeneratorWrapper<std::vector<T>>(
  3612. pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
  3613. );
  3614. }
  3615. } // namespace Generators
  3616. } // namespace Catch
  3617. // end catch_generators_generic.hpp
  3618. // start catch_generators_specific.hpp
  3619. // start catch_context.h
  3620. #include <memory>
  3621. namespace Catch {
  3622. struct IResultCapture;
  3623. struct IRunner;
  3624. struct IConfig;
  3625. struct IMutableContext;
  3626. using IConfigPtr = std::shared_ptr<IConfig const>;
  3627. struct IContext
  3628. {
  3629. virtual ~IContext();
  3630. virtual IResultCapture* getResultCapture() = 0;
  3631. virtual IRunner* getRunner() = 0;
  3632. virtual IConfigPtr const& getConfig() const = 0;
  3633. };
  3634. struct IMutableContext : IContext
  3635. {
  3636. virtual ~IMutableContext();
  3637. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3638. virtual void setRunner( IRunner* runner ) = 0;
  3639. virtual void setConfig( IConfigPtr const& config ) = 0;
  3640. private:
  3641. static IMutableContext *currentContext;
  3642. friend IMutableContext& getCurrentMutableContext();
  3643. friend void cleanUpContext();
  3644. static void createContext();
  3645. };
  3646. inline IMutableContext& getCurrentMutableContext()
  3647. {
  3648. if( !IMutableContext::currentContext )
  3649. IMutableContext::createContext();
  3650. // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
  3651. return *IMutableContext::currentContext;
  3652. }
  3653. inline IContext& getCurrentContext()
  3654. {
  3655. return getCurrentMutableContext();
  3656. }
  3657. void cleanUpContext();
  3658. class SimplePcg32;
  3659. SimplePcg32& rng();
  3660. }
  3661. // end catch_context.h
  3662. // start catch_interfaces_config.h
  3663. // start catch_option.hpp
  3664. namespace Catch {
  3665. // An optional type
  3666. template<typename T>
  3667. class Option {
  3668. public:
  3669. Option() : nullableValue( nullptr ) {}
  3670. Option( T const& _value )
  3671. : nullableValue( new( storage ) T( _value ) )
  3672. {}
  3673. Option( Option const& _other )
  3674. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3675. {}
  3676. ~Option() {
  3677. reset();
  3678. }
  3679. Option& operator= ( Option const& _other ) {
  3680. if( &_other != this ) {
  3681. reset();
  3682. if( _other )
  3683. nullableValue = new( storage ) T( *_other );
  3684. }
  3685. return *this;
  3686. }
  3687. Option& operator = ( T const& _value ) {
  3688. reset();
  3689. nullableValue = new( storage ) T( _value );
  3690. return *this;
  3691. }
  3692. void reset() {
  3693. if( nullableValue )
  3694. nullableValue->~T();
  3695. nullableValue = nullptr;
  3696. }
  3697. T& operator*() { return *nullableValue; }
  3698. T const& operator*() const { return *nullableValue; }
  3699. T* operator->() { return nullableValue; }
  3700. const T* operator->() const { return nullableValue; }
  3701. T valueOr( T const& defaultValue ) const {
  3702. return nullableValue ? *nullableValue : defaultValue;
  3703. }
  3704. bool some() const { return nullableValue != nullptr; }
  3705. bool none() const { return nullableValue == nullptr; }
  3706. bool operator !() const { return nullableValue == nullptr; }
  3707. explicit operator bool() const {
  3708. return some();
  3709. }
  3710. private:
  3711. T *nullableValue;
  3712. alignas(alignof(T)) char storage[sizeof(T)];
  3713. };
  3714. } // end namespace Catch
  3715. // end catch_option.hpp
  3716. #include <chrono>
  3717. #include <iosfwd>
  3718. #include <string>
  3719. #include <vector>
  3720. #include <memory>
  3721. namespace Catch {
  3722. enum class Verbosity {
  3723. Quiet = 0,
  3724. Normal,
  3725. High
  3726. };
  3727. struct WarnAbout { enum What {
  3728. Nothing = 0x00,
  3729. NoAssertions = 0x01,
  3730. NoTests = 0x02
  3731. }; };
  3732. struct ShowDurations { enum OrNot {
  3733. DefaultForReporter,
  3734. Always,
  3735. Never
  3736. }; };
  3737. struct RunTests { enum InWhatOrder {
  3738. InDeclarationOrder,
  3739. InLexicographicalOrder,
  3740. InRandomOrder
  3741. }; };
  3742. struct UseColour { enum YesOrNo {
  3743. Auto,
  3744. Yes,
  3745. No
  3746. }; };
  3747. struct WaitForKeypress { enum When {
  3748. Never,
  3749. BeforeStart = 1,
  3750. BeforeExit = 2,
  3751. BeforeStartAndExit = BeforeStart | BeforeExit
  3752. }; };
  3753. class TestSpec;
  3754. struct IConfig : NonCopyable {
  3755. virtual ~IConfig();
  3756. virtual bool allowThrows() const = 0;
  3757. virtual std::ostream& stream() const = 0;
  3758. virtual std::string name() const = 0;
  3759. virtual bool includeSuccessfulResults() const = 0;
  3760. virtual bool shouldDebugBreak() const = 0;
  3761. virtual bool warnAboutMissingAssertions() const = 0;
  3762. virtual bool warnAboutNoTests() const = 0;
  3763. virtual int abortAfter() const = 0;
  3764. virtual bool showInvisibles() const = 0;
  3765. virtual ShowDurations::OrNot showDurations() const = 0;
  3766. virtual double minDuration() const = 0;
  3767. virtual TestSpec const& testSpec() const = 0;
  3768. virtual bool hasTestFilters() const = 0;
  3769. virtual std::vector<std::string> const& getTestsOrTags() const = 0;
  3770. virtual RunTests::InWhatOrder runOrder() const = 0;
  3771. virtual unsigned int rngSeed() const = 0;
  3772. virtual UseColour::YesOrNo useColour() const = 0;
  3773. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3774. virtual Verbosity verbosity() const = 0;
  3775. virtual bool benchmarkNoAnalysis() const = 0;
  3776. virtual int benchmarkSamples() const = 0;
  3777. virtual double benchmarkConfidenceInterval() const = 0;
  3778. virtual unsigned int benchmarkResamples() const = 0;
  3779. virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
  3780. };
  3781. using IConfigPtr = std::shared_ptr<IConfig const>;
  3782. }
  3783. // end catch_interfaces_config.h
  3784. // start catch_random_number_generator.h
  3785. #include <cstdint>
  3786. namespace Catch {
  3787. // This is a simple implementation of C++11 Uniform Random Number
  3788. // Generator. It does not provide all operators, because Catch2
  3789. // does not use it, but it should behave as expected inside stdlib's
  3790. // distributions.
  3791. // The implementation is based on the PCG family (http://pcg-random.org)
  3792. class SimplePcg32 {
  3793. using state_type = std::uint64_t;
  3794. public:
  3795. using result_type = std::uint32_t;
  3796. static constexpr result_type (min)() {
  3797. return 0;
  3798. }
  3799. static constexpr result_type (max)() {
  3800. return static_cast<result_type>(-1);
  3801. }
  3802. // Provide some default initial state for the default constructor
  3803. SimplePcg32():SimplePcg32(0xed743cc4U) {}
  3804. explicit SimplePcg32(result_type seed_);
  3805. void seed(result_type seed_);
  3806. void discard(uint64_t skip);
  3807. result_type operator()();
  3808. private:
  3809. friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
  3810. friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
  3811. // In theory we also need operator<< and operator>>
  3812. // In practice we do not use them, so we will skip them for now
  3813. std::uint64_t m_state;
  3814. // This part of the state determines which "stream" of the numbers
  3815. // is chosen -- we take it as a constant for Catch2, so we only
  3816. // need to deal with seeding the main state.
  3817. // Picked by reading 8 bytes from `/dev/random` :-)
  3818. static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
  3819. };
  3820. } // end namespace Catch
  3821. // end catch_random_number_generator.h
  3822. #include <random>
  3823. namespace Catch {
  3824. namespace Generators {
  3825. template <typename Float>
  3826. class RandomFloatingGenerator final : public IGenerator<Float> {
  3827. Catch::SimplePcg32& m_rng;
  3828. std::uniform_real_distribution<Float> m_dist;
  3829. Float m_current_number;
  3830. public:
  3831. RandomFloatingGenerator(Float a, Float b):
  3832. m_rng(rng()),
  3833. m_dist(a, b) {
  3834. static_cast<void>(next());
  3835. }
  3836. Float const& get() const override {
  3837. return m_current_number;
  3838. }
  3839. bool next() override {
  3840. m_current_number = m_dist(m_rng);
  3841. return true;
  3842. }
  3843. };
  3844. template <typename Integer>
  3845. class RandomIntegerGenerator final : public IGenerator<Integer> {
  3846. Catch::SimplePcg32& m_rng;
  3847. std::uniform_int_distribution<Integer> m_dist;
  3848. Integer m_current_number;
  3849. public:
  3850. RandomIntegerGenerator(Integer a, Integer b):
  3851. m_rng(rng()),
  3852. m_dist(a, b) {
  3853. static_cast<void>(next());
  3854. }
  3855. Integer const& get() const override {
  3856. return m_current_number;
  3857. }
  3858. bool next() override {
  3859. m_current_number = m_dist(m_rng);
  3860. return true;
  3861. }
  3862. };
  3863. // TODO: Ideally this would be also constrained against the various char types,
  3864. // but I don't expect users to run into that in practice.
  3865. template <typename T>
  3866. typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
  3867. GeneratorWrapper<T>>::type
  3868. random(T a, T b) {
  3869. return GeneratorWrapper<T>(
  3870. pf::make_unique<RandomIntegerGenerator<T>>(a, b)
  3871. );
  3872. }
  3873. template <typename T>
  3874. typename std::enable_if<std::is_floating_point<T>::value,
  3875. GeneratorWrapper<T>>::type
  3876. random(T a, T b) {
  3877. return GeneratorWrapper<T>(
  3878. pf::make_unique<RandomFloatingGenerator<T>>(a, b)
  3879. );
  3880. }
  3881. template <typename T>
  3882. class RangeGenerator final : public IGenerator<T> {
  3883. T m_current;
  3884. T m_end;
  3885. T m_step;
  3886. bool m_positive;
  3887. public:
  3888. RangeGenerator(T const& start, T const& end, T const& step):
  3889. m_current(start),
  3890. m_end(end),
  3891. m_step(step),
  3892. m_positive(m_step > T(0))
  3893. {
  3894. assert(m_current != m_end && "Range start and end cannot be equal");
  3895. assert(m_step != T(0) && "Step size cannot be zero");
  3896. assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
  3897. }
  3898. RangeGenerator(T const& start, T const& end):
  3899. RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
  3900. {}
  3901. T const& get() const override {
  3902. return m_current;
  3903. }
  3904. bool next() override {
  3905. m_current += m_step;
  3906. return (m_positive) ? (m_current < m_end) : (m_current > m_end);
  3907. }
  3908. };
  3909. template <typename T>
  3910. GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
  3911. static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "Type must be numeric");
  3912. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
  3913. }
  3914. template <typename T>
  3915. GeneratorWrapper<T> range(T const& start, T const& end) {
  3916. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3917. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
  3918. }
  3919. template <typename T>
  3920. class IteratorGenerator final : public IGenerator<T> {
  3921. static_assert(!std::is_same<T, bool>::value,
  3922. "IteratorGenerator currently does not support bools"
  3923. "because of std::vector<bool> specialization");
  3924. std::vector<T> m_elems;
  3925. size_t m_current = 0;
  3926. public:
  3927. template <typename InputIterator, typename InputSentinel>
  3928. IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
  3929. if (m_elems.empty()) {
  3930. Catch::throw_exception(GeneratorException("IteratorGenerator received no valid values"));
  3931. }
  3932. }
  3933. T const& get() const override {
  3934. return m_elems[m_current];
  3935. }
  3936. bool next() override {
  3937. ++m_current;
  3938. return m_current != m_elems.size();
  3939. }
  3940. };
  3941. template <typename InputIterator,
  3942. typename InputSentinel,
  3943. typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
  3944. GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
  3945. return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to));
  3946. }
  3947. template <typename Container,
  3948. typename ResultType = typename Container::value_type>
  3949. GeneratorWrapper<ResultType> from_range(Container const& cnt) {
  3950. return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
  3951. }
  3952. } // namespace Generators
  3953. } // namespace Catch
  3954. // end catch_generators_specific.hpp
  3955. // These files are included here so the single_include script doesn't put them
  3956. // in the conditionally compiled sections
  3957. // start catch_test_case_info.h
  3958. #include <string>
  3959. #include <vector>
  3960. #include <memory>
  3961. #ifdef __clang__
  3962. #pragma clang diagnostic push
  3963. #pragma clang diagnostic ignored "-Wpadded"
  3964. #endif
  3965. namespace Catch {
  3966. struct ITestInvoker;
  3967. struct TestCaseInfo {
  3968. enum SpecialProperties{
  3969. None = 0,
  3970. IsHidden = 1 << 1,
  3971. ShouldFail = 1 << 2,
  3972. MayFail = 1 << 3,
  3973. Throws = 1 << 4,
  3974. NonPortable = 1 << 5,
  3975. Benchmark = 1 << 6
  3976. };
  3977. TestCaseInfo( std::string const& _name,
  3978. std::string const& _className,
  3979. std::string const& _description,
  3980. std::vector<std::string> const& _tags,
  3981. SourceLineInfo const& _lineInfo );
  3982. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  3983. bool isHidden() const;
  3984. bool throws() const;
  3985. bool okToFail() const;
  3986. bool expectedToFail() const;
  3987. std::string tagsAsString() const;
  3988. std::string name;
  3989. std::string className;
  3990. std::string description;
  3991. std::vector<std::string> tags;
  3992. std::vector<std::string> lcaseTags;
  3993. SourceLineInfo lineInfo;
  3994. SpecialProperties properties;
  3995. };
  3996. class TestCase : public TestCaseInfo {
  3997. public:
  3998. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  3999. TestCase withName( std::string const& _newName ) const;
  4000. void invoke() const;
  4001. TestCaseInfo const& getTestCaseInfo() const;
  4002. bool operator == ( TestCase const& other ) const;
  4003. bool operator < ( TestCase const& other ) const;
  4004. private:
  4005. std::shared_ptr<ITestInvoker> test;
  4006. };
  4007. TestCase makeTestCase( ITestInvoker* testCase,
  4008. std::string const& className,
  4009. NameAndTags const& nameAndTags,
  4010. SourceLineInfo const& lineInfo );
  4011. }
  4012. #ifdef __clang__
  4013. #pragma clang diagnostic pop
  4014. #endif
  4015. // end catch_test_case_info.h
  4016. // start catch_interfaces_runner.h
  4017. namespace Catch {
  4018. struct IRunner {
  4019. virtual ~IRunner();
  4020. virtual bool aborting() const = 0;
  4021. };
  4022. }
  4023. // end catch_interfaces_runner.h
  4024. #ifdef __OBJC__
  4025. // start catch_objc.hpp
  4026. #import <objc/runtime.h>
  4027. #include <string>
  4028. // NB. Any general catch headers included here must be included
  4029. // in catch.hpp first to make sure they are included by the single
  4030. // header for non obj-usage
  4031. ///////////////////////////////////////////////////////////////////////////////
  4032. // This protocol is really only here for (self) documenting purposes, since
  4033. // all its methods are optional.
  4034. @protocol OcFixture
  4035. @optional
  4036. -(void) setUp;
  4037. -(void) tearDown;
  4038. @end
  4039. namespace Catch {
  4040. class OcMethod : public ITestInvoker {
  4041. public:
  4042. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  4043. virtual void invoke() const {
  4044. id obj = [[m_cls alloc] init];
  4045. performOptionalSelector( obj, @selector(setUp) );
  4046. performOptionalSelector( obj, m_sel );
  4047. performOptionalSelector( obj, @selector(tearDown) );
  4048. arcSafeRelease( obj );
  4049. }
  4050. private:
  4051. virtual ~OcMethod() {}
  4052. Class m_cls;
  4053. SEL m_sel;
  4054. };
  4055. namespace Detail{
  4056. inline std::string getAnnotation( Class cls,
  4057. std::string const& annotationName,
  4058. std::string const& testCaseName ) {
  4059. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  4060. SEL sel = NSSelectorFromString( selStr );
  4061. arcSafeRelease( selStr );
  4062. id value = performOptionalSelector( cls, sel );
  4063. if( value )
  4064. return [(NSString*)value UTF8String];
  4065. return "";
  4066. }
  4067. }
  4068. inline std::size_t registerTestMethods() {
  4069. std::size_t noTestMethods = 0;
  4070. int noClasses = objc_getClassList( nullptr, 0 );
  4071. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  4072. objc_getClassList( classes, noClasses );
  4073. for( int c = 0; c < noClasses; c++ ) {
  4074. Class cls = classes[c];
  4075. {
  4076. u_int count;
  4077. Method* methods = class_copyMethodList( cls, &count );
  4078. for( u_int m = 0; m < count ; m++ ) {
  4079. SEL selector = method_getName(methods[m]);
  4080. std::string methodName = sel_getName(selector);
  4081. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  4082. std::string testCaseName = methodName.substr( 15 );
  4083. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  4084. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  4085. const char* className = class_getName( cls );
  4086. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  4087. noTestMethods++;
  4088. }
  4089. }
  4090. free(methods);
  4091. }
  4092. }
  4093. return noTestMethods;
  4094. }
  4095. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  4096. namespace Matchers {
  4097. namespace Impl {
  4098. namespace NSStringMatchers {
  4099. struct StringHolder : MatcherBase<NSString*>{
  4100. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  4101. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  4102. StringHolder() {
  4103. arcSafeRelease( m_substr );
  4104. }
  4105. bool match( NSString* str ) const override {
  4106. return false;
  4107. }
  4108. NSString* CATCH_ARC_STRONG m_substr;
  4109. };
  4110. struct Equals : StringHolder {
  4111. Equals( NSString* substr ) : StringHolder( substr ){}
  4112. bool match( NSString* str ) const override {
  4113. return (str != nil || m_substr == nil ) &&
  4114. [str isEqualToString:m_substr];
  4115. }
  4116. std::string describe() const override {
  4117. return "equals string: " + Catch::Detail::stringify( m_substr );
  4118. }
  4119. };
  4120. struct Contains : StringHolder {
  4121. Contains( NSString* substr ) : StringHolder( substr ){}
  4122. bool match( NSString* str ) const override {
  4123. return (str != nil || m_substr == nil ) &&
  4124. [str rangeOfString:m_substr].location != NSNotFound;
  4125. }
  4126. std::string describe() const override {
  4127. return "contains string: " + Catch::Detail::stringify( m_substr );
  4128. }
  4129. };
  4130. struct StartsWith : StringHolder {
  4131. StartsWith( NSString* substr ) : StringHolder( substr ){}
  4132. bool match( NSString* str ) const override {
  4133. return (str != nil || m_substr == nil ) &&
  4134. [str rangeOfString:m_substr].location == 0;
  4135. }
  4136. std::string describe() const override {
  4137. return "starts with: " + Catch::Detail::stringify( m_substr );
  4138. }
  4139. };
  4140. struct EndsWith : StringHolder {
  4141. EndsWith( NSString* substr ) : StringHolder( substr ){}
  4142. bool match( NSString* str ) const override {
  4143. return (str != nil || m_substr == nil ) &&
  4144. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  4145. }
  4146. std::string describe() const override {
  4147. return "ends with: " + Catch::Detail::stringify( m_substr );
  4148. }
  4149. };
  4150. } // namespace NSStringMatchers
  4151. } // namespace Impl
  4152. inline Impl::NSStringMatchers::Equals
  4153. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  4154. inline Impl::NSStringMatchers::Contains
  4155. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  4156. inline Impl::NSStringMatchers::StartsWith
  4157. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  4158. inline Impl::NSStringMatchers::EndsWith
  4159. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  4160. } // namespace Matchers
  4161. using namespace Matchers;
  4162. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  4163. } // namespace Catch
  4164. ///////////////////////////////////////////////////////////////////////////////
  4165. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  4166. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  4167. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  4168. { \
  4169. return @ name; \
  4170. } \
  4171. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  4172. { \
  4173. return @ desc; \
  4174. } \
  4175. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  4176. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  4177. // end catch_objc.hpp
  4178. #endif
  4179. // Benchmarking needs the externally-facing parts of reporters to work
  4180. #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4181. // start catch_external_interfaces.h
  4182. // start catch_reporter_bases.hpp
  4183. // start catch_interfaces_reporter.h
  4184. // start catch_config.hpp
  4185. // start catch_test_spec_parser.h
  4186. #ifdef __clang__
  4187. #pragma clang diagnostic push
  4188. #pragma clang diagnostic ignored "-Wpadded"
  4189. #endif
  4190. // start catch_test_spec.h
  4191. #ifdef __clang__
  4192. #pragma clang diagnostic push
  4193. #pragma clang diagnostic ignored "-Wpadded"
  4194. #endif
  4195. // start catch_wildcard_pattern.h
  4196. namespace Catch
  4197. {
  4198. class WildcardPattern {
  4199. enum WildcardPosition {
  4200. NoWildcard = 0,
  4201. WildcardAtStart = 1,
  4202. WildcardAtEnd = 2,
  4203. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  4204. };
  4205. public:
  4206. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  4207. virtual ~WildcardPattern() = default;
  4208. virtual bool matches( std::string const& str ) const;
  4209. private:
  4210. std::string normaliseString( std::string const& str ) const;
  4211. CaseSensitive::Choice m_caseSensitivity;
  4212. WildcardPosition m_wildcard = NoWildcard;
  4213. std::string m_pattern;
  4214. };
  4215. }
  4216. // end catch_wildcard_pattern.h
  4217. #include <string>
  4218. #include <vector>
  4219. #include <memory>
  4220. namespace Catch {
  4221. struct IConfig;
  4222. class TestSpec {
  4223. class Pattern {
  4224. public:
  4225. explicit Pattern( std::string const& name );
  4226. virtual ~Pattern();
  4227. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  4228. std::string const& name() const;
  4229. private:
  4230. std::string const m_name;
  4231. };
  4232. using PatternPtr = std::shared_ptr<Pattern>;
  4233. class NamePattern : public Pattern {
  4234. public:
  4235. explicit NamePattern( std::string const& name, std::string const& filterString );
  4236. bool matches( TestCaseInfo const& testCase ) const override;
  4237. private:
  4238. WildcardPattern m_wildcardPattern;
  4239. };
  4240. class TagPattern : public Pattern {
  4241. public:
  4242. explicit TagPattern( std::string const& tag, std::string const& filterString );
  4243. bool matches( TestCaseInfo const& testCase ) const override;
  4244. private:
  4245. std::string m_tag;
  4246. };
  4247. class ExcludedPattern : public Pattern {
  4248. public:
  4249. explicit ExcludedPattern( PatternPtr const& underlyingPattern );
  4250. bool matches( TestCaseInfo const& testCase ) const override;
  4251. private:
  4252. PatternPtr m_underlyingPattern;
  4253. };
  4254. struct Filter {
  4255. std::vector<PatternPtr> m_patterns;
  4256. bool matches( TestCaseInfo const& testCase ) const;
  4257. std::string name() const;
  4258. };
  4259. public:
  4260. struct FilterMatch {
  4261. std::string name;
  4262. std::vector<TestCase const*> tests;
  4263. };
  4264. using Matches = std::vector<FilterMatch>;
  4265. using vectorStrings = std::vector<std::string>;
  4266. bool hasFilters() const;
  4267. bool matches( TestCaseInfo const& testCase ) const;
  4268. Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
  4269. const vectorStrings & getInvalidArgs() const;
  4270. private:
  4271. std::vector<Filter> m_filters;
  4272. std::vector<std::string> m_invalidArgs;
  4273. friend class TestSpecParser;
  4274. };
  4275. }
  4276. #ifdef __clang__
  4277. #pragma clang diagnostic pop
  4278. #endif
  4279. // end catch_test_spec.h
  4280. // start catch_interfaces_tag_alias_registry.h
  4281. #include <string>
  4282. namespace Catch {
  4283. struct TagAlias;
  4284. struct ITagAliasRegistry {
  4285. virtual ~ITagAliasRegistry();
  4286. // Nullptr if not present
  4287. virtual TagAlias const* find( std::string const& alias ) const = 0;
  4288. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  4289. static ITagAliasRegistry const& get();
  4290. };
  4291. } // end namespace Catch
  4292. // end catch_interfaces_tag_alias_registry.h
  4293. namespace Catch {
  4294. class TestSpecParser {
  4295. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  4296. Mode m_mode = None;
  4297. Mode lastMode = None;
  4298. bool m_exclusion = false;
  4299. std::size_t m_pos = 0;
  4300. std::size_t m_realPatternPos = 0;
  4301. std::string m_arg;
  4302. std::string m_substring;
  4303. std::string m_patternName;
  4304. std::vector<std::size_t> m_escapeChars;
  4305. TestSpec::Filter m_currentFilter;
  4306. TestSpec m_testSpec;
  4307. ITagAliasRegistry const* m_tagAliases = nullptr;
  4308. public:
  4309. TestSpecParser( ITagAliasRegistry const& tagAliases );
  4310. TestSpecParser& parse( std::string const& arg );
  4311. TestSpec testSpec();
  4312. private:
  4313. bool visitChar( char c );
  4314. void startNewMode( Mode mode );
  4315. bool processNoneChar( char c );
  4316. void processNameChar( char c );
  4317. bool processOtherChar( char c );
  4318. void endMode();
  4319. void escape();
  4320. bool isControlChar( char c ) const;
  4321. void saveLastMode();
  4322. void revertBackToLastMode();
  4323. void addFilter();
  4324. bool separate();
  4325. // Handles common preprocessing of the pattern for name/tag patterns
  4326. std::string preprocessPattern();
  4327. // Adds the current pattern as a test name
  4328. void addNamePattern();
  4329. // Adds the current pattern as a tag
  4330. void addTagPattern();
  4331. inline void addCharToPattern(char c) {
  4332. m_substring += c;
  4333. m_patternName += c;
  4334. m_realPatternPos++;
  4335. }
  4336. };
  4337. TestSpec parseTestSpec( std::string const& arg );
  4338. } // namespace Catch
  4339. #ifdef __clang__
  4340. #pragma clang diagnostic pop
  4341. #endif
  4342. // end catch_test_spec_parser.h
  4343. // Libstdc++ doesn't like incomplete classes for unique_ptr
  4344. #include <memory>
  4345. #include <vector>
  4346. #include <string>
  4347. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  4348. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  4349. #endif
  4350. namespace Catch {
  4351. struct IStream;
  4352. struct ConfigData {
  4353. bool listTests = false;
  4354. bool listTags = false;
  4355. bool listReporters = false;
  4356. bool listTestNamesOnly = false;
  4357. bool showSuccessfulTests = false;
  4358. bool shouldDebugBreak = false;
  4359. bool noThrow = false;
  4360. bool showHelp = false;
  4361. bool showInvisibles = false;
  4362. bool filenamesAsTags = false;
  4363. bool libIdentify = false;
  4364. int abortAfter = -1;
  4365. unsigned int rngSeed = 0;
  4366. bool benchmarkNoAnalysis = false;
  4367. unsigned int benchmarkSamples = 100;
  4368. double benchmarkConfidenceInterval = 0.95;
  4369. unsigned int benchmarkResamples = 100000;
  4370. std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
  4371. Verbosity verbosity = Verbosity::Normal;
  4372. WarnAbout::What warnings = WarnAbout::Nothing;
  4373. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  4374. double minDuration = -1;
  4375. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  4376. UseColour::YesOrNo useColour = UseColour::Auto;
  4377. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  4378. std::string outputFilename;
  4379. std::string name;
  4380. std::string processName;
  4381. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  4382. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  4383. #endif
  4384. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  4385. #undef CATCH_CONFIG_DEFAULT_REPORTER
  4386. std::vector<std::string> testsOrTags;
  4387. std::vector<std::string> sectionsToRun;
  4388. };
  4389. class Config : public IConfig {
  4390. public:
  4391. Config() = default;
  4392. Config( ConfigData const& data );
  4393. virtual ~Config() = default;
  4394. std::string const& getFilename() const;
  4395. bool listTests() const;
  4396. bool listTestNamesOnly() const;
  4397. bool listTags() const;
  4398. bool listReporters() const;
  4399. std::string getProcessName() const;
  4400. std::string const& getReporterName() const;
  4401. std::vector<std::string> const& getTestsOrTags() const override;
  4402. std::vector<std::string> const& getSectionsToRun() const override;
  4403. TestSpec const& testSpec() const override;
  4404. bool hasTestFilters() const override;
  4405. bool showHelp() const;
  4406. // IConfig interface
  4407. bool allowThrows() const override;
  4408. std::ostream& stream() const override;
  4409. std::string name() const override;
  4410. bool includeSuccessfulResults() const override;
  4411. bool warnAboutMissingAssertions() const override;
  4412. bool warnAboutNoTests() const override;
  4413. ShowDurations::OrNot showDurations() const override;
  4414. double minDuration() const override;
  4415. RunTests::InWhatOrder runOrder() const override;
  4416. unsigned int rngSeed() const override;
  4417. UseColour::YesOrNo useColour() const override;
  4418. bool shouldDebugBreak() const override;
  4419. int abortAfter() const override;
  4420. bool showInvisibles() const override;
  4421. Verbosity verbosity() const override;
  4422. bool benchmarkNoAnalysis() const override;
  4423. int benchmarkSamples() const override;
  4424. double benchmarkConfidenceInterval() const override;
  4425. unsigned int benchmarkResamples() const override;
  4426. std::chrono::milliseconds benchmarkWarmupTime() const override;
  4427. private:
  4428. IStream const* openStream();
  4429. ConfigData m_data;
  4430. std::unique_ptr<IStream const> m_stream;
  4431. TestSpec m_testSpec;
  4432. bool m_hasTestFilters = false;
  4433. };
  4434. } // end namespace Catch
  4435. // end catch_config.hpp
  4436. // start catch_assertionresult.h
  4437. #include <string>
  4438. namespace Catch {
  4439. struct AssertionResultData
  4440. {
  4441. AssertionResultData() = delete;
  4442. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  4443. std::string message;
  4444. mutable std::string reconstructedExpression;
  4445. LazyExpression lazyExpression;
  4446. ResultWas::OfType resultType;
  4447. std::string reconstructExpression() const;
  4448. };
  4449. class AssertionResult {
  4450. public:
  4451. AssertionResult() = delete;
  4452. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  4453. bool isOk() const;
  4454. bool succeeded() const;
  4455. ResultWas::OfType getResultType() const;
  4456. bool hasExpression() const;
  4457. bool hasMessage() const;
  4458. std::string getExpression() const;
  4459. std::string getExpressionInMacro() const;
  4460. bool hasExpandedExpression() const;
  4461. std::string getExpandedExpression() const;
  4462. std::string getMessage() const;
  4463. SourceLineInfo getSourceInfo() const;
  4464. StringRef getTestMacroName() const;
  4465. //protected:
  4466. AssertionInfo m_info;
  4467. AssertionResultData m_resultData;
  4468. };
  4469. } // end namespace Catch
  4470. // end catch_assertionresult.h
  4471. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4472. // start catch_estimate.hpp
  4473. // Statistics estimates
  4474. namespace Catch {
  4475. namespace Benchmark {
  4476. template <typename Duration>
  4477. struct Estimate {
  4478. Duration point;
  4479. Duration lower_bound;
  4480. Duration upper_bound;
  4481. double confidence_interval;
  4482. template <typename Duration2>
  4483. operator Estimate<Duration2>() const {
  4484. return { point, lower_bound, upper_bound, confidence_interval };
  4485. }
  4486. };
  4487. } // namespace Benchmark
  4488. } // namespace Catch
  4489. // end catch_estimate.hpp
  4490. // start catch_outlier_classification.hpp
  4491. // Outlier information
  4492. namespace Catch {
  4493. namespace Benchmark {
  4494. struct OutlierClassification {
  4495. int samples_seen = 0;
  4496. int low_severe = 0; // more than 3 times IQR below Q1
  4497. int low_mild = 0; // 1.5 to 3 times IQR below Q1
  4498. int high_mild = 0; // 1.5 to 3 times IQR above Q3
  4499. int high_severe = 0; // more than 3 times IQR above Q3
  4500. int total() const {
  4501. return low_severe + low_mild + high_mild + high_severe;
  4502. }
  4503. };
  4504. } // namespace Benchmark
  4505. } // namespace Catch
  4506. // end catch_outlier_classification.hpp
  4507. #include <iterator>
  4508. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4509. #include <string>
  4510. #include <iosfwd>
  4511. #include <map>
  4512. #include <set>
  4513. #include <memory>
  4514. #include <algorithm>
  4515. namespace Catch {
  4516. struct ReporterConfig {
  4517. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  4518. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  4519. std::ostream& stream() const;
  4520. IConfigPtr fullConfig() const;
  4521. private:
  4522. std::ostream* m_stream;
  4523. IConfigPtr m_fullConfig;
  4524. };
  4525. struct ReporterPreferences {
  4526. bool shouldRedirectStdOut = false;
  4527. bool shouldReportAllAssertions = false;
  4528. };
  4529. template<typename T>
  4530. struct LazyStat : Option<T> {
  4531. LazyStat& operator=( T const& _value ) {
  4532. Option<T>::operator=( _value );
  4533. used = false;
  4534. return *this;
  4535. }
  4536. void reset() {
  4537. Option<T>::reset();
  4538. used = false;
  4539. }
  4540. bool used = false;
  4541. };
  4542. struct TestRunInfo {
  4543. TestRunInfo( std::string const& _name );
  4544. std::string name;
  4545. };
  4546. struct GroupInfo {
  4547. GroupInfo( std::string const& _name,
  4548. std::size_t _groupIndex,
  4549. std::size_t _groupsCount );
  4550. std::string name;
  4551. std::size_t groupIndex;
  4552. std::size_t groupsCounts;
  4553. };
  4554. struct AssertionStats {
  4555. AssertionStats( AssertionResult const& _assertionResult,
  4556. std::vector<MessageInfo> const& _infoMessages,
  4557. Totals const& _totals );
  4558. AssertionStats( AssertionStats const& ) = default;
  4559. AssertionStats( AssertionStats && ) = default;
  4560. AssertionStats& operator = ( AssertionStats const& ) = delete;
  4561. AssertionStats& operator = ( AssertionStats && ) = delete;
  4562. virtual ~AssertionStats();
  4563. AssertionResult assertionResult;
  4564. std::vector<MessageInfo> infoMessages;
  4565. Totals totals;
  4566. };
  4567. struct SectionStats {
  4568. SectionStats( SectionInfo const& _sectionInfo,
  4569. Counts const& _assertions,
  4570. double _durationInSeconds,
  4571. bool _missingAssertions );
  4572. SectionStats( SectionStats const& ) = default;
  4573. SectionStats( SectionStats && ) = default;
  4574. SectionStats& operator = ( SectionStats const& ) = default;
  4575. SectionStats& operator = ( SectionStats && ) = default;
  4576. virtual ~SectionStats();
  4577. SectionInfo sectionInfo;
  4578. Counts assertions;
  4579. double durationInSeconds;
  4580. bool missingAssertions;
  4581. };
  4582. struct TestCaseStats {
  4583. TestCaseStats( TestCaseInfo const& _testInfo,
  4584. Totals const& _totals,
  4585. std::string const& _stdOut,
  4586. std::string const& _stdErr,
  4587. bool _aborting );
  4588. TestCaseStats( TestCaseStats const& ) = default;
  4589. TestCaseStats( TestCaseStats && ) = default;
  4590. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  4591. TestCaseStats& operator = ( TestCaseStats && ) = default;
  4592. virtual ~TestCaseStats();
  4593. TestCaseInfo testInfo;
  4594. Totals totals;
  4595. std::string stdOut;
  4596. std::string stdErr;
  4597. bool aborting;
  4598. };
  4599. struct TestGroupStats {
  4600. TestGroupStats( GroupInfo const& _groupInfo,
  4601. Totals const& _totals,
  4602. bool _aborting );
  4603. TestGroupStats( GroupInfo const& _groupInfo );
  4604. TestGroupStats( TestGroupStats const& ) = default;
  4605. TestGroupStats( TestGroupStats && ) = default;
  4606. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  4607. TestGroupStats& operator = ( TestGroupStats && ) = default;
  4608. virtual ~TestGroupStats();
  4609. GroupInfo groupInfo;
  4610. Totals totals;
  4611. bool aborting;
  4612. };
  4613. struct TestRunStats {
  4614. TestRunStats( TestRunInfo const& _runInfo,
  4615. Totals const& _totals,
  4616. bool _aborting );
  4617. TestRunStats( TestRunStats const& ) = default;
  4618. TestRunStats( TestRunStats && ) = default;
  4619. TestRunStats& operator = ( TestRunStats const& ) = default;
  4620. TestRunStats& operator = ( TestRunStats && ) = default;
  4621. virtual ~TestRunStats();
  4622. TestRunInfo runInfo;
  4623. Totals totals;
  4624. bool aborting;
  4625. };
  4626. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4627. struct BenchmarkInfo {
  4628. std::string name;
  4629. double estimatedDuration;
  4630. int iterations;
  4631. int samples;
  4632. unsigned int resamples;
  4633. double clockResolution;
  4634. double clockCost;
  4635. };
  4636. template <class Duration>
  4637. struct BenchmarkStats {
  4638. BenchmarkInfo info;
  4639. std::vector<Duration> samples;
  4640. Benchmark::Estimate<Duration> mean;
  4641. Benchmark::Estimate<Duration> standardDeviation;
  4642. Benchmark::OutlierClassification outliers;
  4643. double outlierVariance;
  4644. template <typename Duration2>
  4645. operator BenchmarkStats<Duration2>() const {
  4646. std::vector<Duration2> samples2;
  4647. samples2.reserve(samples.size());
  4648. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  4649. return {
  4650. info,
  4651. std::move(samples2),
  4652. mean,
  4653. standardDeviation,
  4654. outliers,
  4655. outlierVariance,
  4656. };
  4657. }
  4658. };
  4659. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4660. struct IStreamingReporter {
  4661. virtual ~IStreamingReporter() = default;
  4662. // Implementing class must also provide the following static methods:
  4663. // static std::string getDescription();
  4664. // static std::set<Verbosity> getSupportedVerbosities()
  4665. virtual ReporterPreferences getPreferences() const = 0;
  4666. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  4667. virtual void reportInvalidArguments(std::string const&) {}
  4668. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  4669. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  4670. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  4671. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  4672. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  4673. virtual void benchmarkPreparing( std::string const& ) {}
  4674. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  4675. virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
  4676. virtual void benchmarkFailed( std::string const& ) {}
  4677. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  4678. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  4679. // The return value indicates if the messages buffer should be cleared:
  4680. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  4681. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  4682. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  4683. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  4684. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  4685. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  4686. // Default empty implementation provided
  4687. virtual void fatalErrorEncountered( StringRef name );
  4688. virtual bool isMulti() const;
  4689. };
  4690. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  4691. struct IReporterFactory {
  4692. virtual ~IReporterFactory();
  4693. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  4694. virtual std::string getDescription() const = 0;
  4695. };
  4696. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  4697. struct IReporterRegistry {
  4698. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  4699. using Listeners = std::vector<IReporterFactoryPtr>;
  4700. virtual ~IReporterRegistry();
  4701. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  4702. virtual FactoryMap const& getFactories() const = 0;
  4703. virtual Listeners const& getListeners() const = 0;
  4704. };
  4705. } // end namespace Catch
  4706. // end catch_interfaces_reporter.h
  4707. #include <algorithm>
  4708. #include <cstring>
  4709. #include <cfloat>
  4710. #include <cstdio>
  4711. #include <cassert>
  4712. #include <memory>
  4713. #include <ostream>
  4714. namespace Catch {
  4715. void prepareExpandedExpression(AssertionResult& result);
  4716. // Returns double formatted as %.3f (format expected on output)
  4717. std::string getFormattedDuration( double duration );
  4718. //! Should the reporter show
  4719. bool shouldShowDuration( IConfig const& config, double duration );
  4720. std::string serializeFilters( std::vector<std::string> const& container );
  4721. template<typename DerivedT>
  4722. struct StreamingReporterBase : IStreamingReporter {
  4723. StreamingReporterBase( ReporterConfig const& _config )
  4724. : m_config( _config.fullConfig() ),
  4725. stream( _config.stream() )
  4726. {
  4727. m_reporterPrefs.shouldRedirectStdOut = false;
  4728. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4729. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4730. }
  4731. ReporterPreferences getPreferences() const override {
  4732. return m_reporterPrefs;
  4733. }
  4734. static std::set<Verbosity> getSupportedVerbosities() {
  4735. return { Verbosity::Normal };
  4736. }
  4737. ~StreamingReporterBase() override = default;
  4738. void noMatchingTestCases(std::string const&) override {}
  4739. void reportInvalidArguments(std::string const&) override {}
  4740. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  4741. currentTestRunInfo = _testRunInfo;
  4742. }
  4743. void testGroupStarting(GroupInfo const& _groupInfo) override {
  4744. currentGroupInfo = _groupInfo;
  4745. }
  4746. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  4747. currentTestCaseInfo = _testInfo;
  4748. }
  4749. void sectionStarting(SectionInfo const& _sectionInfo) override {
  4750. m_sectionStack.push_back(_sectionInfo);
  4751. }
  4752. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  4753. m_sectionStack.pop_back();
  4754. }
  4755. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  4756. currentTestCaseInfo.reset();
  4757. }
  4758. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  4759. currentGroupInfo.reset();
  4760. }
  4761. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  4762. currentTestCaseInfo.reset();
  4763. currentGroupInfo.reset();
  4764. currentTestRunInfo.reset();
  4765. }
  4766. void skipTest(TestCaseInfo const&) override {
  4767. // Don't do anything with this by default.
  4768. // It can optionally be overridden in the derived class.
  4769. }
  4770. IConfigPtr m_config;
  4771. std::ostream& stream;
  4772. LazyStat<TestRunInfo> currentTestRunInfo;
  4773. LazyStat<GroupInfo> currentGroupInfo;
  4774. LazyStat<TestCaseInfo> currentTestCaseInfo;
  4775. std::vector<SectionInfo> m_sectionStack;
  4776. ReporterPreferences m_reporterPrefs;
  4777. };
  4778. template<typename DerivedT>
  4779. struct CumulativeReporterBase : IStreamingReporter {
  4780. template<typename T, typename ChildNodeT>
  4781. struct Node {
  4782. explicit Node( T const& _value ) : value( _value ) {}
  4783. virtual ~Node() {}
  4784. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  4785. T value;
  4786. ChildNodes children;
  4787. };
  4788. struct SectionNode {
  4789. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  4790. virtual ~SectionNode() = default;
  4791. bool operator == (SectionNode const& other) const {
  4792. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  4793. }
  4794. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  4795. return operator==(*other);
  4796. }
  4797. SectionStats stats;
  4798. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  4799. using Assertions = std::vector<AssertionStats>;
  4800. ChildSections childSections;
  4801. Assertions assertions;
  4802. std::string stdOut;
  4803. std::string stdErr;
  4804. };
  4805. struct BySectionInfo {
  4806. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  4807. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  4808. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  4809. return ((node->stats.sectionInfo.name == m_other.name) &&
  4810. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  4811. }
  4812. void operator=(BySectionInfo const&) = delete;
  4813. private:
  4814. SectionInfo const& m_other;
  4815. };
  4816. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  4817. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  4818. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  4819. CumulativeReporterBase( ReporterConfig const& _config )
  4820. : m_config( _config.fullConfig() ),
  4821. stream( _config.stream() )
  4822. {
  4823. m_reporterPrefs.shouldRedirectStdOut = false;
  4824. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4825. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4826. }
  4827. ~CumulativeReporterBase() override = default;
  4828. ReporterPreferences getPreferences() const override {
  4829. return m_reporterPrefs;
  4830. }
  4831. static std::set<Verbosity> getSupportedVerbosities() {
  4832. return { Verbosity::Normal };
  4833. }
  4834. void testRunStarting( TestRunInfo const& ) override {}
  4835. void testGroupStarting( GroupInfo const& ) override {}
  4836. void testCaseStarting( TestCaseInfo const& ) override {}
  4837. void sectionStarting( SectionInfo const& sectionInfo ) override {
  4838. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  4839. std::shared_ptr<SectionNode> node;
  4840. if( m_sectionStack.empty() ) {
  4841. if( !m_rootSection )
  4842. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  4843. node = m_rootSection;
  4844. }
  4845. else {
  4846. SectionNode& parentNode = *m_sectionStack.back();
  4847. auto it =
  4848. std::find_if( parentNode.childSections.begin(),
  4849. parentNode.childSections.end(),
  4850. BySectionInfo( sectionInfo ) );
  4851. if( it == parentNode.childSections.end() ) {
  4852. node = std::make_shared<SectionNode>( incompleteStats );
  4853. parentNode.childSections.push_back( node );
  4854. }
  4855. else
  4856. node = *it;
  4857. }
  4858. m_sectionStack.push_back( node );
  4859. m_deepestSection = std::move(node);
  4860. }
  4861. void assertionStarting(AssertionInfo const&) override {}
  4862. bool assertionEnded(AssertionStats const& assertionStats) override {
  4863. assert(!m_sectionStack.empty());
  4864. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  4865. // which getExpandedExpression() calls to build the expression string.
  4866. // Our section stack copy of the assertionResult will likely outlive the
  4867. // temporary, so it must be expanded or discarded now to avoid calling
  4868. // a destroyed object later.
  4869. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  4870. SectionNode& sectionNode = *m_sectionStack.back();
  4871. sectionNode.assertions.push_back(assertionStats);
  4872. return true;
  4873. }
  4874. void sectionEnded(SectionStats const& sectionStats) override {
  4875. assert(!m_sectionStack.empty());
  4876. SectionNode& node = *m_sectionStack.back();
  4877. node.stats = sectionStats;
  4878. m_sectionStack.pop_back();
  4879. }
  4880. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  4881. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  4882. assert(m_sectionStack.size() == 0);
  4883. node->children.push_back(m_rootSection);
  4884. m_testCases.push_back(node);
  4885. m_rootSection.reset();
  4886. assert(m_deepestSection);
  4887. m_deepestSection->stdOut = testCaseStats.stdOut;
  4888. m_deepestSection->stdErr = testCaseStats.stdErr;
  4889. }
  4890. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  4891. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  4892. node->children.swap(m_testCases);
  4893. m_testGroups.push_back(node);
  4894. }
  4895. void testRunEnded(TestRunStats const& testRunStats) override {
  4896. auto node = std::make_shared<TestRunNode>(testRunStats);
  4897. node->children.swap(m_testGroups);
  4898. m_testRuns.push_back(node);
  4899. testRunEndedCumulative();
  4900. }
  4901. virtual void testRunEndedCumulative() = 0;
  4902. void skipTest(TestCaseInfo const&) override {}
  4903. IConfigPtr m_config;
  4904. std::ostream& stream;
  4905. std::vector<AssertionStats> m_assertions;
  4906. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  4907. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  4908. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  4909. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  4910. std::shared_ptr<SectionNode> m_rootSection;
  4911. std::shared_ptr<SectionNode> m_deepestSection;
  4912. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  4913. ReporterPreferences m_reporterPrefs;
  4914. };
  4915. template<char C>
  4916. char const* getLineOfChars() {
  4917. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  4918. if( !*line ) {
  4919. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  4920. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  4921. }
  4922. return line;
  4923. }
  4924. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  4925. TestEventListenerBase( ReporterConfig const& _config );
  4926. static std::set<Verbosity> getSupportedVerbosities();
  4927. void assertionStarting(AssertionInfo const&) override;
  4928. bool assertionEnded(AssertionStats const&) override;
  4929. };
  4930. } // end namespace Catch
  4931. // end catch_reporter_bases.hpp
  4932. // start catch_console_colour.h
  4933. namespace Catch {
  4934. struct Colour {
  4935. enum Code {
  4936. None = 0,
  4937. White,
  4938. Red,
  4939. Green,
  4940. Blue,
  4941. Cyan,
  4942. Yellow,
  4943. Grey,
  4944. Bright = 0x10,
  4945. BrightRed = Bright | Red,
  4946. BrightGreen = Bright | Green,
  4947. LightGrey = Bright | Grey,
  4948. BrightWhite = Bright | White,
  4949. BrightYellow = Bright | Yellow,
  4950. // By intention
  4951. FileName = LightGrey,
  4952. Warning = BrightYellow,
  4953. ResultError = BrightRed,
  4954. ResultSuccess = BrightGreen,
  4955. ResultExpectedFailure = Warning,
  4956. Error = BrightRed,
  4957. Success = Green,
  4958. OriginalExpression = Cyan,
  4959. ReconstructedExpression = BrightYellow,
  4960. SecondaryText = LightGrey,
  4961. Headers = White
  4962. };
  4963. // Use constructed object for RAII guard
  4964. Colour( Code _colourCode );
  4965. Colour( Colour&& other ) noexcept;
  4966. Colour& operator=( Colour&& other ) noexcept;
  4967. ~Colour();
  4968. // Use static method for one-shot changes
  4969. static void use( Code _colourCode );
  4970. private:
  4971. bool m_moved = false;
  4972. };
  4973. std::ostream& operator << ( std::ostream& os, Colour const& );
  4974. } // end namespace Catch
  4975. // end catch_console_colour.h
  4976. // start catch_reporter_registrars.hpp
  4977. namespace Catch {
  4978. template<typename T>
  4979. class ReporterRegistrar {
  4980. class ReporterFactory : public IReporterFactory {
  4981. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4982. return std::unique_ptr<T>( new T( config ) );
  4983. }
  4984. std::string getDescription() const override {
  4985. return T::getDescription();
  4986. }
  4987. };
  4988. public:
  4989. explicit ReporterRegistrar( std::string const& name ) {
  4990. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  4991. }
  4992. };
  4993. template<typename T>
  4994. class ListenerRegistrar {
  4995. class ListenerFactory : public IReporterFactory {
  4996. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4997. return std::unique_ptr<T>( new T( config ) );
  4998. }
  4999. std::string getDescription() const override {
  5000. return std::string();
  5001. }
  5002. };
  5003. public:
  5004. ListenerRegistrar() {
  5005. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  5006. }
  5007. };
  5008. }
  5009. #if !defined(CATCH_CONFIG_DISABLE)
  5010. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  5011. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  5012. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  5013. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  5014. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  5015. #define CATCH_REGISTER_LISTENER( listenerType ) \
  5016. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
  5017. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  5018. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  5019. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  5020. #else // CATCH_CONFIG_DISABLE
  5021. #define CATCH_REGISTER_REPORTER(name, reporterType)
  5022. #define CATCH_REGISTER_LISTENER(listenerType)
  5023. #endif // CATCH_CONFIG_DISABLE
  5024. // end catch_reporter_registrars.hpp
  5025. // Allow users to base their work off existing reporters
  5026. // start catch_reporter_compact.h
  5027. namespace Catch {
  5028. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  5029. using StreamingReporterBase::StreamingReporterBase;
  5030. ~CompactReporter() override;
  5031. static std::string getDescription();
  5032. void noMatchingTestCases(std::string const& spec) override;
  5033. void assertionStarting(AssertionInfo const&) override;
  5034. bool assertionEnded(AssertionStats const& _assertionStats) override;
  5035. void sectionEnded(SectionStats const& _sectionStats) override;
  5036. void testRunEnded(TestRunStats const& _testRunStats) override;
  5037. };
  5038. } // end namespace Catch
  5039. // end catch_reporter_compact.h
  5040. // start catch_reporter_console.h
  5041. #if defined(_MSC_VER)
  5042. #pragma warning(push)
  5043. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  5044. // Note that 4062 (not all labels are handled
  5045. // and default is missing) is enabled
  5046. #endif
  5047. namespace Catch {
  5048. // Fwd decls
  5049. struct SummaryColumn;
  5050. class TablePrinter;
  5051. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  5052. std::unique_ptr<TablePrinter> m_tablePrinter;
  5053. ConsoleReporter(ReporterConfig const& config);
  5054. ~ConsoleReporter() override;
  5055. static std::string getDescription();
  5056. void noMatchingTestCases(std::string const& spec) override;
  5057. void reportInvalidArguments(std::string const&arg) override;
  5058. void assertionStarting(AssertionInfo const&) override;
  5059. bool assertionEnded(AssertionStats const& _assertionStats) override;
  5060. void sectionStarting(SectionInfo const& _sectionInfo) override;
  5061. void sectionEnded(SectionStats const& _sectionStats) override;
  5062. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5063. void benchmarkPreparing(std::string const& name) override;
  5064. void benchmarkStarting(BenchmarkInfo const& info) override;
  5065. void benchmarkEnded(BenchmarkStats<> const& stats) override;
  5066. void benchmarkFailed(std::string const& error) override;
  5067. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  5068. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  5069. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  5070. void testRunEnded(TestRunStats const& _testRunStats) override;
  5071. void testRunStarting(TestRunInfo const& _testRunInfo) override;
  5072. private:
  5073. void lazyPrint();
  5074. void lazyPrintWithoutClosingBenchmarkTable();
  5075. void lazyPrintRunInfo();
  5076. void lazyPrintGroupInfo();
  5077. void printTestCaseAndSectionHeader();
  5078. void printClosedHeader(std::string const& _name);
  5079. void printOpenHeader(std::string const& _name);
  5080. // if string has a : in first line will set indent to follow it on
  5081. // subsequent lines
  5082. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  5083. void printTotals(Totals const& totals);
  5084. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  5085. void printTotalsDivider(Totals const& totals);
  5086. void printSummaryDivider();
  5087. void printTestFilters();
  5088. private:
  5089. bool m_headerPrinted = false;
  5090. };
  5091. } // end namespace Catch
  5092. #if defined(_MSC_VER)
  5093. #pragma warning(pop)
  5094. #endif
  5095. // end catch_reporter_console.h
  5096. // start catch_reporter_junit.h
  5097. // start catch_xmlwriter.h
  5098. #include <vector>
  5099. namespace Catch {
  5100. enum class XmlFormatting {
  5101. None = 0x00,
  5102. Indent = 0x01,
  5103. Newline = 0x02,
  5104. };
  5105. XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
  5106. XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
  5107. class XmlEncode {
  5108. public:
  5109. enum ForWhat { ForTextNodes, ForAttributes };
  5110. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  5111. void encodeTo( std::ostream& os ) const;
  5112. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  5113. private:
  5114. std::string m_str;
  5115. ForWhat m_forWhat;
  5116. };
  5117. class XmlWriter {
  5118. public:
  5119. class ScopedElement {
  5120. public:
  5121. ScopedElement( XmlWriter* writer, XmlFormatting fmt );
  5122. ScopedElement( ScopedElement&& other ) noexcept;
  5123. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  5124. ~ScopedElement();
  5125. ScopedElement& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
  5126. template<typename T>
  5127. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  5128. m_writer->writeAttribute( name, attribute );
  5129. return *this;
  5130. }
  5131. private:
  5132. mutable XmlWriter* m_writer = nullptr;
  5133. XmlFormatting m_fmt;
  5134. };
  5135. XmlWriter( std::ostream& os = Catch::cout() );
  5136. ~XmlWriter();
  5137. XmlWriter( XmlWriter const& ) = delete;
  5138. XmlWriter& operator=( XmlWriter const& ) = delete;
  5139. XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5140. ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5141. XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5142. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  5143. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  5144. template<typename T>
  5145. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  5146. ReusableStringStream rss;
  5147. rss << attribute;
  5148. return writeAttribute( name, rss.str() );
  5149. }
  5150. XmlWriter& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5151. XmlWriter& writeComment(std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
  5152. void writeStylesheetRef( std::string const& url );
  5153. XmlWriter& writeBlankLine();
  5154. void ensureTagClosed();
  5155. private:
  5156. void applyFormatting(XmlFormatting fmt);
  5157. void writeDeclaration();
  5158. void newlineIfNecessary();
  5159. bool m_tagIsOpen = false;
  5160. bool m_needsNewline = false;
  5161. std::vector<std::string> m_tags;
  5162. std::string m_indent;
  5163. std::ostream& m_os;
  5164. };
  5165. }
  5166. // end catch_xmlwriter.h
  5167. namespace Catch {
  5168. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  5169. public:
  5170. JunitReporter(ReporterConfig const& _config);
  5171. ~JunitReporter() override;
  5172. static std::string getDescription();
  5173. void noMatchingTestCases(std::string const& /*spec*/) override;
  5174. void testRunStarting(TestRunInfo const& runInfo) override;
  5175. void testGroupStarting(GroupInfo const& groupInfo) override;
  5176. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  5177. bool assertionEnded(AssertionStats const& assertionStats) override;
  5178. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5179. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5180. void testRunEndedCumulative() override;
  5181. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  5182. void writeTestCase(TestCaseNode const& testCaseNode);
  5183. void writeSection( std::string const& className,
  5184. std::string const& rootName,
  5185. SectionNode const& sectionNode,
  5186. bool testOkToFail );
  5187. void writeAssertions(SectionNode const& sectionNode);
  5188. void writeAssertion(AssertionStats const& stats);
  5189. XmlWriter xml;
  5190. Timer suiteTimer;
  5191. std::string stdOutForSuite;
  5192. std::string stdErrForSuite;
  5193. unsigned int unexpectedExceptions = 0;
  5194. bool m_okToFail = false;
  5195. };
  5196. } // end namespace Catch
  5197. // end catch_reporter_junit.h
  5198. // start catch_reporter_xml.h
  5199. namespace Catch {
  5200. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  5201. public:
  5202. XmlReporter(ReporterConfig const& _config);
  5203. ~XmlReporter() override;
  5204. static std::string getDescription();
  5205. virtual std::string getStylesheetRef() const;
  5206. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  5207. public: // StreamingReporterBase
  5208. void noMatchingTestCases(std::string const& s) override;
  5209. void testRunStarting(TestRunInfo const& testInfo) override;
  5210. void testGroupStarting(GroupInfo const& groupInfo) override;
  5211. void testCaseStarting(TestCaseInfo const& testInfo) override;
  5212. void sectionStarting(SectionInfo const& sectionInfo) override;
  5213. void assertionStarting(AssertionInfo const&) override;
  5214. bool assertionEnded(AssertionStats const& assertionStats) override;
  5215. void sectionEnded(SectionStats const& sectionStats) override;
  5216. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  5217. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  5218. void testRunEnded(TestRunStats const& testRunStats) override;
  5219. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5220. void benchmarkPreparing(std::string const& name) override;
  5221. void benchmarkStarting(BenchmarkInfo const&) override;
  5222. void benchmarkEnded(BenchmarkStats<> const&) override;
  5223. void benchmarkFailed(std::string const&) override;
  5224. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  5225. private:
  5226. Timer m_testCaseTimer;
  5227. XmlWriter m_xml;
  5228. int m_sectionDepth = 0;
  5229. };
  5230. } // end namespace Catch
  5231. // end catch_reporter_xml.h
  5232. // end catch_external_interfaces.h
  5233. #endif
  5234. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  5235. // start catch_benchmarking_all.hpp
  5236. // A proxy header that includes all of the benchmarking headers to allow
  5237. // concise include of the benchmarking features. You should prefer the
  5238. // individual includes in standard use.
  5239. // start catch_benchmark.hpp
  5240. // Benchmark
  5241. // start catch_chronometer.hpp
  5242. // User-facing chronometer
  5243. // start catch_clock.hpp
  5244. // Clocks
  5245. #include <chrono>
  5246. #include <ratio>
  5247. namespace Catch {
  5248. namespace Benchmark {
  5249. template <typename Clock>
  5250. using ClockDuration = typename Clock::duration;
  5251. template <typename Clock>
  5252. using FloatDuration = std::chrono::duration<double, typename Clock::period>;
  5253. template <typename Clock>
  5254. using TimePoint = typename Clock::time_point;
  5255. using default_clock = std::chrono::steady_clock;
  5256. template <typename Clock>
  5257. struct now {
  5258. TimePoint<Clock> operator()() const {
  5259. return Clock::now();
  5260. }
  5261. };
  5262. using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
  5263. } // namespace Benchmark
  5264. } // namespace Catch
  5265. // end catch_clock.hpp
  5266. // start catch_optimizer.hpp
  5267. // Hinting the optimizer
  5268. #if defined(_MSC_VER)
  5269. # include <atomic> // atomic_thread_fence
  5270. #endif
  5271. namespace Catch {
  5272. namespace Benchmark {
  5273. #if defined(__GNUC__) || defined(__clang__)
  5274. template <typename T>
  5275. inline void keep_memory(T* p) {
  5276. asm volatile("" : : "g"(p) : "memory");
  5277. }
  5278. inline void keep_memory() {
  5279. asm volatile("" : : : "memory");
  5280. }
  5281. namespace Detail {
  5282. inline void optimizer_barrier() { keep_memory(); }
  5283. } // namespace Detail
  5284. #elif defined(_MSC_VER)
  5285. #pragma optimize("", off)
  5286. template <typename T>
  5287. inline void keep_memory(T* p) {
  5288. // thanks @milleniumbug
  5289. *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
  5290. }
  5291. // TODO equivalent keep_memory()
  5292. #pragma optimize("", on)
  5293. namespace Detail {
  5294. inline void optimizer_barrier() {
  5295. std::atomic_thread_fence(std::memory_order_seq_cst);
  5296. }
  5297. } // namespace Detail
  5298. #endif
  5299. template <typename T>
  5300. inline void deoptimize_value(T&& x) {
  5301. keep_memory(&x);
  5302. }
  5303. template <typename Fn, typename... Args>
  5304. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
  5305. deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
  5306. }
  5307. template <typename Fn, typename... Args>
  5308. inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
  5309. std::forward<Fn>(fn) (std::forward<Args...>(args...));
  5310. }
  5311. } // namespace Benchmark
  5312. } // namespace Catch
  5313. // end catch_optimizer.hpp
  5314. // start catch_complete_invoke.hpp
  5315. // Invoke with a special case for void
  5316. #include <type_traits>
  5317. #include <utility>
  5318. namespace Catch {
  5319. namespace Benchmark {
  5320. namespace Detail {
  5321. template <typename T>
  5322. struct CompleteType { using type = T; };
  5323. template <>
  5324. struct CompleteType<void> { struct type {}; };
  5325. template <typename T>
  5326. using CompleteType_t = typename CompleteType<T>::type;
  5327. template <typename Result>
  5328. struct CompleteInvoker {
  5329. template <typename Fun, typename... Args>
  5330. static Result invoke(Fun&& fun, Args&&... args) {
  5331. return std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5332. }
  5333. };
  5334. template <>
  5335. struct CompleteInvoker<void> {
  5336. template <typename Fun, typename... Args>
  5337. static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
  5338. std::forward<Fun>(fun)(std::forward<Args>(args)...);
  5339. return {};
  5340. }
  5341. };
  5342. // invoke and not return void :(
  5343. template <typename Fun, typename... Args>
  5344. CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
  5345. return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
  5346. }
  5347. const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
  5348. } // namespace Detail
  5349. template <typename Fun>
  5350. Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
  5351. CATCH_TRY{
  5352. return Detail::complete_invoke(std::forward<Fun>(fun));
  5353. } CATCH_CATCH_ALL{
  5354. getResultCapture().benchmarkFailed(translateActiveException());
  5355. CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
  5356. }
  5357. }
  5358. } // namespace Benchmark
  5359. } // namespace Catch
  5360. // end catch_complete_invoke.hpp
  5361. namespace Catch {
  5362. namespace Benchmark {
  5363. namespace Detail {
  5364. struct ChronometerConcept {
  5365. virtual void start() = 0;
  5366. virtual void finish() = 0;
  5367. virtual ~ChronometerConcept() = default;
  5368. };
  5369. template <typename Clock>
  5370. struct ChronometerModel final : public ChronometerConcept {
  5371. void start() override { started = Clock::now(); }
  5372. void finish() override { finished = Clock::now(); }
  5373. ClockDuration<Clock> elapsed() const { return finished - started; }
  5374. TimePoint<Clock> started;
  5375. TimePoint<Clock> finished;
  5376. };
  5377. } // namespace Detail
  5378. struct Chronometer {
  5379. public:
  5380. template <typename Fun>
  5381. void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
  5382. int runs() const { return k; }
  5383. Chronometer(Detail::ChronometerConcept& meter, int k)
  5384. : impl(&meter)
  5385. , k(k) {}
  5386. private:
  5387. template <typename Fun>
  5388. void measure(Fun&& fun, std::false_type) {
  5389. measure([&fun](int) { return fun(); }, std::true_type());
  5390. }
  5391. template <typename Fun>
  5392. void measure(Fun&& fun, std::true_type) {
  5393. Detail::optimizer_barrier();
  5394. impl->start();
  5395. for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
  5396. impl->finish();
  5397. Detail::optimizer_barrier();
  5398. }
  5399. Detail::ChronometerConcept* impl;
  5400. int k;
  5401. };
  5402. } // namespace Benchmark
  5403. } // namespace Catch
  5404. // end catch_chronometer.hpp
  5405. // start catch_environment.hpp
  5406. // Environment information
  5407. namespace Catch {
  5408. namespace Benchmark {
  5409. template <typename Duration>
  5410. struct EnvironmentEstimate {
  5411. Duration mean;
  5412. OutlierClassification outliers;
  5413. template <typename Duration2>
  5414. operator EnvironmentEstimate<Duration2>() const {
  5415. return { mean, outliers };
  5416. }
  5417. };
  5418. template <typename Clock>
  5419. struct Environment {
  5420. using clock_type = Clock;
  5421. EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
  5422. EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
  5423. };
  5424. } // namespace Benchmark
  5425. } // namespace Catch
  5426. // end catch_environment.hpp
  5427. // start catch_execution_plan.hpp
  5428. // Execution plan
  5429. // start catch_benchmark_function.hpp
  5430. // Dumb std::function implementation for consistent call overhead
  5431. #include <cassert>
  5432. #include <type_traits>
  5433. #include <utility>
  5434. #include <memory>
  5435. namespace Catch {
  5436. namespace Benchmark {
  5437. namespace Detail {
  5438. template <typename T>
  5439. using Decay = typename std::decay<T>::type;
  5440. template <typename T, typename U>
  5441. struct is_related
  5442. : std::is_same<Decay<T>, Decay<U>> {};
  5443. /// We need to reinvent std::function because every piece of code that might add overhead
  5444. /// in a measurement context needs to have consistent performance characteristics so that we
  5445. /// can account for it in the measurement.
  5446. /// Implementations of std::function with optimizations that aren't always applicable, like
  5447. /// small buffer optimizations, are not uncommon.
  5448. /// This is effectively an implementation of std::function without any such optimizations;
  5449. /// it may be slow, but it is consistently slow.
  5450. struct BenchmarkFunction {
  5451. private:
  5452. struct callable {
  5453. virtual void call(Chronometer meter) const = 0;
  5454. virtual callable* clone() const = 0;
  5455. virtual ~callable() = default;
  5456. };
  5457. template <typename Fun>
  5458. struct model : public callable {
  5459. model(Fun&& fun) : fun(std::move(fun)) {}
  5460. model(Fun const& fun) : fun(fun) {}
  5461. model<Fun>* clone() const override { return new model<Fun>(*this); }
  5462. void call(Chronometer meter) const override {
  5463. call(meter, is_callable<Fun(Chronometer)>());
  5464. }
  5465. void call(Chronometer meter, std::true_type) const {
  5466. fun(meter);
  5467. }
  5468. void call(Chronometer meter, std::false_type) const {
  5469. meter.measure(fun);
  5470. }
  5471. Fun fun;
  5472. };
  5473. struct do_nothing { void operator()() const {} };
  5474. template <typename T>
  5475. BenchmarkFunction(model<T>* c) : f(c) {}
  5476. public:
  5477. BenchmarkFunction()
  5478. : f(new model<do_nothing>{ {} }) {}
  5479. template <typename Fun,
  5480. typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
  5481. BenchmarkFunction(Fun&& fun)
  5482. : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
  5483. BenchmarkFunction(BenchmarkFunction&& that)
  5484. : f(std::move(that.f)) {}
  5485. BenchmarkFunction(BenchmarkFunction const& that)
  5486. : f(that.f->clone()) {}
  5487. BenchmarkFunction& operator=(BenchmarkFunction&& that) {
  5488. f = std::move(that.f);
  5489. return *this;
  5490. }
  5491. BenchmarkFunction& operator=(BenchmarkFunction const& that) {
  5492. f.reset(that.f->clone());
  5493. return *this;
  5494. }
  5495. void operator()(Chronometer meter) const { f->call(meter); }
  5496. private:
  5497. std::unique_ptr<callable> f;
  5498. };
  5499. } // namespace Detail
  5500. } // namespace Benchmark
  5501. } // namespace Catch
  5502. // end catch_benchmark_function.hpp
  5503. // start catch_repeat.hpp
  5504. // repeat algorithm
  5505. #include <type_traits>
  5506. #include <utility>
  5507. namespace Catch {
  5508. namespace Benchmark {
  5509. namespace Detail {
  5510. template <typename Fun>
  5511. struct repeater {
  5512. void operator()(int k) const {
  5513. for (int i = 0; i < k; ++i) {
  5514. fun();
  5515. }
  5516. }
  5517. Fun fun;
  5518. };
  5519. template <typename Fun>
  5520. repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
  5521. return { std::forward<Fun>(fun) };
  5522. }
  5523. } // namespace Detail
  5524. } // namespace Benchmark
  5525. } // namespace Catch
  5526. // end catch_repeat.hpp
  5527. // start catch_run_for_at_least.hpp
  5528. // Run a function for a minimum amount of time
  5529. // start catch_measure.hpp
  5530. // Measure
  5531. // start catch_timing.hpp
  5532. // Timing
  5533. #include <tuple>
  5534. #include <type_traits>
  5535. namespace Catch {
  5536. namespace Benchmark {
  5537. template <typename Duration, typename Result>
  5538. struct Timing {
  5539. Duration elapsed;
  5540. Result result;
  5541. int iterations;
  5542. };
  5543. template <typename Clock, typename Func, typename... Args>
  5544. using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
  5545. } // namespace Benchmark
  5546. } // namespace Catch
  5547. // end catch_timing.hpp
  5548. #include <utility>
  5549. namespace Catch {
  5550. namespace Benchmark {
  5551. namespace Detail {
  5552. template <typename Clock, typename Fun, typename... Args>
  5553. TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
  5554. auto start = Clock::now();
  5555. auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
  5556. auto end = Clock::now();
  5557. auto delta = end - start;
  5558. return { delta, std::forward<decltype(r)>(r), 1 };
  5559. }
  5560. } // namespace Detail
  5561. } // namespace Benchmark
  5562. } // namespace Catch
  5563. // end catch_measure.hpp
  5564. #include <utility>
  5565. #include <type_traits>
  5566. namespace Catch {
  5567. namespace Benchmark {
  5568. namespace Detail {
  5569. template <typename Clock, typename Fun>
  5570. TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
  5571. return Detail::measure<Clock>(fun, iters);
  5572. }
  5573. template <typename Clock, typename Fun>
  5574. TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
  5575. Detail::ChronometerModel<Clock> meter;
  5576. auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
  5577. return { meter.elapsed(), std::move(result), iters };
  5578. }
  5579. template <typename Clock, typename Fun>
  5580. using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
  5581. struct optimized_away_error : std::exception {
  5582. const char* what() const noexcept override {
  5583. return "could not measure benchmark, maybe it was optimized away";
  5584. }
  5585. };
  5586. template <typename Clock, typename Fun>
  5587. TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
  5588. auto iters = seed;
  5589. while (iters < (1 << 30)) {
  5590. auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
  5591. if (Timing.elapsed >= how_long) {
  5592. return { Timing.elapsed, std::move(Timing.result), iters };
  5593. }
  5594. iters *= 2;
  5595. }
  5596. Catch::throw_exception(optimized_away_error{});
  5597. }
  5598. } // namespace Detail
  5599. } // namespace Benchmark
  5600. } // namespace Catch
  5601. // end catch_run_for_at_least.hpp
  5602. #include <algorithm>
  5603. #include <iterator>
  5604. namespace Catch {
  5605. namespace Benchmark {
  5606. template <typename Duration>
  5607. struct ExecutionPlan {
  5608. int iterations_per_sample;
  5609. Duration estimated_duration;
  5610. Detail::BenchmarkFunction benchmark;
  5611. Duration warmup_time;
  5612. int warmup_iterations;
  5613. template <typename Duration2>
  5614. operator ExecutionPlan<Duration2>() const {
  5615. return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
  5616. }
  5617. template <typename Clock>
  5618. std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5619. // warmup a bit
  5620. Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
  5621. std::vector<FloatDuration<Clock>> times;
  5622. times.reserve(cfg.benchmarkSamples());
  5623. std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
  5624. Detail::ChronometerModel<Clock> model;
  5625. this->benchmark(Chronometer(model, iterations_per_sample));
  5626. auto sample_time = model.elapsed() - env.clock_cost.mean;
  5627. if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
  5628. return sample_time / iterations_per_sample;
  5629. });
  5630. return times;
  5631. }
  5632. };
  5633. } // namespace Benchmark
  5634. } // namespace Catch
  5635. // end catch_execution_plan.hpp
  5636. // start catch_estimate_clock.hpp
  5637. // Environment measurement
  5638. // start catch_stats.hpp
  5639. // Statistical analysis tools
  5640. #include <algorithm>
  5641. #include <functional>
  5642. #include <vector>
  5643. #include <iterator>
  5644. #include <numeric>
  5645. #include <tuple>
  5646. #include <cmath>
  5647. #include <utility>
  5648. #include <cstddef>
  5649. #include <random>
  5650. namespace Catch {
  5651. namespace Benchmark {
  5652. namespace Detail {
  5653. using sample = std::vector<double>;
  5654. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5655. template <typename Iterator>
  5656. OutlierClassification classify_outliers(Iterator first, Iterator last) {
  5657. std::vector<double> copy(first, last);
  5658. auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
  5659. auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
  5660. auto iqr = q3 - q1;
  5661. auto los = q1 - (iqr * 3.);
  5662. auto lom = q1 - (iqr * 1.5);
  5663. auto him = q3 + (iqr * 1.5);
  5664. auto his = q3 + (iqr * 3.);
  5665. OutlierClassification o;
  5666. for (; first != last; ++first) {
  5667. auto&& t = *first;
  5668. if (t < los) ++o.low_severe;
  5669. else if (t < lom) ++o.low_mild;
  5670. else if (t > his) ++o.high_severe;
  5671. else if (t > him) ++o.high_mild;
  5672. ++o.samples_seen;
  5673. }
  5674. return o;
  5675. }
  5676. template <typename Iterator>
  5677. double mean(Iterator first, Iterator last) {
  5678. auto count = last - first;
  5679. double sum = std::accumulate(first, last, 0.);
  5680. return sum / count;
  5681. }
  5682. template <typename URng, typename Iterator, typename Estimator>
  5683. sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
  5684. auto n = last - first;
  5685. std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
  5686. sample out;
  5687. out.reserve(resamples);
  5688. std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
  5689. std::vector<double> resampled;
  5690. resampled.reserve(n);
  5691. std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
  5692. return estimator(resampled.begin(), resampled.end());
  5693. });
  5694. std::sort(out.begin(), out.end());
  5695. return out;
  5696. }
  5697. template <typename Estimator, typename Iterator>
  5698. sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
  5699. auto n = last - first;
  5700. auto second = std::next(first);
  5701. sample results;
  5702. results.reserve(n);
  5703. for (auto it = first; it != last; ++it) {
  5704. std::iter_swap(it, first);
  5705. results.push_back(estimator(second, last));
  5706. }
  5707. return results;
  5708. }
  5709. inline double normal_cdf(double x) {
  5710. return std::erfc(-x / std::sqrt(2.0)) / 2.0;
  5711. }
  5712. double erfc_inv(double x);
  5713. double normal_quantile(double p);
  5714. template <typename Iterator, typename Estimator>
  5715. Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
  5716. auto n_samples = last - first;
  5717. double point = estimator(first, last);
  5718. // Degenerate case with a single sample
  5719. if (n_samples == 1) return { point, point, point, confidence_level };
  5720. sample jack = jackknife(estimator, first, last);
  5721. double jack_mean = mean(jack.begin(), jack.end());
  5722. double sum_squares, sum_cubes;
  5723. std::tie(sum_squares, sum_cubes) = std::accumulate(jack.begin(), jack.end(), std::make_pair(0., 0.), [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> {
  5724. auto d = jack_mean - x;
  5725. auto d2 = d * d;
  5726. auto d3 = d2 * d;
  5727. return { sqcb.first + d2, sqcb.second + d3 };
  5728. });
  5729. double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
  5730. int n = static_cast<int>(resample.size());
  5731. double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
  5732. // degenerate case with uniform samples
  5733. if (prob_n == 0) return { point, point, point, confidence_level };
  5734. double bias = normal_quantile(prob_n);
  5735. double z1 = normal_quantile((1. - confidence_level) / 2.);
  5736. auto cumn = [n](double x) -> int {
  5737. return std::lround(normal_cdf(x) * n); };
  5738. auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
  5739. double b1 = bias + z1;
  5740. double b2 = bias - z1;
  5741. double a1 = a(b1);
  5742. double a2 = a(b2);
  5743. auto lo = (std::max)(cumn(a1), 0);
  5744. auto hi = (std::min)(cumn(a2), n - 1);
  5745. return { point, resample[lo], resample[hi], confidence_level };
  5746. }
  5747. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
  5748. struct bootstrap_analysis {
  5749. Estimate<double> mean;
  5750. Estimate<double> standard_deviation;
  5751. double outlier_variance;
  5752. };
  5753. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
  5754. } // namespace Detail
  5755. } // namespace Benchmark
  5756. } // namespace Catch
  5757. // end catch_stats.hpp
  5758. #include <algorithm>
  5759. #include <iterator>
  5760. #include <tuple>
  5761. #include <vector>
  5762. #include <cmath>
  5763. namespace Catch {
  5764. namespace Benchmark {
  5765. namespace Detail {
  5766. template <typename Clock>
  5767. std::vector<double> resolution(int k) {
  5768. std::vector<TimePoint<Clock>> times;
  5769. times.reserve(k + 1);
  5770. std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
  5771. std::vector<double> deltas;
  5772. deltas.reserve(k);
  5773. std::transform(std::next(times.begin()), times.end(), times.begin(),
  5774. std::back_inserter(deltas),
  5775. [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
  5776. return deltas;
  5777. }
  5778. const auto warmup_iterations = 10000;
  5779. const auto warmup_time = std::chrono::milliseconds(100);
  5780. const auto minimum_ticks = 1000;
  5781. const auto warmup_seed = 10000;
  5782. const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
  5783. const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
  5784. const auto clock_cost_estimation_tick_limit = 100000;
  5785. const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
  5786. const auto clock_cost_estimation_iterations = 10000;
  5787. template <typename Clock>
  5788. int warmup() {
  5789. return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
  5790. .iterations;
  5791. }
  5792. template <typename Clock>
  5793. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
  5794. auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
  5795. .result;
  5796. return {
  5797. FloatDuration<Clock>(mean(r.begin(), r.end())),
  5798. classify_outliers(r.begin(), r.end()),
  5799. };
  5800. }
  5801. template <typename Clock>
  5802. EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
  5803. auto time_limit = (std::min)(
  5804. resolution * clock_cost_estimation_tick_limit,
  5805. FloatDuration<Clock>(clock_cost_estimation_time_limit));
  5806. auto time_clock = [](int k) {
  5807. return Detail::measure<Clock>([k] {
  5808. for (int i = 0; i < k; ++i) {
  5809. volatile auto ignored = Clock::now();
  5810. (void)ignored;
  5811. }
  5812. }).elapsed;
  5813. };
  5814. time_clock(1);
  5815. int iters = clock_cost_estimation_iterations;
  5816. auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
  5817. std::vector<double> times;
  5818. int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
  5819. times.reserve(nsamples);
  5820. std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
  5821. return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
  5822. });
  5823. return {
  5824. FloatDuration<Clock>(mean(times.begin(), times.end())),
  5825. classify_outliers(times.begin(), times.end()),
  5826. };
  5827. }
  5828. template <typename Clock>
  5829. Environment<FloatDuration<Clock>> measure_environment() {
  5830. static Environment<FloatDuration<Clock>>* env = nullptr;
  5831. if (env) {
  5832. return *env;
  5833. }
  5834. auto iters = Detail::warmup<Clock>();
  5835. auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
  5836. auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
  5837. env = new Environment<FloatDuration<Clock>>{ resolution, cost };
  5838. return *env;
  5839. }
  5840. } // namespace Detail
  5841. } // namespace Benchmark
  5842. } // namespace Catch
  5843. // end catch_estimate_clock.hpp
  5844. // start catch_analyse.hpp
  5845. // Run and analyse one benchmark
  5846. // start catch_sample_analysis.hpp
  5847. // Benchmark results
  5848. #include <algorithm>
  5849. #include <vector>
  5850. #include <string>
  5851. #include <iterator>
  5852. namespace Catch {
  5853. namespace Benchmark {
  5854. template <typename Duration>
  5855. struct SampleAnalysis {
  5856. std::vector<Duration> samples;
  5857. Estimate<Duration> mean;
  5858. Estimate<Duration> standard_deviation;
  5859. OutlierClassification outliers;
  5860. double outlier_variance;
  5861. template <typename Duration2>
  5862. operator SampleAnalysis<Duration2>() const {
  5863. std::vector<Duration2> samples2;
  5864. samples2.reserve(samples.size());
  5865. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
  5866. return {
  5867. std::move(samples2),
  5868. mean,
  5869. standard_deviation,
  5870. outliers,
  5871. outlier_variance,
  5872. };
  5873. }
  5874. };
  5875. } // namespace Benchmark
  5876. } // namespace Catch
  5877. // end catch_sample_analysis.hpp
  5878. #include <algorithm>
  5879. #include <iterator>
  5880. #include <vector>
  5881. namespace Catch {
  5882. namespace Benchmark {
  5883. namespace Detail {
  5884. template <typename Duration, typename Iterator>
  5885. SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
  5886. if (!cfg.benchmarkNoAnalysis()) {
  5887. std::vector<double> samples;
  5888. samples.reserve(last - first);
  5889. std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
  5890. auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
  5891. auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
  5892. auto wrap_estimate = [](Estimate<double> e) {
  5893. return Estimate<Duration> {
  5894. Duration(e.point),
  5895. Duration(e.lower_bound),
  5896. Duration(e.upper_bound),
  5897. e.confidence_interval,
  5898. };
  5899. };
  5900. std::vector<Duration> samples2;
  5901. samples2.reserve(samples.size());
  5902. std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
  5903. return {
  5904. std::move(samples2),
  5905. wrap_estimate(analysis.mean),
  5906. wrap_estimate(analysis.standard_deviation),
  5907. outliers,
  5908. analysis.outlier_variance,
  5909. };
  5910. } else {
  5911. std::vector<Duration> samples;
  5912. samples.reserve(last - first);
  5913. Duration mean = Duration(0);
  5914. int i = 0;
  5915. for (auto it = first; it < last; ++it, ++i) {
  5916. samples.push_back(Duration(*it));
  5917. mean += Duration(*it);
  5918. }
  5919. mean /= i;
  5920. return {
  5921. std::move(samples),
  5922. Estimate<Duration>{mean, mean, mean, 0.0},
  5923. Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
  5924. OutlierClassification{},
  5925. 0.0
  5926. };
  5927. }
  5928. }
  5929. } // namespace Detail
  5930. } // namespace Benchmark
  5931. } // namespace Catch
  5932. // end catch_analyse.hpp
  5933. #include <algorithm>
  5934. #include <functional>
  5935. #include <string>
  5936. #include <vector>
  5937. #include <cmath>
  5938. namespace Catch {
  5939. namespace Benchmark {
  5940. struct Benchmark {
  5941. Benchmark(std::string &&name)
  5942. : name(std::move(name)) {}
  5943. template <class FUN>
  5944. Benchmark(std::string &&name, FUN &&func)
  5945. : fun(std::move(func)), name(std::move(name)) {}
  5946. template <typename Clock>
  5947. ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
  5948. auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
  5949. auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
  5950. auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
  5951. int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
  5952. return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
  5953. }
  5954. template <typename Clock = default_clock>
  5955. void run() {
  5956. IConfigPtr cfg = getCurrentContext().getConfig();
  5957. auto env = Detail::measure_environment<Clock>();
  5958. getResultCapture().benchmarkPreparing(name);
  5959. CATCH_TRY{
  5960. auto plan = user_code([&] {
  5961. return prepare<Clock>(*cfg, env);
  5962. });
  5963. BenchmarkInfo info {
  5964. name,
  5965. plan.estimated_duration.count(),
  5966. plan.iterations_per_sample,
  5967. cfg->benchmarkSamples(),
  5968. cfg->benchmarkResamples(),
  5969. env.clock_resolution.mean.count(),
  5970. env.clock_cost.mean.count()
  5971. };
  5972. getResultCapture().benchmarkStarting(info);
  5973. auto samples = user_code([&] {
  5974. return plan.template run<Clock>(*cfg, env);
  5975. });
  5976. auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
  5977. BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
  5978. getResultCapture().benchmarkEnded(stats);
  5979. } CATCH_CATCH_ALL{
  5980. if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
  5981. std::rethrow_exception(std::current_exception());
  5982. }
  5983. }
  5984. // sets lambda to be used in fun *and* executes benchmark!
  5985. template <typename Fun,
  5986. typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
  5987. Benchmark & operator=(Fun func) {
  5988. fun = Detail::BenchmarkFunction(func);
  5989. run();
  5990. return *this;
  5991. }
  5992. explicit operator bool() {
  5993. return true;
  5994. }
  5995. private:
  5996. Detail::BenchmarkFunction fun;
  5997. std::string name;
  5998. };
  5999. }
  6000. } // namespace Catch
  6001. #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
  6002. #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
  6003. #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
  6004. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  6005. BenchmarkName = [&](int benchmarkIndex)
  6006. #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
  6007. if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
  6008. BenchmarkName = [&]
  6009. // end catch_benchmark.hpp
  6010. // start catch_constructor.hpp
  6011. // Constructor and destructor helpers
  6012. #include <type_traits>
  6013. namespace Catch {
  6014. namespace Benchmark {
  6015. namespace Detail {
  6016. template <typename T, bool Destruct>
  6017. struct ObjectStorage
  6018. {
  6019. ObjectStorage() : data() {}
  6020. ObjectStorage(const ObjectStorage& other)
  6021. {
  6022. new(&data) T(other.stored_object());
  6023. }
  6024. ObjectStorage(ObjectStorage&& other)
  6025. {
  6026. new(&data) T(std::move(other.stored_object()));
  6027. }
  6028. ~ObjectStorage() { destruct_on_exit<T>(); }
  6029. template <typename... Args>
  6030. void construct(Args&&... args)
  6031. {
  6032. new (&data) T(std::forward<Args>(args)...);
  6033. }
  6034. template <bool AllowManualDestruction = !Destruct>
  6035. typename std::enable_if<AllowManualDestruction>::type destruct()
  6036. {
  6037. stored_object().~T();
  6038. }
  6039. private:
  6040. // If this is a constructor benchmark, destruct the underlying object
  6041. template <typename U>
  6042. void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
  6043. // Otherwise, don't
  6044. template <typename U>
  6045. void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { }
  6046. T& stored_object() {
  6047. return *static_cast<T*>(static_cast<void*>(&data));
  6048. }
  6049. T const& stored_object() const {
  6050. return *static_cast<T*>(static_cast<void*>(&data));
  6051. }
  6052. struct { alignas(T) unsigned char data[sizeof(T)]; } data;
  6053. };
  6054. }
  6055. template <typename T>
  6056. using storage_for = Detail::ObjectStorage<T, true>;
  6057. template <typename T>
  6058. using destructable_object = Detail::ObjectStorage<T, false>;
  6059. }
  6060. }
  6061. // end catch_constructor.hpp
  6062. // end catch_benchmarking_all.hpp
  6063. #endif
  6064. #endif // ! CATCH_CONFIG_IMPL_ONLY
  6065. #ifdef CATCH_IMPL
  6066. // start catch_impl.hpp
  6067. #ifdef __clang__
  6068. #pragma clang diagnostic push
  6069. #pragma clang diagnostic ignored "-Wweak-vtables"
  6070. #endif
  6071. // Keep these here for external reporters
  6072. // start catch_test_case_tracker.h
  6073. #include <string>
  6074. #include <vector>
  6075. #include <memory>
  6076. namespace Catch {
  6077. namespace TestCaseTracking {
  6078. struct NameAndLocation {
  6079. std::string name;
  6080. SourceLineInfo location;
  6081. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  6082. friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
  6083. return lhs.name == rhs.name
  6084. && lhs.location == rhs.location;
  6085. }
  6086. };
  6087. class ITracker;
  6088. using ITrackerPtr = std::shared_ptr<ITracker>;
  6089. class ITracker {
  6090. NameAndLocation m_nameAndLocation;
  6091. public:
  6092. ITracker(NameAndLocation const& nameAndLoc) :
  6093. m_nameAndLocation(nameAndLoc)
  6094. {}
  6095. // static queries
  6096. NameAndLocation const& nameAndLocation() const {
  6097. return m_nameAndLocation;
  6098. }
  6099. virtual ~ITracker();
  6100. // dynamic queries
  6101. virtual bool isComplete() const = 0; // Successfully completed or failed
  6102. virtual bool isSuccessfullyCompleted() const = 0;
  6103. virtual bool isOpen() const = 0; // Started but not complete
  6104. virtual bool hasChildren() const = 0;
  6105. virtual bool hasStarted() const = 0;
  6106. virtual ITracker& parent() = 0;
  6107. // actions
  6108. virtual void close() = 0; // Successfully complete
  6109. virtual void fail() = 0;
  6110. virtual void markAsNeedingAnotherRun() = 0;
  6111. virtual void addChild( ITrackerPtr const& child ) = 0;
  6112. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  6113. virtual void openChild() = 0;
  6114. // Debug/ checking
  6115. virtual bool isSectionTracker() const = 0;
  6116. virtual bool isGeneratorTracker() const = 0;
  6117. };
  6118. class TrackerContext {
  6119. enum RunState {
  6120. NotStarted,
  6121. Executing,
  6122. CompletedCycle
  6123. };
  6124. ITrackerPtr m_rootTracker;
  6125. ITracker* m_currentTracker = nullptr;
  6126. RunState m_runState = NotStarted;
  6127. public:
  6128. ITracker& startRun();
  6129. void endRun();
  6130. void startCycle();
  6131. void completeCycle();
  6132. bool completedCycle() const;
  6133. ITracker& currentTracker();
  6134. void setCurrentTracker( ITracker* tracker );
  6135. };
  6136. class TrackerBase : public ITracker {
  6137. protected:
  6138. enum CycleState {
  6139. NotStarted,
  6140. Executing,
  6141. ExecutingChildren,
  6142. NeedsAnotherRun,
  6143. CompletedSuccessfully,
  6144. Failed
  6145. };
  6146. using Children = std::vector<ITrackerPtr>;
  6147. TrackerContext& m_ctx;
  6148. ITracker* m_parent;
  6149. Children m_children;
  6150. CycleState m_runState = NotStarted;
  6151. public:
  6152. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  6153. bool isComplete() const override;
  6154. bool isSuccessfullyCompleted() const override;
  6155. bool isOpen() const override;
  6156. bool hasChildren() const override;
  6157. bool hasStarted() const override {
  6158. return m_runState != NotStarted;
  6159. }
  6160. void addChild( ITrackerPtr const& child ) override;
  6161. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  6162. ITracker& parent() override;
  6163. void openChild() override;
  6164. bool isSectionTracker() const override;
  6165. bool isGeneratorTracker() const override;
  6166. void open();
  6167. void close() override;
  6168. void fail() override;
  6169. void markAsNeedingAnotherRun() override;
  6170. private:
  6171. void moveToParent();
  6172. void moveToThis();
  6173. };
  6174. class SectionTracker : public TrackerBase {
  6175. std::vector<std::string> m_filters;
  6176. std::string m_trimmed_name;
  6177. public:
  6178. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  6179. bool isSectionTracker() const override;
  6180. bool isComplete() const override;
  6181. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  6182. void tryOpen();
  6183. void addInitialFilters( std::vector<std::string> const& filters );
  6184. void addNextFilters( std::vector<std::string> const& filters );
  6185. //! Returns filters active in this tracker
  6186. std::vector<std::string> const& getFilters() const;
  6187. //! Returns whitespace-trimmed name of the tracked section
  6188. std::string const& trimmedName() const;
  6189. };
  6190. } // namespace TestCaseTracking
  6191. using TestCaseTracking::ITracker;
  6192. using TestCaseTracking::TrackerContext;
  6193. using TestCaseTracking::SectionTracker;
  6194. } // namespace Catch
  6195. // end catch_test_case_tracker.h
  6196. // start catch_leak_detector.h
  6197. namespace Catch {
  6198. struct LeakDetector {
  6199. LeakDetector();
  6200. ~LeakDetector();
  6201. };
  6202. }
  6203. // end catch_leak_detector.h
  6204. // Cpp files will be included in the single-header file here
  6205. // start catch_stats.cpp
  6206. // Statistical analysis tools
  6207. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6208. #include <cassert>
  6209. #include <random>
  6210. #if defined(CATCH_CONFIG_USE_ASYNC)
  6211. #include <future>
  6212. #endif
  6213. namespace {
  6214. double erf_inv(double x) {
  6215. // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
  6216. double w, p;
  6217. w = -log((1.0 - x) * (1.0 + x));
  6218. if (w < 6.250000) {
  6219. w = w - 3.125000;
  6220. p = -3.6444120640178196996e-21;
  6221. p = -1.685059138182016589e-19 + p * w;
  6222. p = 1.2858480715256400167e-18 + p * w;
  6223. p = 1.115787767802518096e-17 + p * w;
  6224. p = -1.333171662854620906e-16 + p * w;
  6225. p = 2.0972767875968561637e-17 + p * w;
  6226. p = 6.6376381343583238325e-15 + p * w;
  6227. p = -4.0545662729752068639e-14 + p * w;
  6228. p = -8.1519341976054721522e-14 + p * w;
  6229. p = 2.6335093153082322977e-12 + p * w;
  6230. p = -1.2975133253453532498e-11 + p * w;
  6231. p = -5.4154120542946279317e-11 + p * w;
  6232. p = 1.051212273321532285e-09 + p * w;
  6233. p = -4.1126339803469836976e-09 + p * w;
  6234. p = -2.9070369957882005086e-08 + p * w;
  6235. p = 4.2347877827932403518e-07 + p * w;
  6236. p = -1.3654692000834678645e-06 + p * w;
  6237. p = -1.3882523362786468719e-05 + p * w;
  6238. p = 0.0001867342080340571352 + p * w;
  6239. p = -0.00074070253416626697512 + p * w;
  6240. p = -0.0060336708714301490533 + p * w;
  6241. p = 0.24015818242558961693 + p * w;
  6242. p = 1.6536545626831027356 + p * w;
  6243. } else if (w < 16.000000) {
  6244. w = sqrt(w) - 3.250000;
  6245. p = 2.2137376921775787049e-09;
  6246. p = 9.0756561938885390979e-08 + p * w;
  6247. p = -2.7517406297064545428e-07 + p * w;
  6248. p = 1.8239629214389227755e-08 + p * w;
  6249. p = 1.5027403968909827627e-06 + p * w;
  6250. p = -4.013867526981545969e-06 + p * w;
  6251. p = 2.9234449089955446044e-06 + p * w;
  6252. p = 1.2475304481671778723e-05 + p * w;
  6253. p = -4.7318229009055733981e-05 + p * w;
  6254. p = 6.8284851459573175448e-05 + p * w;
  6255. p = 2.4031110387097893999e-05 + p * w;
  6256. p = -0.0003550375203628474796 + p * w;
  6257. p = 0.00095328937973738049703 + p * w;
  6258. p = -0.0016882755560235047313 + p * w;
  6259. p = 0.0024914420961078508066 + p * w;
  6260. p = -0.0037512085075692412107 + p * w;
  6261. p = 0.005370914553590063617 + p * w;
  6262. p = 1.0052589676941592334 + p * w;
  6263. p = 3.0838856104922207635 + p * w;
  6264. } else {
  6265. w = sqrt(w) - 5.000000;
  6266. p = -2.7109920616438573243e-11;
  6267. p = -2.5556418169965252055e-10 + p * w;
  6268. p = 1.5076572693500548083e-09 + p * w;
  6269. p = -3.7894654401267369937e-09 + p * w;
  6270. p = 7.6157012080783393804e-09 + p * w;
  6271. p = -1.4960026627149240478e-08 + p * w;
  6272. p = 2.9147953450901080826e-08 + p * w;
  6273. p = -6.7711997758452339498e-08 + p * w;
  6274. p = 2.2900482228026654717e-07 + p * w;
  6275. p = -9.9298272942317002539e-07 + p * w;
  6276. p = 4.5260625972231537039e-06 + p * w;
  6277. p = -1.9681778105531670567e-05 + p * w;
  6278. p = 7.5995277030017761139e-05 + p * w;
  6279. p = -0.00021503011930044477347 + p * w;
  6280. p = -0.00013871931833623122026 + p * w;
  6281. p = 1.0103004648645343977 + p * w;
  6282. p = 4.8499064014085844221 + p * w;
  6283. }
  6284. return p * x;
  6285. }
  6286. double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6287. auto m = Catch::Benchmark::Detail::mean(first, last);
  6288. double variance = std::accumulate(first, last, 0., [m](double a, double b) {
  6289. double diff = b - m;
  6290. return a + diff * diff;
  6291. }) / (last - first);
  6292. return std::sqrt(variance);
  6293. }
  6294. }
  6295. namespace Catch {
  6296. namespace Benchmark {
  6297. namespace Detail {
  6298. double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6299. auto count = last - first;
  6300. double idx = (count - 1) * k / static_cast<double>(q);
  6301. int j = static_cast<int>(idx);
  6302. double g = idx - j;
  6303. std::nth_element(first, first + j, last);
  6304. auto xj = first[j];
  6305. if (g == 0) return xj;
  6306. auto xj1 = *std::min_element(first + (j + 1), last);
  6307. return xj + g * (xj1 - xj);
  6308. }
  6309. double erfc_inv(double x) {
  6310. return erf_inv(1.0 - x);
  6311. }
  6312. double normal_quantile(double p) {
  6313. static const double ROOT_TWO = std::sqrt(2.0);
  6314. double result = 0.0;
  6315. assert(p >= 0 && p <= 1);
  6316. if (p < 0 || p > 1) {
  6317. return result;
  6318. }
  6319. result = -erfc_inv(2.0 * p);
  6320. // result *= normal distribution standard deviation (1.0) * sqrt(2)
  6321. result *= /*sd * */ ROOT_TWO;
  6322. // result += normal disttribution mean (0)
  6323. return result;
  6324. }
  6325. double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
  6326. double sb = stddev.point;
  6327. double mn = mean.point / n;
  6328. double mg_min = mn / 2.;
  6329. double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
  6330. double sg2 = sg * sg;
  6331. double sb2 = sb * sb;
  6332. auto c_max = [n, mn, sb2, sg2](double x) -> double {
  6333. double k = mn - x;
  6334. double d = k * k;
  6335. double nd = n * d;
  6336. double k0 = -n * nd;
  6337. double k1 = sb2 - n * sg2 + nd;
  6338. double det = k1 * k1 - 4 * sg2 * k0;
  6339. return (int)(-2. * k0 / (k1 + std::sqrt(det)));
  6340. };
  6341. auto var_out = [n, sb2, sg2](double c) {
  6342. double nc = n - c;
  6343. return (nc / n) * (sb2 - nc * sg2);
  6344. };
  6345. return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
  6346. }
  6347. bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
  6348. CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
  6349. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  6350. static std::random_device entropy;
  6351. CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
  6352. auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
  6353. auto mean = &Detail::mean<std::vector<double>::iterator>;
  6354. auto stddev = &standard_deviation;
  6355. #if defined(CATCH_CONFIG_USE_ASYNC)
  6356. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6357. auto seed = entropy();
  6358. return std::async(std::launch::async, [=] {
  6359. std::mt19937 rng(seed);
  6360. auto resampled = resample(rng, n_resamples, first, last, f);
  6361. return bootstrap(confidence_level, first, last, resampled, f);
  6362. });
  6363. };
  6364. auto mean_future = Estimate(mean);
  6365. auto stddev_future = Estimate(stddev);
  6366. auto mean_estimate = mean_future.get();
  6367. auto stddev_estimate = stddev_future.get();
  6368. #else
  6369. auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
  6370. auto seed = entropy();
  6371. std::mt19937 rng(seed);
  6372. auto resampled = resample(rng, n_resamples, first, last, f);
  6373. return bootstrap(confidence_level, first, last, resampled, f);
  6374. };
  6375. auto mean_estimate = Estimate(mean);
  6376. auto stddev_estimate = Estimate(stddev);
  6377. #endif // CATCH_USE_ASYNC
  6378. double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
  6379. return { mean_estimate, stddev_estimate, outlier_variance };
  6380. }
  6381. } // namespace Detail
  6382. } // namespace Benchmark
  6383. } // namespace Catch
  6384. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6385. // end catch_stats.cpp
  6386. // start catch_approx.cpp
  6387. #include <cmath>
  6388. #include <limits>
  6389. namespace {
  6390. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6391. // But without the subtraction to allow for INFINITY in comparison
  6392. bool marginComparison(double lhs, double rhs, double margin) {
  6393. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  6394. }
  6395. }
  6396. namespace Catch {
  6397. namespace Detail {
  6398. Approx::Approx ( double value )
  6399. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  6400. m_margin( 0.0 ),
  6401. m_scale( 0.0 ),
  6402. m_value( value )
  6403. {}
  6404. Approx Approx::custom() {
  6405. return Approx( 0 );
  6406. }
  6407. Approx Approx::operator-() const {
  6408. auto temp(*this);
  6409. temp.m_value = -temp.m_value;
  6410. return temp;
  6411. }
  6412. std::string Approx::toString() const {
  6413. ReusableStringStream rss;
  6414. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  6415. return rss.str();
  6416. }
  6417. bool Approx::equalityComparisonImpl(const double other) const {
  6418. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  6419. // Thanks to Richard Harris for his help refining the scaled margin value
  6420. return marginComparison(m_value, other, m_margin)
  6421. || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
  6422. }
  6423. void Approx::setMargin(double newMargin) {
  6424. CATCH_ENFORCE(newMargin >= 0,
  6425. "Invalid Approx::margin: " << newMargin << '.'
  6426. << " Approx::Margin has to be non-negative.");
  6427. m_margin = newMargin;
  6428. }
  6429. void Approx::setEpsilon(double newEpsilon) {
  6430. CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
  6431. "Invalid Approx::epsilon: " << newEpsilon << '.'
  6432. << " Approx::epsilon has to be in [0, 1]");
  6433. m_epsilon = newEpsilon;
  6434. }
  6435. } // end namespace Detail
  6436. namespace literals {
  6437. Detail::Approx operator "" _a(long double val) {
  6438. return Detail::Approx(val);
  6439. }
  6440. Detail::Approx operator "" _a(unsigned long long val) {
  6441. return Detail::Approx(val);
  6442. }
  6443. } // end namespace literals
  6444. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  6445. return value.toString();
  6446. }
  6447. } // end namespace Catch
  6448. // end catch_approx.cpp
  6449. // start catch_assertionhandler.cpp
  6450. // start catch_debugger.h
  6451. namespace Catch {
  6452. bool isDebuggerActive();
  6453. }
  6454. #ifdef CATCH_PLATFORM_MAC
  6455. #if defined(__i386__) || defined(__x86_64__)
  6456. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  6457. #elif defined(__aarch64__)
  6458. #define CATCH_TRAP() __asm__(".inst 0xd43e0000")
  6459. #endif
  6460. #elif defined(CATCH_PLATFORM_IPHONE)
  6461. // use inline assembler
  6462. #if defined(__i386__) || defined(__x86_64__)
  6463. #define CATCH_TRAP() __asm__("int $3")
  6464. #elif defined(__aarch64__)
  6465. #define CATCH_TRAP() __asm__(".inst 0xd4200000")
  6466. #elif defined(__arm__) && !defined(__thumb__)
  6467. #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
  6468. #elif defined(__arm__) && defined(__thumb__)
  6469. #define CATCH_TRAP() __asm__(".inst 0xde01")
  6470. #endif
  6471. #elif defined(CATCH_PLATFORM_LINUX)
  6472. // If we can use inline assembler, do it because this allows us to break
  6473. // directly at the location of the failing check instead of breaking inside
  6474. // raise() called from it, i.e. one stack frame below.
  6475. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  6476. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  6477. #else // Fall back to the generic way.
  6478. #include <signal.h>
  6479. #define CATCH_TRAP() raise(SIGTRAP)
  6480. #endif
  6481. #elif defined(_MSC_VER)
  6482. #define CATCH_TRAP() __debugbreak()
  6483. #elif defined(__MINGW32__)
  6484. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  6485. #define CATCH_TRAP() DebugBreak()
  6486. #endif
  6487. #ifndef CATCH_BREAK_INTO_DEBUGGER
  6488. #ifdef CATCH_TRAP
  6489. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  6490. #else
  6491. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  6492. #endif
  6493. #endif
  6494. // end catch_debugger.h
  6495. // start catch_run_context.h
  6496. // start catch_fatal_condition.h
  6497. #include <cassert>
  6498. namespace Catch {
  6499. // Wrapper for platform-specific fatal error (signals/SEH) handlers
  6500. //
  6501. // Tries to be cooperative with other handlers, and not step over
  6502. // other handlers. This means that unknown structured exceptions
  6503. // are passed on, previous signal handlers are called, and so on.
  6504. //
  6505. // Can only be instantiated once, and assumes that once a signal
  6506. // is caught, the binary will end up terminating. Thus, there
  6507. class FatalConditionHandler {
  6508. bool m_started = false;
  6509. // Install/disengage implementation for specific platform.
  6510. // Should be if-defed to work on current platform, can assume
  6511. // engage-disengage 1:1 pairing.
  6512. void engage_platform();
  6513. void disengage_platform();
  6514. public:
  6515. // Should also have platform-specific implementations as needed
  6516. FatalConditionHandler();
  6517. ~FatalConditionHandler();
  6518. void engage() {
  6519. assert(!m_started && "Handler cannot be installed twice.");
  6520. m_started = true;
  6521. engage_platform();
  6522. }
  6523. void disengage() {
  6524. assert(m_started && "Handler cannot be uninstalled without being installed first");
  6525. m_started = false;
  6526. disengage_platform();
  6527. }
  6528. };
  6529. //! Simple RAII guard for (dis)engaging the FatalConditionHandler
  6530. class FatalConditionHandlerGuard {
  6531. FatalConditionHandler* m_handler;
  6532. public:
  6533. FatalConditionHandlerGuard(FatalConditionHandler* handler):
  6534. m_handler(handler) {
  6535. m_handler->engage();
  6536. }
  6537. ~FatalConditionHandlerGuard() {
  6538. m_handler->disengage();
  6539. }
  6540. };
  6541. } // end namespace Catch
  6542. // end catch_fatal_condition.h
  6543. #include <string>
  6544. namespace Catch {
  6545. struct IMutableContext;
  6546. ///////////////////////////////////////////////////////////////////////////
  6547. class RunContext : public IResultCapture, public IRunner {
  6548. public:
  6549. RunContext( RunContext const& ) = delete;
  6550. RunContext& operator =( RunContext const& ) = delete;
  6551. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  6552. ~RunContext() override;
  6553. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  6554. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  6555. Totals runTest(TestCase const& testCase);
  6556. IConfigPtr config() const;
  6557. IStreamingReporter& reporter() const;
  6558. public: // IResultCapture
  6559. // Assertion handlers
  6560. void handleExpr
  6561. ( AssertionInfo const& info,
  6562. ITransientExpression const& expr,
  6563. AssertionReaction& reaction ) override;
  6564. void handleMessage
  6565. ( AssertionInfo const& info,
  6566. ResultWas::OfType resultType,
  6567. StringRef const& message,
  6568. AssertionReaction& reaction ) override;
  6569. void handleUnexpectedExceptionNotThrown
  6570. ( AssertionInfo const& info,
  6571. AssertionReaction& reaction ) override;
  6572. void handleUnexpectedInflightException
  6573. ( AssertionInfo const& info,
  6574. std::string const& message,
  6575. AssertionReaction& reaction ) override;
  6576. void handleIncomplete
  6577. ( AssertionInfo const& info ) override;
  6578. void handleNonExpr
  6579. ( AssertionInfo const &info,
  6580. ResultWas::OfType resultType,
  6581. AssertionReaction &reaction ) override;
  6582. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  6583. void sectionEnded( SectionEndInfo const& endInfo ) override;
  6584. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  6585. auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  6586. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  6587. void benchmarkPreparing( std::string const& name ) override;
  6588. void benchmarkStarting( BenchmarkInfo const& info ) override;
  6589. void benchmarkEnded( BenchmarkStats<> const& stats ) override;
  6590. void benchmarkFailed( std::string const& error ) override;
  6591. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  6592. void pushScopedMessage( MessageInfo const& message ) override;
  6593. void popScopedMessage( MessageInfo const& message ) override;
  6594. void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
  6595. std::string getCurrentTestName() const override;
  6596. const AssertionResult* getLastResult() const override;
  6597. void exceptionEarlyReported() override;
  6598. void handleFatalErrorCondition( StringRef message ) override;
  6599. bool lastAssertionPassed() override;
  6600. void assertionPassed() override;
  6601. public:
  6602. // !TBD We need to do this another way!
  6603. bool aborting() const final;
  6604. private:
  6605. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  6606. void invokeActiveTestCase();
  6607. void resetAssertionInfo();
  6608. bool testForMissingAssertions( Counts& assertions );
  6609. void assertionEnded( AssertionResult const& result );
  6610. void reportExpr
  6611. ( AssertionInfo const &info,
  6612. ResultWas::OfType resultType,
  6613. ITransientExpression const *expr,
  6614. bool negated );
  6615. void populateReaction( AssertionReaction& reaction );
  6616. private:
  6617. void handleUnfinishedSections();
  6618. TestRunInfo m_runInfo;
  6619. IMutableContext& m_context;
  6620. TestCase const* m_activeTestCase = nullptr;
  6621. ITracker* m_testCaseTracker = nullptr;
  6622. Option<AssertionResult> m_lastResult;
  6623. IConfigPtr m_config;
  6624. Totals m_totals;
  6625. IStreamingReporterPtr m_reporter;
  6626. std::vector<MessageInfo> m_messages;
  6627. std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
  6628. AssertionInfo m_lastAssertionInfo;
  6629. std::vector<SectionEndInfo> m_unfinishedSections;
  6630. std::vector<ITracker*> m_activeSections;
  6631. TrackerContext m_trackerContext;
  6632. FatalConditionHandler m_fatalConditionhandler;
  6633. bool m_lastAssertionPassed = false;
  6634. bool m_shouldReportUnexpected = true;
  6635. bool m_includeSuccessfulResults;
  6636. };
  6637. void seedRng(IConfig const& config);
  6638. unsigned int rngSeed();
  6639. } // end namespace Catch
  6640. // end catch_run_context.h
  6641. namespace Catch {
  6642. namespace {
  6643. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  6644. expr.streamReconstructedExpression( os );
  6645. return os;
  6646. }
  6647. }
  6648. LazyExpression::LazyExpression( bool isNegated )
  6649. : m_isNegated( isNegated )
  6650. {}
  6651. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  6652. LazyExpression::operator bool() const {
  6653. return m_transientExpression != nullptr;
  6654. }
  6655. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  6656. if( lazyExpr.m_isNegated )
  6657. os << "!";
  6658. if( lazyExpr ) {
  6659. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  6660. os << "(" << *lazyExpr.m_transientExpression << ")";
  6661. else
  6662. os << *lazyExpr.m_transientExpression;
  6663. }
  6664. else {
  6665. os << "{** error - unchecked empty expression requested **}";
  6666. }
  6667. return os;
  6668. }
  6669. AssertionHandler::AssertionHandler
  6670. ( StringRef const& macroName,
  6671. SourceLineInfo const& lineInfo,
  6672. StringRef capturedExpression,
  6673. ResultDisposition::Flags resultDisposition )
  6674. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  6675. m_resultCapture( getResultCapture() )
  6676. {}
  6677. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  6678. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  6679. }
  6680. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  6681. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  6682. }
  6683. auto AssertionHandler::allowThrows() const -> bool {
  6684. return getCurrentContext().getConfig()->allowThrows();
  6685. }
  6686. void AssertionHandler::complete() {
  6687. setCompleted();
  6688. if( m_reaction.shouldDebugBreak ) {
  6689. // If you find your debugger stopping you here then go one level up on the
  6690. // call-stack for the code that caused it (typically a failed assertion)
  6691. // (To go back to the test and change execution, jump over the throw, next)
  6692. CATCH_BREAK_INTO_DEBUGGER();
  6693. }
  6694. if (m_reaction.shouldThrow) {
  6695. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6696. throw Catch::TestFailureException();
  6697. #else
  6698. CATCH_ERROR( "Test failure requires aborting test!" );
  6699. #endif
  6700. }
  6701. }
  6702. void AssertionHandler::setCompleted() {
  6703. m_completed = true;
  6704. }
  6705. void AssertionHandler::handleUnexpectedInflightException() {
  6706. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  6707. }
  6708. void AssertionHandler::handleExceptionThrownAsExpected() {
  6709. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6710. }
  6711. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  6712. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6713. }
  6714. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  6715. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  6716. }
  6717. void AssertionHandler::handleThrowingCallSkipped() {
  6718. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  6719. }
  6720. // This is the overload that takes a string and infers the Equals matcher from it
  6721. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  6722. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  6723. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  6724. }
  6725. } // namespace Catch
  6726. // end catch_assertionhandler.cpp
  6727. // start catch_assertionresult.cpp
  6728. namespace Catch {
  6729. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  6730. lazyExpression(_lazyExpression),
  6731. resultType(_resultType) {}
  6732. std::string AssertionResultData::reconstructExpression() const {
  6733. if( reconstructedExpression.empty() ) {
  6734. if( lazyExpression ) {
  6735. ReusableStringStream rss;
  6736. rss << lazyExpression;
  6737. reconstructedExpression = rss.str();
  6738. }
  6739. }
  6740. return reconstructedExpression;
  6741. }
  6742. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  6743. : m_info( info ),
  6744. m_resultData( data )
  6745. {}
  6746. // Result was a success
  6747. bool AssertionResult::succeeded() const {
  6748. return Catch::isOk( m_resultData.resultType );
  6749. }
  6750. // Result was a success, or failure is suppressed
  6751. bool AssertionResult::isOk() const {
  6752. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  6753. }
  6754. ResultWas::OfType AssertionResult::getResultType() const {
  6755. return m_resultData.resultType;
  6756. }
  6757. bool AssertionResult::hasExpression() const {
  6758. return !m_info.capturedExpression.empty();
  6759. }
  6760. bool AssertionResult::hasMessage() const {
  6761. return !m_resultData.message.empty();
  6762. }
  6763. std::string AssertionResult::getExpression() const {
  6764. // Possibly overallocating by 3 characters should be basically free
  6765. std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
  6766. if (isFalseTest(m_info.resultDisposition)) {
  6767. expr += "!(";
  6768. }
  6769. expr += m_info.capturedExpression;
  6770. if (isFalseTest(m_info.resultDisposition)) {
  6771. expr += ')';
  6772. }
  6773. return expr;
  6774. }
  6775. std::string AssertionResult::getExpressionInMacro() const {
  6776. std::string expr;
  6777. if( m_info.macroName.empty() )
  6778. expr = static_cast<std::string>(m_info.capturedExpression);
  6779. else {
  6780. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  6781. expr += m_info.macroName;
  6782. expr += "( ";
  6783. expr += m_info.capturedExpression;
  6784. expr += " )";
  6785. }
  6786. return expr;
  6787. }
  6788. bool AssertionResult::hasExpandedExpression() const {
  6789. return hasExpression() && getExpandedExpression() != getExpression();
  6790. }
  6791. std::string AssertionResult::getExpandedExpression() const {
  6792. std::string expr = m_resultData.reconstructExpression();
  6793. return expr.empty()
  6794. ? getExpression()
  6795. : expr;
  6796. }
  6797. std::string AssertionResult::getMessage() const {
  6798. return m_resultData.message;
  6799. }
  6800. SourceLineInfo AssertionResult::getSourceInfo() const {
  6801. return m_info.lineInfo;
  6802. }
  6803. StringRef AssertionResult::getTestMacroName() const {
  6804. return m_info.macroName;
  6805. }
  6806. } // end namespace Catch
  6807. // end catch_assertionresult.cpp
  6808. // start catch_capture_matchers.cpp
  6809. namespace Catch {
  6810. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  6811. // This is the general overload that takes a any string matcher
  6812. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  6813. // the Equals matcher (so the header does not mention matchers)
  6814. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  6815. std::string exceptionMessage = Catch::translateActiveException();
  6816. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  6817. handler.handleExpr( expr );
  6818. }
  6819. } // namespace Catch
  6820. // end catch_capture_matchers.cpp
  6821. // start catch_commandline.cpp
  6822. // start catch_commandline.h
  6823. // start catch_clara.h
  6824. // Use Catch's value for console width (store Clara's off to the side, if present)
  6825. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  6826. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6827. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6828. #endif
  6829. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  6830. #ifdef __clang__
  6831. #pragma clang diagnostic push
  6832. #pragma clang diagnostic ignored "-Wweak-vtables"
  6833. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  6834. #pragma clang diagnostic ignored "-Wshadow"
  6835. #endif
  6836. // start clara.hpp
  6837. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  6838. //
  6839. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6840. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6841. //
  6842. // See https://github.com/philsquared/Clara for more details
  6843. // Clara v1.1.5
  6844. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6845. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  6846. #endif
  6847. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6848. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  6849. #endif
  6850. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  6851. #ifdef __has_include
  6852. #if __has_include(<optional>) && __cplusplus >= 201703L
  6853. #include <optional>
  6854. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  6855. #endif
  6856. #endif
  6857. #endif
  6858. // ----------- #included from clara_textflow.hpp -----------
  6859. // TextFlowCpp
  6860. //
  6861. // A single-header library for wrapping and laying out basic text, by Phil Nash
  6862. //
  6863. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6864. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6865. //
  6866. // This project is hosted at https://github.com/philsquared/textflowcpp
  6867. #include <cassert>
  6868. #include <ostream>
  6869. #include <sstream>
  6870. #include <vector>
  6871. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  6872. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  6873. #endif
  6874. namespace Catch {
  6875. namespace clara {
  6876. namespace TextFlow {
  6877. inline auto isWhitespace(char c) -> bool {
  6878. static std::string chars = " \t\n\r";
  6879. return chars.find(c) != std::string::npos;
  6880. }
  6881. inline auto isBreakableBefore(char c) -> bool {
  6882. static std::string chars = "[({<|";
  6883. return chars.find(c) != std::string::npos;
  6884. }
  6885. inline auto isBreakableAfter(char c) -> bool {
  6886. static std::string chars = "])}>.,:;*+-=&/\\";
  6887. return chars.find(c) != std::string::npos;
  6888. }
  6889. class Columns;
  6890. class Column {
  6891. std::vector<std::string> m_strings;
  6892. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  6893. size_t m_indent = 0;
  6894. size_t m_initialIndent = std::string::npos;
  6895. public:
  6896. class iterator {
  6897. friend Column;
  6898. Column const& m_column;
  6899. size_t m_stringIndex = 0;
  6900. size_t m_pos = 0;
  6901. size_t m_len = 0;
  6902. size_t m_end = 0;
  6903. bool m_suffix = false;
  6904. iterator(Column const& column, size_t stringIndex)
  6905. : m_column(column),
  6906. m_stringIndex(stringIndex) {}
  6907. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  6908. auto isBoundary(size_t at) const -> bool {
  6909. assert(at > 0);
  6910. assert(at <= line().size());
  6911. return at == line().size() ||
  6912. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  6913. isBreakableBefore(line()[at]) ||
  6914. isBreakableAfter(line()[at - 1]);
  6915. }
  6916. void calcLength() {
  6917. assert(m_stringIndex < m_column.m_strings.size());
  6918. m_suffix = false;
  6919. auto width = m_column.m_width - indent();
  6920. m_end = m_pos;
  6921. if (line()[m_pos] == '\n') {
  6922. ++m_end;
  6923. }
  6924. while (m_end < line().size() && line()[m_end] != '\n')
  6925. ++m_end;
  6926. if (m_end < m_pos + width) {
  6927. m_len = m_end - m_pos;
  6928. } else {
  6929. size_t len = width;
  6930. while (len > 0 && !isBoundary(m_pos + len))
  6931. --len;
  6932. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  6933. --len;
  6934. if (len > 0) {
  6935. m_len = len;
  6936. } else {
  6937. m_suffix = true;
  6938. m_len = width - 1;
  6939. }
  6940. }
  6941. }
  6942. auto indent() const -> size_t {
  6943. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  6944. return initial == std::string::npos ? m_column.m_indent : initial;
  6945. }
  6946. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  6947. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  6948. }
  6949. public:
  6950. using difference_type = std::ptrdiff_t;
  6951. using value_type = std::string;
  6952. using pointer = value_type * ;
  6953. using reference = value_type & ;
  6954. using iterator_category = std::forward_iterator_tag;
  6955. explicit iterator(Column const& column) : m_column(column) {
  6956. assert(m_column.m_width > m_column.m_indent);
  6957. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  6958. calcLength();
  6959. if (m_len == 0)
  6960. m_stringIndex++; // Empty string
  6961. }
  6962. auto operator *() const -> std::string {
  6963. assert(m_stringIndex < m_column.m_strings.size());
  6964. assert(m_pos <= m_end);
  6965. return addIndentAndSuffix(line().substr(m_pos, m_len));
  6966. }
  6967. auto operator ++() -> iterator& {
  6968. m_pos += m_len;
  6969. if (m_pos < line().size() && line()[m_pos] == '\n')
  6970. m_pos += 1;
  6971. else
  6972. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  6973. ++m_pos;
  6974. if (m_pos == line().size()) {
  6975. m_pos = 0;
  6976. ++m_stringIndex;
  6977. }
  6978. if (m_stringIndex < m_column.m_strings.size())
  6979. calcLength();
  6980. return *this;
  6981. }
  6982. auto operator ++(int) -> iterator {
  6983. iterator prev(*this);
  6984. operator++();
  6985. return prev;
  6986. }
  6987. auto operator ==(iterator const& other) const -> bool {
  6988. return
  6989. m_pos == other.m_pos &&
  6990. m_stringIndex == other.m_stringIndex &&
  6991. &m_column == &other.m_column;
  6992. }
  6993. auto operator !=(iterator const& other) const -> bool {
  6994. return !operator==(other);
  6995. }
  6996. };
  6997. using const_iterator = iterator;
  6998. explicit Column(std::string const& text) { m_strings.push_back(text); }
  6999. auto width(size_t newWidth) -> Column& {
  7000. assert(newWidth > 0);
  7001. m_width = newWidth;
  7002. return *this;
  7003. }
  7004. auto indent(size_t newIndent) -> Column& {
  7005. m_indent = newIndent;
  7006. return *this;
  7007. }
  7008. auto initialIndent(size_t newIndent) -> Column& {
  7009. m_initialIndent = newIndent;
  7010. return *this;
  7011. }
  7012. auto width() const -> size_t { return m_width; }
  7013. auto begin() const -> iterator { return iterator(*this); }
  7014. auto end() const -> iterator { return { *this, m_strings.size() }; }
  7015. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  7016. bool first = true;
  7017. for (auto line : col) {
  7018. if (first)
  7019. first = false;
  7020. else
  7021. os << "\n";
  7022. os << line;
  7023. }
  7024. return os;
  7025. }
  7026. auto operator + (Column const& other)->Columns;
  7027. auto toString() const -> std::string {
  7028. std::ostringstream oss;
  7029. oss << *this;
  7030. return oss.str();
  7031. }
  7032. };
  7033. class Spacer : public Column {
  7034. public:
  7035. explicit Spacer(size_t spaceWidth) : Column("") {
  7036. width(spaceWidth);
  7037. }
  7038. };
  7039. class Columns {
  7040. std::vector<Column> m_columns;
  7041. public:
  7042. class iterator {
  7043. friend Columns;
  7044. struct EndTag {};
  7045. std::vector<Column> const& m_columns;
  7046. std::vector<Column::iterator> m_iterators;
  7047. size_t m_activeIterators;
  7048. iterator(Columns const& columns, EndTag)
  7049. : m_columns(columns.m_columns),
  7050. m_activeIterators(0) {
  7051. m_iterators.reserve(m_columns.size());
  7052. for (auto const& col : m_columns)
  7053. m_iterators.push_back(col.end());
  7054. }
  7055. public:
  7056. using difference_type = std::ptrdiff_t;
  7057. using value_type = std::string;
  7058. using pointer = value_type * ;
  7059. using reference = value_type & ;
  7060. using iterator_category = std::forward_iterator_tag;
  7061. explicit iterator(Columns const& columns)
  7062. : m_columns(columns.m_columns),
  7063. m_activeIterators(m_columns.size()) {
  7064. m_iterators.reserve(m_columns.size());
  7065. for (auto const& col : m_columns)
  7066. m_iterators.push_back(col.begin());
  7067. }
  7068. auto operator ==(iterator const& other) const -> bool {
  7069. return m_iterators == other.m_iterators;
  7070. }
  7071. auto operator !=(iterator const& other) const -> bool {
  7072. return m_iterators != other.m_iterators;
  7073. }
  7074. auto operator *() const -> std::string {
  7075. std::string row, padding;
  7076. for (size_t i = 0; i < m_columns.size(); ++i) {
  7077. auto width = m_columns[i].width();
  7078. if (m_iterators[i] != m_columns[i].end()) {
  7079. std::string col = *m_iterators[i];
  7080. row += padding + col;
  7081. if (col.size() < width)
  7082. padding = std::string(width - col.size(), ' ');
  7083. else
  7084. padding = "";
  7085. } else {
  7086. padding += std::string(width, ' ');
  7087. }
  7088. }
  7089. return row;
  7090. }
  7091. auto operator ++() -> iterator& {
  7092. for (size_t i = 0; i < m_columns.size(); ++i) {
  7093. if (m_iterators[i] != m_columns[i].end())
  7094. ++m_iterators[i];
  7095. }
  7096. return *this;
  7097. }
  7098. auto operator ++(int) -> iterator {
  7099. iterator prev(*this);
  7100. operator++();
  7101. return prev;
  7102. }
  7103. };
  7104. using const_iterator = iterator;
  7105. auto begin() const -> iterator { return iterator(*this); }
  7106. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  7107. auto operator += (Column const& col) -> Columns& {
  7108. m_columns.push_back(col);
  7109. return *this;
  7110. }
  7111. auto operator + (Column const& col) -> Columns {
  7112. Columns combined = *this;
  7113. combined += col;
  7114. return combined;
  7115. }
  7116. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  7117. bool first = true;
  7118. for (auto line : cols) {
  7119. if (first)
  7120. first = false;
  7121. else
  7122. os << "\n";
  7123. os << line;
  7124. }
  7125. return os;
  7126. }
  7127. auto toString() const -> std::string {
  7128. std::ostringstream oss;
  7129. oss << *this;
  7130. return oss.str();
  7131. }
  7132. };
  7133. inline auto Column::operator + (Column const& other) -> Columns {
  7134. Columns cols;
  7135. cols += *this;
  7136. cols += other;
  7137. return cols;
  7138. }
  7139. }
  7140. }
  7141. }
  7142. // ----------- end of #include from clara_textflow.hpp -----------
  7143. // ........... back in clara.hpp
  7144. #include <cctype>
  7145. #include <string>
  7146. #include <memory>
  7147. #include <set>
  7148. #include <algorithm>
  7149. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  7150. #define CATCH_PLATFORM_WINDOWS
  7151. #endif
  7152. namespace Catch { namespace clara {
  7153. namespace detail {
  7154. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  7155. template<typename L>
  7156. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  7157. template<typename ClassT, typename ReturnT, typename... Args>
  7158. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  7159. static const bool isValid = false;
  7160. };
  7161. template<typename ClassT, typename ReturnT, typename ArgT>
  7162. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  7163. static const bool isValid = true;
  7164. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  7165. using ReturnType = ReturnT;
  7166. };
  7167. class TokenStream;
  7168. // Transport for raw args (copied from main args, or supplied via init list for testing)
  7169. class Args {
  7170. friend TokenStream;
  7171. std::string m_exeName;
  7172. std::vector<std::string> m_args;
  7173. public:
  7174. Args( int argc, char const* const* argv )
  7175. : m_exeName(argv[0]),
  7176. m_args(argv + 1, argv + argc) {}
  7177. Args( std::initializer_list<std::string> args )
  7178. : m_exeName( *args.begin() ),
  7179. m_args( args.begin()+1, args.end() )
  7180. {}
  7181. auto exeName() const -> std::string {
  7182. return m_exeName;
  7183. }
  7184. };
  7185. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  7186. // may encode an option + its argument if the : or = form is used
  7187. enum class TokenType {
  7188. Option, Argument
  7189. };
  7190. struct Token {
  7191. TokenType type;
  7192. std::string token;
  7193. };
  7194. inline auto isOptPrefix( char c ) -> bool {
  7195. return c == '-'
  7196. #ifdef CATCH_PLATFORM_WINDOWS
  7197. || c == '/'
  7198. #endif
  7199. ;
  7200. }
  7201. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  7202. class TokenStream {
  7203. using Iterator = std::vector<std::string>::const_iterator;
  7204. Iterator it;
  7205. Iterator itEnd;
  7206. std::vector<Token> m_tokenBuffer;
  7207. void loadBuffer() {
  7208. m_tokenBuffer.resize( 0 );
  7209. // Skip any empty strings
  7210. while( it != itEnd && it->empty() )
  7211. ++it;
  7212. if( it != itEnd ) {
  7213. auto const &next = *it;
  7214. if( isOptPrefix( next[0] ) ) {
  7215. auto delimiterPos = next.find_first_of( " :=" );
  7216. if( delimiterPos != std::string::npos ) {
  7217. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  7218. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  7219. } else {
  7220. if( next[1] != '-' && next.size() > 2 ) {
  7221. std::string opt = "- ";
  7222. for( size_t i = 1; i < next.size(); ++i ) {
  7223. opt[1] = next[i];
  7224. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  7225. }
  7226. } else {
  7227. m_tokenBuffer.push_back( { TokenType::Option, next } );
  7228. }
  7229. }
  7230. } else {
  7231. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  7232. }
  7233. }
  7234. }
  7235. public:
  7236. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  7237. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  7238. loadBuffer();
  7239. }
  7240. explicit operator bool() const {
  7241. return !m_tokenBuffer.empty() || it != itEnd;
  7242. }
  7243. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  7244. auto operator*() const -> Token {
  7245. assert( !m_tokenBuffer.empty() );
  7246. return m_tokenBuffer.front();
  7247. }
  7248. auto operator->() const -> Token const * {
  7249. assert( !m_tokenBuffer.empty() );
  7250. return &m_tokenBuffer.front();
  7251. }
  7252. auto operator++() -> TokenStream & {
  7253. if( m_tokenBuffer.size() >= 2 ) {
  7254. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  7255. } else {
  7256. if( it != itEnd )
  7257. ++it;
  7258. loadBuffer();
  7259. }
  7260. return *this;
  7261. }
  7262. };
  7263. class ResultBase {
  7264. public:
  7265. enum Type {
  7266. Ok, LogicError, RuntimeError
  7267. };
  7268. protected:
  7269. ResultBase( Type type ) : m_type( type ) {}
  7270. virtual ~ResultBase() = default;
  7271. virtual void enforceOk() const = 0;
  7272. Type m_type;
  7273. };
  7274. template<typename T>
  7275. class ResultValueBase : public ResultBase {
  7276. public:
  7277. auto value() const -> T const & {
  7278. enforceOk();
  7279. return m_value;
  7280. }
  7281. protected:
  7282. ResultValueBase( Type type ) : ResultBase( type ) {}
  7283. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  7284. if( m_type == ResultBase::Ok )
  7285. new( &m_value ) T( other.m_value );
  7286. }
  7287. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  7288. new( &m_value ) T( value );
  7289. }
  7290. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  7291. if( m_type == ResultBase::Ok )
  7292. m_value.~T();
  7293. ResultBase::operator=(other);
  7294. if( m_type == ResultBase::Ok )
  7295. new( &m_value ) T( other.m_value );
  7296. return *this;
  7297. }
  7298. ~ResultValueBase() override {
  7299. if( m_type == Ok )
  7300. m_value.~T();
  7301. }
  7302. union {
  7303. T m_value;
  7304. };
  7305. };
  7306. template<>
  7307. class ResultValueBase<void> : public ResultBase {
  7308. protected:
  7309. using ResultBase::ResultBase;
  7310. };
  7311. template<typename T = void>
  7312. class BasicResult : public ResultValueBase<T> {
  7313. public:
  7314. template<typename U>
  7315. explicit BasicResult( BasicResult<U> const &other )
  7316. : ResultValueBase<T>( other.type() ),
  7317. m_errorMessage( other.errorMessage() )
  7318. {
  7319. assert( type() != ResultBase::Ok );
  7320. }
  7321. template<typename U>
  7322. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  7323. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  7324. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  7325. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  7326. explicit operator bool() const { return m_type == ResultBase::Ok; }
  7327. auto type() const -> ResultBase::Type { return m_type; }
  7328. auto errorMessage() const -> std::string { return m_errorMessage; }
  7329. protected:
  7330. void enforceOk() const override {
  7331. // Errors shouldn't reach this point, but if they do
  7332. // the actual error message will be in m_errorMessage
  7333. assert( m_type != ResultBase::LogicError );
  7334. assert( m_type != ResultBase::RuntimeError );
  7335. if( m_type != ResultBase::Ok )
  7336. std::abort();
  7337. }
  7338. std::string m_errorMessage; // Only populated if resultType is an error
  7339. BasicResult( ResultBase::Type type, std::string const &message )
  7340. : ResultValueBase<T>(type),
  7341. m_errorMessage(message)
  7342. {
  7343. assert( m_type != ResultBase::Ok );
  7344. }
  7345. using ResultValueBase<T>::ResultValueBase;
  7346. using ResultBase::m_type;
  7347. };
  7348. enum class ParseResultType {
  7349. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  7350. };
  7351. class ParseState {
  7352. public:
  7353. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  7354. : m_type(type),
  7355. m_remainingTokens( remainingTokens )
  7356. {}
  7357. auto type() const -> ParseResultType { return m_type; }
  7358. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  7359. private:
  7360. ParseResultType m_type;
  7361. TokenStream m_remainingTokens;
  7362. };
  7363. using Result = BasicResult<void>;
  7364. using ParserResult = BasicResult<ParseResultType>;
  7365. using InternalParseResult = BasicResult<ParseState>;
  7366. struct HelpColumns {
  7367. std::string left;
  7368. std::string right;
  7369. };
  7370. template<typename T>
  7371. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  7372. std::stringstream ss;
  7373. ss << source;
  7374. ss >> target;
  7375. if( ss.fail() )
  7376. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  7377. else
  7378. return ParserResult::ok( ParseResultType::Matched );
  7379. }
  7380. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  7381. target = source;
  7382. return ParserResult::ok( ParseResultType::Matched );
  7383. }
  7384. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  7385. std::string srcLC = source;
  7386. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
  7387. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  7388. target = true;
  7389. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  7390. target = false;
  7391. else
  7392. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  7393. return ParserResult::ok( ParseResultType::Matched );
  7394. }
  7395. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  7396. template<typename T>
  7397. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  7398. T temp;
  7399. auto result = convertInto( source, temp );
  7400. if( result )
  7401. target = std::move(temp);
  7402. return result;
  7403. }
  7404. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  7405. struct NonCopyable {
  7406. NonCopyable() = default;
  7407. NonCopyable( NonCopyable const & ) = delete;
  7408. NonCopyable( NonCopyable && ) = delete;
  7409. NonCopyable &operator=( NonCopyable const & ) = delete;
  7410. NonCopyable &operator=( NonCopyable && ) = delete;
  7411. };
  7412. struct BoundRef : NonCopyable {
  7413. virtual ~BoundRef() = default;
  7414. virtual auto isContainer() const -> bool { return false; }
  7415. virtual auto isFlag() const -> bool { return false; }
  7416. };
  7417. struct BoundValueRefBase : BoundRef {
  7418. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  7419. };
  7420. struct BoundFlagRefBase : BoundRef {
  7421. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  7422. virtual auto isFlag() const -> bool { return true; }
  7423. };
  7424. template<typename T>
  7425. struct BoundValueRef : BoundValueRefBase {
  7426. T &m_ref;
  7427. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  7428. auto setValue( std::string const &arg ) -> ParserResult override {
  7429. return convertInto( arg, m_ref );
  7430. }
  7431. };
  7432. template<typename T>
  7433. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  7434. std::vector<T> &m_ref;
  7435. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  7436. auto isContainer() const -> bool override { return true; }
  7437. auto setValue( std::string const &arg ) -> ParserResult override {
  7438. T temp;
  7439. auto result = convertInto( arg, temp );
  7440. if( result )
  7441. m_ref.push_back( temp );
  7442. return result;
  7443. }
  7444. };
  7445. struct BoundFlagRef : BoundFlagRefBase {
  7446. bool &m_ref;
  7447. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  7448. auto setFlag( bool flag ) -> ParserResult override {
  7449. m_ref = flag;
  7450. return ParserResult::ok( ParseResultType::Matched );
  7451. }
  7452. };
  7453. template<typename ReturnType>
  7454. struct LambdaInvoker {
  7455. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  7456. template<typename L, typename ArgType>
  7457. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7458. return lambda( arg );
  7459. }
  7460. };
  7461. template<>
  7462. struct LambdaInvoker<void> {
  7463. template<typename L, typename ArgType>
  7464. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  7465. lambda( arg );
  7466. return ParserResult::ok( ParseResultType::Matched );
  7467. }
  7468. };
  7469. template<typename ArgType, typename L>
  7470. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  7471. ArgType temp{};
  7472. auto result = convertInto( arg, temp );
  7473. return !result
  7474. ? result
  7475. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  7476. }
  7477. template<typename L>
  7478. struct BoundLambda : BoundValueRefBase {
  7479. L m_lambda;
  7480. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7481. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  7482. auto setValue( std::string const &arg ) -> ParserResult override {
  7483. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  7484. }
  7485. };
  7486. template<typename L>
  7487. struct BoundFlagLambda : BoundFlagRefBase {
  7488. L m_lambda;
  7489. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  7490. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  7491. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  7492. auto setFlag( bool flag ) -> ParserResult override {
  7493. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  7494. }
  7495. };
  7496. enum class Optionality { Optional, Required };
  7497. struct Parser;
  7498. class ParserBase {
  7499. public:
  7500. virtual ~ParserBase() = default;
  7501. virtual auto validate() const -> Result { return Result::ok(); }
  7502. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  7503. virtual auto cardinality() const -> size_t { return 1; }
  7504. auto parse( Args const &args ) const -> InternalParseResult {
  7505. return parse( args.exeName(), TokenStream( args ) );
  7506. }
  7507. };
  7508. template<typename DerivedT>
  7509. class ComposableParserImpl : public ParserBase {
  7510. public:
  7511. template<typename T>
  7512. auto operator|( T const &other ) const -> Parser;
  7513. template<typename T>
  7514. auto operator+( T const &other ) const -> Parser;
  7515. };
  7516. // Common code and state for Args and Opts
  7517. template<typename DerivedT>
  7518. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  7519. protected:
  7520. Optionality m_optionality = Optionality::Optional;
  7521. std::shared_ptr<BoundRef> m_ref;
  7522. std::string m_hint;
  7523. std::string m_description;
  7524. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  7525. public:
  7526. template<typename T>
  7527. ParserRefImpl( T &ref, std::string const &hint )
  7528. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  7529. m_hint( hint )
  7530. {}
  7531. template<typename LambdaT>
  7532. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  7533. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  7534. m_hint(hint)
  7535. {}
  7536. auto operator()( std::string const &description ) -> DerivedT & {
  7537. m_description = description;
  7538. return static_cast<DerivedT &>( *this );
  7539. }
  7540. auto optional() -> DerivedT & {
  7541. m_optionality = Optionality::Optional;
  7542. return static_cast<DerivedT &>( *this );
  7543. };
  7544. auto required() -> DerivedT & {
  7545. m_optionality = Optionality::Required;
  7546. return static_cast<DerivedT &>( *this );
  7547. };
  7548. auto isOptional() const -> bool {
  7549. return m_optionality == Optionality::Optional;
  7550. }
  7551. auto cardinality() const -> size_t override {
  7552. if( m_ref->isContainer() )
  7553. return 0;
  7554. else
  7555. return 1;
  7556. }
  7557. auto hint() const -> std::string { return m_hint; }
  7558. };
  7559. class ExeName : public ComposableParserImpl<ExeName> {
  7560. std::shared_ptr<std::string> m_name;
  7561. std::shared_ptr<BoundValueRefBase> m_ref;
  7562. template<typename LambdaT>
  7563. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  7564. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  7565. }
  7566. public:
  7567. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  7568. explicit ExeName( std::string &ref ) : ExeName() {
  7569. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  7570. }
  7571. template<typename LambdaT>
  7572. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  7573. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  7574. }
  7575. // The exe name is not parsed out of the normal tokens, but is handled specially
  7576. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7577. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7578. }
  7579. auto name() const -> std::string { return *m_name; }
  7580. auto set( std::string const& newName ) -> ParserResult {
  7581. auto lastSlash = newName.find_last_of( "\\/" );
  7582. auto filename = ( lastSlash == std::string::npos )
  7583. ? newName
  7584. : newName.substr( lastSlash+1 );
  7585. *m_name = filename;
  7586. if( m_ref )
  7587. return m_ref->setValue( filename );
  7588. else
  7589. return ParserResult::ok( ParseResultType::Matched );
  7590. }
  7591. };
  7592. class Arg : public ParserRefImpl<Arg> {
  7593. public:
  7594. using ParserRefImpl::ParserRefImpl;
  7595. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  7596. auto validationResult = validate();
  7597. if( !validationResult )
  7598. return InternalParseResult( validationResult );
  7599. auto remainingTokens = tokens;
  7600. auto const &token = *remainingTokens;
  7601. if( token.type != TokenType::Argument )
  7602. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7603. assert( !m_ref->isFlag() );
  7604. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7605. auto result = valueRef->setValue( remainingTokens->token );
  7606. if( !result )
  7607. return InternalParseResult( result );
  7608. else
  7609. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7610. }
  7611. };
  7612. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  7613. #ifdef CATCH_PLATFORM_WINDOWS
  7614. if( optName[0] == '/' )
  7615. return "-" + optName.substr( 1 );
  7616. else
  7617. #endif
  7618. return optName;
  7619. }
  7620. class Opt : public ParserRefImpl<Opt> {
  7621. protected:
  7622. std::vector<std::string> m_optNames;
  7623. public:
  7624. template<typename LambdaT>
  7625. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  7626. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  7627. template<typename LambdaT>
  7628. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7629. template<typename T>
  7630. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  7631. auto operator[]( std::string const &optName ) -> Opt & {
  7632. m_optNames.push_back( optName );
  7633. return *this;
  7634. }
  7635. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7636. std::ostringstream oss;
  7637. bool first = true;
  7638. for( auto const &opt : m_optNames ) {
  7639. if (first)
  7640. first = false;
  7641. else
  7642. oss << ", ";
  7643. oss << opt;
  7644. }
  7645. if( !m_hint.empty() )
  7646. oss << " <" << m_hint << ">";
  7647. return { { oss.str(), m_description } };
  7648. }
  7649. auto isMatch( std::string const &optToken ) const -> bool {
  7650. auto normalisedToken = normaliseOpt( optToken );
  7651. for( auto const &name : m_optNames ) {
  7652. if( normaliseOpt( name ) == normalisedToken )
  7653. return true;
  7654. }
  7655. return false;
  7656. }
  7657. using ParserBase::parse;
  7658. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  7659. auto validationResult = validate();
  7660. if( !validationResult )
  7661. return InternalParseResult( validationResult );
  7662. auto remainingTokens = tokens;
  7663. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  7664. auto const &token = *remainingTokens;
  7665. if( isMatch(token.token ) ) {
  7666. if( m_ref->isFlag() ) {
  7667. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  7668. auto result = flagRef->setFlag( true );
  7669. if( !result )
  7670. return InternalParseResult( result );
  7671. if( result.value() == ParseResultType::ShortCircuitAll )
  7672. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7673. } else {
  7674. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  7675. ++remainingTokens;
  7676. if( !remainingTokens )
  7677. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7678. auto const &argToken = *remainingTokens;
  7679. if( argToken.type != TokenType::Argument )
  7680. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  7681. auto result = valueRef->setValue( argToken.token );
  7682. if( !result )
  7683. return InternalParseResult( result );
  7684. if( result.value() == ParseResultType::ShortCircuitAll )
  7685. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  7686. }
  7687. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  7688. }
  7689. }
  7690. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  7691. }
  7692. auto validate() const -> Result override {
  7693. if( m_optNames.empty() )
  7694. return Result::logicError( "No options supplied to Opt" );
  7695. for( auto const &name : m_optNames ) {
  7696. if( name.empty() )
  7697. return Result::logicError( "Option name cannot be empty" );
  7698. #ifdef CATCH_PLATFORM_WINDOWS
  7699. if( name[0] != '-' && name[0] != '/' )
  7700. return Result::logicError( "Option name must begin with '-' or '/'" );
  7701. #else
  7702. if( name[0] != '-' )
  7703. return Result::logicError( "Option name must begin with '-'" );
  7704. #endif
  7705. }
  7706. return ParserRefImpl::validate();
  7707. }
  7708. };
  7709. struct Help : Opt {
  7710. Help( bool &showHelpFlag )
  7711. : Opt([&]( bool flag ) {
  7712. showHelpFlag = flag;
  7713. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  7714. })
  7715. {
  7716. static_cast<Opt &>( *this )
  7717. ("display usage information")
  7718. ["-?"]["-h"]["--help"]
  7719. .optional();
  7720. }
  7721. };
  7722. struct Parser : ParserBase {
  7723. mutable ExeName m_exeName;
  7724. std::vector<Opt> m_options;
  7725. std::vector<Arg> m_args;
  7726. auto operator|=( ExeName const &exeName ) -> Parser & {
  7727. m_exeName = exeName;
  7728. return *this;
  7729. }
  7730. auto operator|=( Arg const &arg ) -> Parser & {
  7731. m_args.push_back(arg);
  7732. return *this;
  7733. }
  7734. auto operator|=( Opt const &opt ) -> Parser & {
  7735. m_options.push_back(opt);
  7736. return *this;
  7737. }
  7738. auto operator|=( Parser const &other ) -> Parser & {
  7739. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  7740. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  7741. return *this;
  7742. }
  7743. template<typename T>
  7744. auto operator|( T const &other ) const -> Parser {
  7745. return Parser( *this ) |= other;
  7746. }
  7747. // Forward deprecated interface with '+' instead of '|'
  7748. template<typename T>
  7749. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  7750. template<typename T>
  7751. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  7752. auto getHelpColumns() const -> std::vector<HelpColumns> {
  7753. std::vector<HelpColumns> cols;
  7754. for (auto const &o : m_options) {
  7755. auto childCols = o.getHelpColumns();
  7756. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  7757. }
  7758. return cols;
  7759. }
  7760. void writeToStream( std::ostream &os ) const {
  7761. if (!m_exeName.name().empty()) {
  7762. os << "usage:\n" << " " << m_exeName.name() << " ";
  7763. bool required = true, first = true;
  7764. for( auto const &arg : m_args ) {
  7765. if (first)
  7766. first = false;
  7767. else
  7768. os << " ";
  7769. if( arg.isOptional() && required ) {
  7770. os << "[";
  7771. required = false;
  7772. }
  7773. os << "<" << arg.hint() << ">";
  7774. if( arg.cardinality() == 0 )
  7775. os << " ... ";
  7776. }
  7777. if( !required )
  7778. os << "]";
  7779. if( !m_options.empty() )
  7780. os << " options";
  7781. os << "\n\nwhere options are:" << std::endl;
  7782. }
  7783. auto rows = getHelpColumns();
  7784. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  7785. size_t optWidth = 0;
  7786. for( auto const &cols : rows )
  7787. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  7788. optWidth = (std::min)(optWidth, consoleWidth/2);
  7789. for( auto const &cols : rows ) {
  7790. auto row =
  7791. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  7792. TextFlow::Spacer(4) +
  7793. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  7794. os << row << std::endl;
  7795. }
  7796. }
  7797. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  7798. parser.writeToStream( os );
  7799. return os;
  7800. }
  7801. auto validate() const -> Result override {
  7802. for( auto const &opt : m_options ) {
  7803. auto result = opt.validate();
  7804. if( !result )
  7805. return result;
  7806. }
  7807. for( auto const &arg : m_args ) {
  7808. auto result = arg.validate();
  7809. if( !result )
  7810. return result;
  7811. }
  7812. return Result::ok();
  7813. }
  7814. using ParserBase::parse;
  7815. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  7816. struct ParserInfo {
  7817. ParserBase const* parser = nullptr;
  7818. size_t count = 0;
  7819. };
  7820. const size_t totalParsers = m_options.size() + m_args.size();
  7821. assert( totalParsers < 512 );
  7822. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  7823. ParserInfo parseInfos[512];
  7824. {
  7825. size_t i = 0;
  7826. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  7827. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  7828. }
  7829. m_exeName.set( exeName );
  7830. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  7831. while( result.value().remainingTokens() ) {
  7832. bool tokenParsed = false;
  7833. for( size_t i = 0; i < totalParsers; ++i ) {
  7834. auto& parseInfo = parseInfos[i];
  7835. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  7836. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  7837. if (!result)
  7838. return result;
  7839. if (result.value().type() != ParseResultType::NoMatch) {
  7840. tokenParsed = true;
  7841. ++parseInfo.count;
  7842. break;
  7843. }
  7844. }
  7845. }
  7846. if( result.value().type() == ParseResultType::ShortCircuitAll )
  7847. return result;
  7848. if( !tokenParsed )
  7849. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  7850. }
  7851. // !TBD Check missing required options
  7852. return result;
  7853. }
  7854. };
  7855. template<typename DerivedT>
  7856. template<typename T>
  7857. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  7858. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  7859. }
  7860. } // namespace detail
  7861. // A Combined parser
  7862. using detail::Parser;
  7863. // A parser for options
  7864. using detail::Opt;
  7865. // A parser for arguments
  7866. using detail::Arg;
  7867. // Wrapper for argc, argv from main()
  7868. using detail::Args;
  7869. // Specifies the name of the executable
  7870. using detail::ExeName;
  7871. // Convenience wrapper for option parser that specifies the help option
  7872. using detail::Help;
  7873. // enum of result types from a parse
  7874. using detail::ParseResultType;
  7875. // Result type for parser operation
  7876. using detail::ParserResult;
  7877. }} // namespace Catch::clara
  7878. // end clara.hpp
  7879. #ifdef __clang__
  7880. #pragma clang diagnostic pop
  7881. #endif
  7882. // Restore Clara's value for console width, if present
  7883. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7884. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7885. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  7886. #endif
  7887. // end catch_clara.h
  7888. namespace Catch {
  7889. clara::Parser makeCommandLineParser( ConfigData& config );
  7890. } // end namespace Catch
  7891. // end catch_commandline.h
  7892. #include <fstream>
  7893. #include <ctime>
  7894. namespace Catch {
  7895. clara::Parser makeCommandLineParser( ConfigData& config ) {
  7896. using namespace clara;
  7897. auto const setWarning = [&]( std::string const& warning ) {
  7898. auto warningSet = [&]() {
  7899. if( warning == "NoAssertions" )
  7900. return WarnAbout::NoAssertions;
  7901. if ( warning == "NoTests" )
  7902. return WarnAbout::NoTests;
  7903. return WarnAbout::Nothing;
  7904. }();
  7905. if (warningSet == WarnAbout::Nothing)
  7906. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  7907. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  7908. return ParserResult::ok( ParseResultType::Matched );
  7909. };
  7910. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  7911. std::ifstream f( filename.c_str() );
  7912. if( !f.is_open() )
  7913. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  7914. std::string line;
  7915. while( std::getline( f, line ) ) {
  7916. line = trim(line);
  7917. if( !line.empty() && !startsWith( line, '#' ) ) {
  7918. if( !startsWith( line, '"' ) )
  7919. line = '"' + line + '"';
  7920. config.testsOrTags.push_back( line );
  7921. config.testsOrTags.emplace_back( "," );
  7922. }
  7923. }
  7924. //Remove comma in the end
  7925. if(!config.testsOrTags.empty())
  7926. config.testsOrTags.erase( config.testsOrTags.end()-1 );
  7927. return ParserResult::ok( ParseResultType::Matched );
  7928. };
  7929. auto const setTestOrder = [&]( std::string const& order ) {
  7930. if( startsWith( "declared", order ) )
  7931. config.runOrder = RunTests::InDeclarationOrder;
  7932. else if( startsWith( "lexical", order ) )
  7933. config.runOrder = RunTests::InLexicographicalOrder;
  7934. else if( startsWith( "random", order ) )
  7935. config.runOrder = RunTests::InRandomOrder;
  7936. else
  7937. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  7938. return ParserResult::ok( ParseResultType::Matched );
  7939. };
  7940. auto const setRngSeed = [&]( std::string const& seed ) {
  7941. if( seed != "time" )
  7942. return clara::detail::convertInto( seed, config.rngSeed );
  7943. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  7944. return ParserResult::ok( ParseResultType::Matched );
  7945. };
  7946. auto const setColourUsage = [&]( std::string const& useColour ) {
  7947. auto mode = toLower( useColour );
  7948. if( mode == "yes" )
  7949. config.useColour = UseColour::Yes;
  7950. else if( mode == "no" )
  7951. config.useColour = UseColour::No;
  7952. else if( mode == "auto" )
  7953. config.useColour = UseColour::Auto;
  7954. else
  7955. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  7956. return ParserResult::ok( ParseResultType::Matched );
  7957. };
  7958. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  7959. auto keypressLc = toLower( keypress );
  7960. if (keypressLc == "never")
  7961. config.waitForKeypress = WaitForKeypress::Never;
  7962. else if( keypressLc == "start" )
  7963. config.waitForKeypress = WaitForKeypress::BeforeStart;
  7964. else if( keypressLc == "exit" )
  7965. config.waitForKeypress = WaitForKeypress::BeforeExit;
  7966. else if( keypressLc == "both" )
  7967. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  7968. else
  7969. return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" );
  7970. return ParserResult::ok( ParseResultType::Matched );
  7971. };
  7972. auto const setVerbosity = [&]( std::string const& verbosity ) {
  7973. auto lcVerbosity = toLower( verbosity );
  7974. if( lcVerbosity == "quiet" )
  7975. config.verbosity = Verbosity::Quiet;
  7976. else if( lcVerbosity == "normal" )
  7977. config.verbosity = Verbosity::Normal;
  7978. else if( lcVerbosity == "high" )
  7979. config.verbosity = Verbosity::High;
  7980. else
  7981. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  7982. return ParserResult::ok( ParseResultType::Matched );
  7983. };
  7984. auto const setReporter = [&]( std::string const& reporter ) {
  7985. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  7986. auto lcReporter = toLower( reporter );
  7987. auto result = factories.find( lcReporter );
  7988. if( factories.end() != result )
  7989. config.reporterName = lcReporter;
  7990. else
  7991. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  7992. return ParserResult::ok( ParseResultType::Matched );
  7993. };
  7994. auto cli
  7995. = ExeName( config.processName )
  7996. | Help( config.showHelp )
  7997. | Opt( config.listTests )
  7998. ["-l"]["--list-tests"]
  7999. ( "list all/matching test cases" )
  8000. | Opt( config.listTags )
  8001. ["-t"]["--list-tags"]
  8002. ( "list all/matching tags" )
  8003. | Opt( config.showSuccessfulTests )
  8004. ["-s"]["--success"]
  8005. ( "include successful tests in output" )
  8006. | Opt( config.shouldDebugBreak )
  8007. ["-b"]["--break"]
  8008. ( "break into debugger on failure" )
  8009. | Opt( config.noThrow )
  8010. ["-e"]["--nothrow"]
  8011. ( "skip exception tests" )
  8012. | Opt( config.showInvisibles )
  8013. ["-i"]["--invisibles"]
  8014. ( "show invisibles (tabs, newlines)" )
  8015. | Opt( config.outputFilename, "filename" )
  8016. ["-o"]["--out"]
  8017. ( "output filename" )
  8018. | Opt( setReporter, "name" )
  8019. ["-r"]["--reporter"]
  8020. ( "reporter to use (defaults to console)" )
  8021. | Opt( config.name, "name" )
  8022. ["-n"]["--name"]
  8023. ( "suite name" )
  8024. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  8025. ["-a"]["--abort"]
  8026. ( "abort at first failure" )
  8027. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  8028. ["-x"]["--abortx"]
  8029. ( "abort after x failures" )
  8030. | Opt( setWarning, "warning name" )
  8031. ["-w"]["--warn"]
  8032. ( "enable warnings" )
  8033. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  8034. ["-d"]["--durations"]
  8035. ( "show test durations" )
  8036. | Opt( config.minDuration, "seconds" )
  8037. ["-D"]["--min-duration"]
  8038. ( "show test durations for tests taking at least the given number of seconds" )
  8039. | Opt( loadTestNamesFromFile, "filename" )
  8040. ["-f"]["--input-file"]
  8041. ( "load test names to run from a file" )
  8042. | Opt( config.filenamesAsTags )
  8043. ["-#"]["--filenames-as-tags"]
  8044. ( "adds a tag for the filename" )
  8045. | Opt( config.sectionsToRun, "section name" )
  8046. ["-c"]["--section"]
  8047. ( "specify section to run" )
  8048. | Opt( setVerbosity, "quiet|normal|high" )
  8049. ["-v"]["--verbosity"]
  8050. ( "set output verbosity" )
  8051. | Opt( config.listTestNamesOnly )
  8052. ["--list-test-names-only"]
  8053. ( "list all/matching test cases names only" )
  8054. | Opt( config.listReporters )
  8055. ["--list-reporters"]
  8056. ( "list all reporters" )
  8057. | Opt( setTestOrder, "decl|lex|rand" )
  8058. ["--order"]
  8059. ( "test case order (defaults to decl)" )
  8060. | Opt( setRngSeed, "'time'|number" )
  8061. ["--rng-seed"]
  8062. ( "set a specific seed for random numbers" )
  8063. | Opt( setColourUsage, "yes|no" )
  8064. ["--use-colour"]
  8065. ( "should output be colourised" )
  8066. | Opt( config.libIdentify )
  8067. ["--libidentify"]
  8068. ( "report name and version according to libidentify standard" )
  8069. | Opt( setWaitForKeypress, "never|start|exit|both" )
  8070. ["--wait-for-keypress"]
  8071. ( "waits for a keypress before exiting" )
  8072. | Opt( config.benchmarkSamples, "samples" )
  8073. ["--benchmark-samples"]
  8074. ( "number of samples to collect (default: 100)" )
  8075. | Opt( config.benchmarkResamples, "resamples" )
  8076. ["--benchmark-resamples"]
  8077. ( "number of resamples for the bootstrap (default: 100000)" )
  8078. | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
  8079. ["--benchmark-confidence-interval"]
  8080. ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
  8081. | Opt( config.benchmarkNoAnalysis )
  8082. ["--benchmark-no-analysis"]
  8083. ( "perform only measurements; do not perform any analysis" )
  8084. | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" )
  8085. ["--benchmark-warmup-time"]
  8086. ( "amount of time in milliseconds spent on warming up each test (default: 100)" )
  8087. | Arg( config.testsOrTags, "test name|pattern|tags" )
  8088. ( "which test or tests to use" );
  8089. return cli;
  8090. }
  8091. } // end namespace Catch
  8092. // end catch_commandline.cpp
  8093. // start catch_common.cpp
  8094. #include <cstring>
  8095. #include <ostream>
  8096. namespace Catch {
  8097. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  8098. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  8099. }
  8100. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  8101. // We can assume that the same file will usually have the same pointer.
  8102. // Thus, if the pointers are the same, there is no point in calling the strcmp
  8103. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  8104. }
  8105. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  8106. #ifndef __GNUG__
  8107. os << info.file << '(' << info.line << ')';
  8108. #else
  8109. os << info.file << ':' << info.line;
  8110. #endif
  8111. return os;
  8112. }
  8113. std::string StreamEndStop::operator+() const {
  8114. return std::string();
  8115. }
  8116. NonCopyable::NonCopyable() = default;
  8117. NonCopyable::~NonCopyable() = default;
  8118. }
  8119. // end catch_common.cpp
  8120. // start catch_config.cpp
  8121. namespace Catch {
  8122. Config::Config( ConfigData const& data )
  8123. : m_data( data ),
  8124. m_stream( openStream() )
  8125. {
  8126. // We need to trim filter specs to avoid trouble with superfluous
  8127. // whitespace (esp. important for bdd macros, as those are manually
  8128. // aligned with whitespace).
  8129. for (auto& elem : m_data.testsOrTags) {
  8130. elem = trim(elem);
  8131. }
  8132. for (auto& elem : m_data.sectionsToRun) {
  8133. elem = trim(elem);
  8134. }
  8135. TestSpecParser parser(ITagAliasRegistry::get());
  8136. if (!m_data.testsOrTags.empty()) {
  8137. m_hasTestFilters = true;
  8138. for (auto const& testOrTags : m_data.testsOrTags) {
  8139. parser.parse(testOrTags);
  8140. }
  8141. }
  8142. m_testSpec = parser.testSpec();
  8143. }
  8144. std::string const& Config::getFilename() const {
  8145. return m_data.outputFilename ;
  8146. }
  8147. bool Config::listTests() const { return m_data.listTests; }
  8148. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  8149. bool Config::listTags() const { return m_data.listTags; }
  8150. bool Config::listReporters() const { return m_data.listReporters; }
  8151. std::string Config::getProcessName() const { return m_data.processName; }
  8152. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  8153. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  8154. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  8155. TestSpec const& Config::testSpec() const { return m_testSpec; }
  8156. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  8157. bool Config::showHelp() const { return m_data.showHelp; }
  8158. // IConfig interface
  8159. bool Config::allowThrows() const { return !m_data.noThrow; }
  8160. std::ostream& Config::stream() const { return m_stream->stream(); }
  8161. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  8162. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  8163. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  8164. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  8165. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  8166. double Config::minDuration() const { return m_data.minDuration; }
  8167. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  8168. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  8169. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  8170. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  8171. int Config::abortAfter() const { return m_data.abortAfter; }
  8172. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  8173. Verbosity Config::verbosity() const { return m_data.verbosity; }
  8174. bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
  8175. int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
  8176. double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
  8177. unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
  8178. std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
  8179. IStream const* Config::openStream() {
  8180. return Catch::makeStream(m_data.outputFilename);
  8181. }
  8182. } // end namespace Catch
  8183. // end catch_config.cpp
  8184. // start catch_console_colour.cpp
  8185. #if defined(__clang__)
  8186. # pragma clang diagnostic push
  8187. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8188. #endif
  8189. // start catch_errno_guard.h
  8190. namespace Catch {
  8191. class ErrnoGuard {
  8192. public:
  8193. ErrnoGuard();
  8194. ~ErrnoGuard();
  8195. private:
  8196. int m_oldErrno;
  8197. };
  8198. }
  8199. // end catch_errno_guard.h
  8200. // start catch_windows_h_proxy.h
  8201. #if defined(CATCH_PLATFORM_WINDOWS)
  8202. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  8203. # define CATCH_DEFINED_NOMINMAX
  8204. # define NOMINMAX
  8205. #endif
  8206. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  8207. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  8208. # define WIN32_LEAN_AND_MEAN
  8209. #endif
  8210. #ifdef __AFXDLL
  8211. #include <AfxWin.h>
  8212. #else
  8213. #include <windows.h>
  8214. #endif
  8215. #ifdef CATCH_DEFINED_NOMINMAX
  8216. # undef NOMINMAX
  8217. #endif
  8218. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  8219. # undef WIN32_LEAN_AND_MEAN
  8220. #endif
  8221. #endif // defined(CATCH_PLATFORM_WINDOWS)
  8222. // end catch_windows_h_proxy.h
  8223. #include <sstream>
  8224. namespace Catch {
  8225. namespace {
  8226. struct IColourImpl {
  8227. virtual ~IColourImpl() = default;
  8228. virtual void use( Colour::Code _colourCode ) = 0;
  8229. };
  8230. struct NoColourImpl : IColourImpl {
  8231. void use( Colour::Code ) override {}
  8232. static IColourImpl* instance() {
  8233. static NoColourImpl s_instance;
  8234. return &s_instance;
  8235. }
  8236. };
  8237. } // anon namespace
  8238. } // namespace Catch
  8239. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  8240. # ifdef CATCH_PLATFORM_WINDOWS
  8241. # define CATCH_CONFIG_COLOUR_WINDOWS
  8242. # else
  8243. # define CATCH_CONFIG_COLOUR_ANSI
  8244. # endif
  8245. #endif
  8246. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  8247. namespace Catch {
  8248. namespace {
  8249. class Win32ColourImpl : public IColourImpl {
  8250. public:
  8251. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  8252. {
  8253. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  8254. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  8255. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  8256. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  8257. }
  8258. void use( Colour::Code _colourCode ) override {
  8259. switch( _colourCode ) {
  8260. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  8261. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8262. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  8263. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  8264. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  8265. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  8266. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  8267. case Colour::Grey: return setTextAttribute( 0 );
  8268. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  8269. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  8270. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  8271. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  8272. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  8273. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8274. default:
  8275. CATCH_ERROR( "Unknown colour requested" );
  8276. }
  8277. }
  8278. private:
  8279. void setTextAttribute( WORD _textAttribute ) {
  8280. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  8281. }
  8282. HANDLE stdoutHandle;
  8283. WORD originalForegroundAttributes;
  8284. WORD originalBackgroundAttributes;
  8285. };
  8286. IColourImpl* platformColourInstance() {
  8287. static Win32ColourImpl s_instance;
  8288. IConfigPtr config = getCurrentContext().getConfig();
  8289. UseColour::YesOrNo colourMode = config
  8290. ? config->useColour()
  8291. : UseColour::Auto;
  8292. if( colourMode == UseColour::Auto )
  8293. colourMode = UseColour::Yes;
  8294. return colourMode == UseColour::Yes
  8295. ? &s_instance
  8296. : NoColourImpl::instance();
  8297. }
  8298. } // end anon namespace
  8299. } // end namespace Catch
  8300. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  8301. #include <unistd.h>
  8302. namespace Catch {
  8303. namespace {
  8304. // use POSIX/ ANSI console terminal codes
  8305. // Thanks to Adam Strzelecki for original contribution
  8306. // (http://github.com/nanoant)
  8307. // https://github.com/philsquared/Catch/pull/131
  8308. class PosixColourImpl : public IColourImpl {
  8309. public:
  8310. void use( Colour::Code _colourCode ) override {
  8311. switch( _colourCode ) {
  8312. case Colour::None:
  8313. case Colour::White: return setColour( "[0m" );
  8314. case Colour::Red: return setColour( "[0;31m" );
  8315. case Colour::Green: return setColour( "[0;32m" );
  8316. case Colour::Blue: return setColour( "[0;34m" );
  8317. case Colour::Cyan: return setColour( "[0;36m" );
  8318. case Colour::Yellow: return setColour( "[0;33m" );
  8319. case Colour::Grey: return setColour( "[1;30m" );
  8320. case Colour::LightGrey: return setColour( "[0;37m" );
  8321. case Colour::BrightRed: return setColour( "[1;31m" );
  8322. case Colour::BrightGreen: return setColour( "[1;32m" );
  8323. case Colour::BrightWhite: return setColour( "[1;37m" );
  8324. case Colour::BrightYellow: return setColour( "[1;33m" );
  8325. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  8326. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  8327. }
  8328. }
  8329. static IColourImpl* instance() {
  8330. static PosixColourImpl s_instance;
  8331. return &s_instance;
  8332. }
  8333. private:
  8334. void setColour( const char* _escapeCode ) {
  8335. getCurrentContext().getConfig()->stream()
  8336. << '\033' << _escapeCode;
  8337. }
  8338. };
  8339. bool useColourOnPlatform() {
  8340. return
  8341. #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
  8342. !isDebuggerActive() &&
  8343. #endif
  8344. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  8345. isatty(STDOUT_FILENO)
  8346. #else
  8347. false
  8348. #endif
  8349. ;
  8350. }
  8351. IColourImpl* platformColourInstance() {
  8352. ErrnoGuard guard;
  8353. IConfigPtr config = getCurrentContext().getConfig();
  8354. UseColour::YesOrNo colourMode = config
  8355. ? config->useColour()
  8356. : UseColour::Auto;
  8357. if( colourMode == UseColour::Auto )
  8358. colourMode = useColourOnPlatform()
  8359. ? UseColour::Yes
  8360. : UseColour::No;
  8361. return colourMode == UseColour::Yes
  8362. ? PosixColourImpl::instance()
  8363. : NoColourImpl::instance();
  8364. }
  8365. } // end anon namespace
  8366. } // end namespace Catch
  8367. #else // not Windows or ANSI ///////////////////////////////////////////////
  8368. namespace Catch {
  8369. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  8370. } // end namespace Catch
  8371. #endif // Windows/ ANSI/ None
  8372. namespace Catch {
  8373. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  8374. Colour::Colour( Colour&& other ) noexcept {
  8375. m_moved = other.m_moved;
  8376. other.m_moved = true;
  8377. }
  8378. Colour& Colour::operator=( Colour&& other ) noexcept {
  8379. m_moved = other.m_moved;
  8380. other.m_moved = true;
  8381. return *this;
  8382. }
  8383. Colour::~Colour(){ if( !m_moved ) use( None ); }
  8384. void Colour::use( Code _colourCode ) {
  8385. static IColourImpl* impl = platformColourInstance();
  8386. // Strictly speaking, this cannot possibly happen.
  8387. // However, under some conditions it does happen (see #1626),
  8388. // and this change is small enough that we can let practicality
  8389. // triumph over purity in this case.
  8390. if (impl != nullptr) {
  8391. impl->use( _colourCode );
  8392. }
  8393. }
  8394. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  8395. return os;
  8396. }
  8397. } // end namespace Catch
  8398. #if defined(__clang__)
  8399. # pragma clang diagnostic pop
  8400. #endif
  8401. // end catch_console_colour.cpp
  8402. // start catch_context.cpp
  8403. namespace Catch {
  8404. class Context : public IMutableContext, NonCopyable {
  8405. public: // IContext
  8406. IResultCapture* getResultCapture() override {
  8407. return m_resultCapture;
  8408. }
  8409. IRunner* getRunner() override {
  8410. return m_runner;
  8411. }
  8412. IConfigPtr const& getConfig() const override {
  8413. return m_config;
  8414. }
  8415. ~Context() override;
  8416. public: // IMutableContext
  8417. void setResultCapture( IResultCapture* resultCapture ) override {
  8418. m_resultCapture = resultCapture;
  8419. }
  8420. void setRunner( IRunner* runner ) override {
  8421. m_runner = runner;
  8422. }
  8423. void setConfig( IConfigPtr const& config ) override {
  8424. m_config = config;
  8425. }
  8426. friend IMutableContext& getCurrentMutableContext();
  8427. private:
  8428. IConfigPtr m_config;
  8429. IRunner* m_runner = nullptr;
  8430. IResultCapture* m_resultCapture = nullptr;
  8431. };
  8432. IMutableContext *IMutableContext::currentContext = nullptr;
  8433. void IMutableContext::createContext()
  8434. {
  8435. currentContext = new Context();
  8436. }
  8437. void cleanUpContext() {
  8438. delete IMutableContext::currentContext;
  8439. IMutableContext::currentContext = nullptr;
  8440. }
  8441. IContext::~IContext() = default;
  8442. IMutableContext::~IMutableContext() = default;
  8443. Context::~Context() = default;
  8444. SimplePcg32& rng() {
  8445. static SimplePcg32 s_rng;
  8446. return s_rng;
  8447. }
  8448. }
  8449. // end catch_context.cpp
  8450. // start catch_debug_console.cpp
  8451. // start catch_debug_console.h
  8452. #include <string>
  8453. namespace Catch {
  8454. void writeToDebugConsole( std::string const& text );
  8455. }
  8456. // end catch_debug_console.h
  8457. #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
  8458. #include <android/log.h>
  8459. namespace Catch {
  8460. void writeToDebugConsole( std::string const& text ) {
  8461. __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
  8462. }
  8463. }
  8464. #elif defined(CATCH_PLATFORM_WINDOWS)
  8465. namespace Catch {
  8466. void writeToDebugConsole( std::string const& text ) {
  8467. ::OutputDebugStringA( text.c_str() );
  8468. }
  8469. }
  8470. #else
  8471. namespace Catch {
  8472. void writeToDebugConsole( std::string const& text ) {
  8473. // !TBD: Need a version for Mac/ XCode and other IDEs
  8474. Catch::cout() << text;
  8475. }
  8476. }
  8477. #endif // Platform
  8478. // end catch_debug_console.cpp
  8479. // start catch_debugger.cpp
  8480. #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
  8481. # include <cassert>
  8482. # include <sys/types.h>
  8483. # include <unistd.h>
  8484. # include <cstddef>
  8485. # include <ostream>
  8486. #ifdef __apple_build_version__
  8487. // These headers will only compile with AppleClang (XCode)
  8488. // For other compilers (Clang, GCC, ... ) we need to exclude them
  8489. # include <sys/sysctl.h>
  8490. #endif
  8491. namespace Catch {
  8492. #ifdef __apple_build_version__
  8493. // The following function is taken directly from the following technical note:
  8494. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  8495. // Returns true if the current process is being debugged (either
  8496. // running under the debugger or has a debugger attached post facto).
  8497. bool isDebuggerActive(){
  8498. int mib[4];
  8499. struct kinfo_proc info;
  8500. std::size_t size;
  8501. // Initialize the flags so that, if sysctl fails for some bizarre
  8502. // reason, we get a predictable result.
  8503. info.kp_proc.p_flag = 0;
  8504. // Initialize mib, which tells sysctl the info we want, in this case
  8505. // we're looking for information about a specific process ID.
  8506. mib[0] = CTL_KERN;
  8507. mib[1] = KERN_PROC;
  8508. mib[2] = KERN_PROC_PID;
  8509. mib[3] = getpid();
  8510. // Call sysctl.
  8511. size = sizeof(info);
  8512. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  8513. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  8514. return false;
  8515. }
  8516. // We're being debugged if the P_TRACED flag is set.
  8517. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  8518. }
  8519. #else
  8520. bool isDebuggerActive() {
  8521. // We need to find another way to determine this for non-appleclang compilers on macOS
  8522. return false;
  8523. }
  8524. #endif
  8525. } // namespace Catch
  8526. #elif defined(CATCH_PLATFORM_LINUX)
  8527. #include <fstream>
  8528. #include <string>
  8529. namespace Catch{
  8530. // The standard POSIX way of detecting a debugger is to attempt to
  8531. // ptrace() the process, but this needs to be done from a child and not
  8532. // this process itself to still allow attaching to this process later
  8533. // if wanted, so is rather heavy. Under Linux we have the PID of the
  8534. // "debugger" (which doesn't need to be gdb, of course, it could also
  8535. // be strace, for example) in /proc/$PID/status, so just get it from
  8536. // there instead.
  8537. bool isDebuggerActive(){
  8538. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  8539. // This way our users can properly assert over errno values
  8540. ErrnoGuard guard;
  8541. std::ifstream in("/proc/self/status");
  8542. for( std::string line; std::getline(in, line); ) {
  8543. static const int PREFIX_LEN = 11;
  8544. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  8545. // We're traced if the PID is not 0 and no other PID starts
  8546. // with 0 digit, so it's enough to check for just a single
  8547. // character.
  8548. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  8549. }
  8550. }
  8551. return false;
  8552. }
  8553. } // namespace Catch
  8554. #elif defined(_MSC_VER)
  8555. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8556. namespace Catch {
  8557. bool isDebuggerActive() {
  8558. return IsDebuggerPresent() != 0;
  8559. }
  8560. }
  8561. #elif defined(__MINGW32__)
  8562. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  8563. namespace Catch {
  8564. bool isDebuggerActive() {
  8565. return IsDebuggerPresent() != 0;
  8566. }
  8567. }
  8568. #else
  8569. namespace Catch {
  8570. bool isDebuggerActive() { return false; }
  8571. }
  8572. #endif // Platform
  8573. // end catch_debugger.cpp
  8574. // start catch_decomposer.cpp
  8575. namespace Catch {
  8576. ITransientExpression::~ITransientExpression() = default;
  8577. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  8578. if( lhs.size() + rhs.size() < 40 &&
  8579. lhs.find('\n') == std::string::npos &&
  8580. rhs.find('\n') == std::string::npos )
  8581. os << lhs << " " << op << " " << rhs;
  8582. else
  8583. os << lhs << "\n" << op << "\n" << rhs;
  8584. }
  8585. }
  8586. // end catch_decomposer.cpp
  8587. // start catch_enforce.cpp
  8588. #include <stdexcept>
  8589. namespace Catch {
  8590. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  8591. [[noreturn]]
  8592. void throw_exception(std::exception const& e) {
  8593. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  8594. << "The message was: " << e.what() << '\n';
  8595. std::terminate();
  8596. }
  8597. #endif
  8598. [[noreturn]]
  8599. void throw_logic_error(std::string const& msg) {
  8600. throw_exception(std::logic_error(msg));
  8601. }
  8602. [[noreturn]]
  8603. void throw_domain_error(std::string const& msg) {
  8604. throw_exception(std::domain_error(msg));
  8605. }
  8606. [[noreturn]]
  8607. void throw_runtime_error(std::string const& msg) {
  8608. throw_exception(std::runtime_error(msg));
  8609. }
  8610. } // namespace Catch;
  8611. // end catch_enforce.cpp
  8612. // start catch_enum_values_registry.cpp
  8613. // start catch_enum_values_registry.h
  8614. #include <vector>
  8615. #include <memory>
  8616. namespace Catch {
  8617. namespace Detail {
  8618. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
  8619. class EnumValuesRegistry : public IMutableEnumValuesRegistry {
  8620. std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
  8621. EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
  8622. };
  8623. std::vector<StringRef> parseEnums( StringRef enums );
  8624. } // Detail
  8625. } // Catch
  8626. // end catch_enum_values_registry.h
  8627. #include <map>
  8628. #include <cassert>
  8629. namespace Catch {
  8630. IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
  8631. namespace Detail {
  8632. namespace {
  8633. // Extracts the actual name part of an enum instance
  8634. // In other words, it returns the Blue part of Bikeshed::Colour::Blue
  8635. StringRef extractInstanceName(StringRef enumInstance) {
  8636. // Find last occurrence of ":"
  8637. size_t name_start = enumInstance.size();
  8638. while (name_start > 0 && enumInstance[name_start - 1] != ':') {
  8639. --name_start;
  8640. }
  8641. return enumInstance.substr(name_start, enumInstance.size() - name_start);
  8642. }
  8643. }
  8644. std::vector<StringRef> parseEnums( StringRef enums ) {
  8645. auto enumValues = splitStringRef( enums, ',' );
  8646. std::vector<StringRef> parsed;
  8647. parsed.reserve( enumValues.size() );
  8648. for( auto const& enumValue : enumValues ) {
  8649. parsed.push_back(trim(extractInstanceName(enumValue)));
  8650. }
  8651. return parsed;
  8652. }
  8653. EnumInfo::~EnumInfo() {}
  8654. StringRef EnumInfo::lookup( int value ) const {
  8655. for( auto const& valueToName : m_values ) {
  8656. if( valueToName.first == value )
  8657. return valueToName.second;
  8658. }
  8659. return "{** unexpected enum value **}"_sr;
  8660. }
  8661. std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8662. std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
  8663. enumInfo->m_name = enumName;
  8664. enumInfo->m_values.reserve( values.size() );
  8665. const auto valueNames = Catch::Detail::parseEnums( allValueNames );
  8666. assert( valueNames.size() == values.size() );
  8667. std::size_t i = 0;
  8668. for( auto value : values )
  8669. enumInfo->m_values.emplace_back(value, valueNames[i++]);
  8670. return enumInfo;
  8671. }
  8672. EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
  8673. m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
  8674. return *m_enumInfos.back();
  8675. }
  8676. } // Detail
  8677. } // Catch
  8678. // end catch_enum_values_registry.cpp
  8679. // start catch_errno_guard.cpp
  8680. #include <cerrno>
  8681. namespace Catch {
  8682. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  8683. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  8684. }
  8685. // end catch_errno_guard.cpp
  8686. // start catch_exception_translator_registry.cpp
  8687. // start catch_exception_translator_registry.h
  8688. #include <vector>
  8689. #include <string>
  8690. #include <memory>
  8691. namespace Catch {
  8692. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  8693. public:
  8694. ~ExceptionTranslatorRegistry();
  8695. virtual void registerTranslator( const IExceptionTranslator* translator );
  8696. std::string translateActiveException() const override;
  8697. std::string tryTranslators() const;
  8698. private:
  8699. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  8700. };
  8701. }
  8702. // end catch_exception_translator_registry.h
  8703. #ifdef __OBJC__
  8704. #import "Foundation/Foundation.h"
  8705. #endif
  8706. namespace Catch {
  8707. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  8708. }
  8709. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  8710. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  8711. }
  8712. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8713. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8714. try {
  8715. #ifdef __OBJC__
  8716. // In Objective-C try objective-c exceptions first
  8717. @try {
  8718. return tryTranslators();
  8719. }
  8720. @catch (NSException *exception) {
  8721. return Catch::Detail::stringify( [exception description] );
  8722. }
  8723. #else
  8724. // Compiling a mixed mode project with MSVC means that CLR
  8725. // exceptions will be caught in (...) as well. However, these
  8726. // do not fill-in std::current_exception and thus lead to crash
  8727. // when attempting rethrow.
  8728. // /EHa switch also causes structured exceptions to be caught
  8729. // here, but they fill-in current_exception properly, so
  8730. // at worst the output should be a little weird, instead of
  8731. // causing a crash.
  8732. if (std::current_exception() == nullptr) {
  8733. return "Non C++ exception. Possibly a CLR exception.";
  8734. }
  8735. return tryTranslators();
  8736. #endif
  8737. }
  8738. catch( TestFailureException& ) {
  8739. std::rethrow_exception(std::current_exception());
  8740. }
  8741. catch( std::exception& ex ) {
  8742. return ex.what();
  8743. }
  8744. catch( std::string& msg ) {
  8745. return msg;
  8746. }
  8747. catch( const char* msg ) {
  8748. return msg;
  8749. }
  8750. catch(...) {
  8751. return "Unknown exception";
  8752. }
  8753. }
  8754. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8755. if (m_translators.empty()) {
  8756. std::rethrow_exception(std::current_exception());
  8757. } else {
  8758. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  8759. }
  8760. }
  8761. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  8762. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  8763. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8764. }
  8765. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  8766. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  8767. }
  8768. #endif
  8769. }
  8770. // end catch_exception_translator_registry.cpp
  8771. // start catch_fatal_condition.cpp
  8772. #include <algorithm>
  8773. #if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS )
  8774. namespace Catch {
  8775. // If neither SEH nor signal handling is required, the handler impls
  8776. // do not have to do anything, and can be empty.
  8777. void FatalConditionHandler::engage_platform() {}
  8778. void FatalConditionHandler::disengage_platform() {}
  8779. FatalConditionHandler::FatalConditionHandler() = default;
  8780. FatalConditionHandler::~FatalConditionHandler() = default;
  8781. } // end namespace Catch
  8782. #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
  8783. #if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS )
  8784. #error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
  8785. #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
  8786. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  8787. namespace {
  8788. //! Signals fatal error message to the run context
  8789. void reportFatal( char const * const message ) {
  8790. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  8791. }
  8792. //! Minimal size Catch2 needs for its own fatal error handling.
  8793. //! Picked anecdotally, so it might not be sufficient on all
  8794. //! platforms, and for all configurations.
  8795. constexpr std::size_t minStackSizeForErrors = 32 * 1024;
  8796. } // end unnamed namespace
  8797. #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
  8798. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  8799. namespace Catch {
  8800. struct SignalDefs { DWORD id; const char* name; };
  8801. // There is no 1-1 mapping between signals and windows exceptions.
  8802. // Windows can easily distinguish between SO and SigSegV,
  8803. // but SigInt, SigTerm, etc are handled differently.
  8804. static SignalDefs signalDefs[] = {
  8805. { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
  8806. { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
  8807. { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
  8808. { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
  8809. };
  8810. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  8811. for (auto const& def : signalDefs) {
  8812. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  8813. reportFatal(def.name);
  8814. }
  8815. }
  8816. // If its not an exception we care about, pass it along.
  8817. // This stops us from eating debugger breaks etc.
  8818. return EXCEPTION_CONTINUE_SEARCH;
  8819. }
  8820. // Since we do not support multiple instantiations, we put these
  8821. // into global variables and rely on cleaning them up in outlined
  8822. // constructors/destructors
  8823. static PVOID exceptionHandlerHandle = nullptr;
  8824. // For MSVC, we reserve part of the stack memory for handling
  8825. // memory overflow structured exception.
  8826. FatalConditionHandler::FatalConditionHandler() {
  8827. ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors);
  8828. if (!SetThreadStackGuarantee(&guaranteeSize)) {
  8829. // We do not want to fully error out, because needing
  8830. // the stack reserve should be rare enough anyway.
  8831. Catch::cerr()
  8832. << "Failed to reserve piece of stack."
  8833. << " Stack overflows will not be reported successfully.";
  8834. }
  8835. }
  8836. // We do not attempt to unset the stack guarantee, because
  8837. // Windows does not support lowering the stack size guarantee.
  8838. FatalConditionHandler::~FatalConditionHandler() = default;
  8839. void FatalConditionHandler::engage_platform() {
  8840. // Register as first handler in current chain
  8841. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  8842. if (!exceptionHandlerHandle) {
  8843. CATCH_RUNTIME_ERROR("Could not register vectored exception handler");
  8844. }
  8845. }
  8846. void FatalConditionHandler::disengage_platform() {
  8847. if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
  8848. CATCH_RUNTIME_ERROR("Could not unregister vectored exception handler");
  8849. }
  8850. exceptionHandlerHandle = nullptr;
  8851. }
  8852. } // end namespace Catch
  8853. #endif // CATCH_CONFIG_WINDOWS_SEH
  8854. #if defined( CATCH_CONFIG_POSIX_SIGNALS )
  8855. #include <signal.h>
  8856. namespace Catch {
  8857. struct SignalDefs {
  8858. int id;
  8859. const char* name;
  8860. };
  8861. static SignalDefs signalDefs[] = {
  8862. { SIGINT, "SIGINT - Terminal interrupt signal" },
  8863. { SIGILL, "SIGILL - Illegal instruction signal" },
  8864. { SIGFPE, "SIGFPE - Floating point error signal" },
  8865. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  8866. { SIGTERM, "SIGTERM - Termination request signal" },
  8867. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  8868. };
  8869. // Older GCCs trigger -Wmissing-field-initializers for T foo = {}
  8870. // which is zero initialization, but not explicit. We want to avoid
  8871. // that.
  8872. #if defined(__GNUC__)
  8873. # pragma GCC diagnostic push
  8874. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  8875. #endif
  8876. static char* altStackMem = nullptr;
  8877. static std::size_t altStackSize = 0;
  8878. static stack_t oldSigStack{};
  8879. static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
  8880. static void restorePreviousSignalHandlers() {
  8881. // We set signal handlers back to the previous ones. Hopefully
  8882. // nobody overwrote them in the meantime, and doesn't expect
  8883. // their signal handlers to live past ours given that they
  8884. // installed them after ours..
  8885. for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
  8886. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  8887. }
  8888. // Return the old stack
  8889. sigaltstack(&oldSigStack, nullptr);
  8890. }
  8891. static void handleSignal( int sig ) {
  8892. char const * name = "<unknown signal>";
  8893. for (auto const& def : signalDefs) {
  8894. if (sig == def.id) {
  8895. name = def.name;
  8896. break;
  8897. }
  8898. }
  8899. // We need to restore previous signal handlers and let them do
  8900. // their thing, so that the users can have the debugger break
  8901. // when a signal is raised, and so on.
  8902. restorePreviousSignalHandlers();
  8903. reportFatal( name );
  8904. raise( sig );
  8905. }
  8906. FatalConditionHandler::FatalConditionHandler() {
  8907. assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists");
  8908. if (altStackSize == 0) {
  8909. altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
  8910. }
  8911. altStackMem = new char[altStackSize]();
  8912. }
  8913. FatalConditionHandler::~FatalConditionHandler() {
  8914. delete[] altStackMem;
  8915. // We signal that another instance can be constructed by zeroing
  8916. // out the pointer.
  8917. altStackMem = nullptr;
  8918. }
  8919. void FatalConditionHandler::engage_platform() {
  8920. stack_t sigStack;
  8921. sigStack.ss_sp = altStackMem;
  8922. sigStack.ss_size = altStackSize;
  8923. sigStack.ss_flags = 0;
  8924. sigaltstack(&sigStack, &oldSigStack);
  8925. struct sigaction sa = { };
  8926. sa.sa_handler = handleSignal;
  8927. sa.sa_flags = SA_ONSTACK;
  8928. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  8929. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  8930. }
  8931. }
  8932. #if defined(__GNUC__)
  8933. # pragma GCC diagnostic pop
  8934. #endif
  8935. void FatalConditionHandler::disengage_platform() {
  8936. restorePreviousSignalHandlers();
  8937. }
  8938. } // end namespace Catch
  8939. #endif // CATCH_CONFIG_POSIX_SIGNALS
  8940. // end catch_fatal_condition.cpp
  8941. // start catch_generators.cpp
  8942. #include <limits>
  8943. #include <set>
  8944. namespace Catch {
  8945. IGeneratorTracker::~IGeneratorTracker() {}
  8946. const char* GeneratorException::what() const noexcept {
  8947. return m_msg;
  8948. }
  8949. namespace Generators {
  8950. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  8951. auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8952. return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
  8953. }
  8954. } // namespace Generators
  8955. } // namespace Catch
  8956. // end catch_generators.cpp
  8957. // start catch_interfaces_capture.cpp
  8958. namespace Catch {
  8959. IResultCapture::~IResultCapture() = default;
  8960. }
  8961. // end catch_interfaces_capture.cpp
  8962. // start catch_interfaces_config.cpp
  8963. namespace Catch {
  8964. IConfig::~IConfig() = default;
  8965. }
  8966. // end catch_interfaces_config.cpp
  8967. // start catch_interfaces_exception.cpp
  8968. namespace Catch {
  8969. IExceptionTranslator::~IExceptionTranslator() = default;
  8970. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  8971. }
  8972. // end catch_interfaces_exception.cpp
  8973. // start catch_interfaces_registry_hub.cpp
  8974. namespace Catch {
  8975. IRegistryHub::~IRegistryHub() = default;
  8976. IMutableRegistryHub::~IMutableRegistryHub() = default;
  8977. }
  8978. // end catch_interfaces_registry_hub.cpp
  8979. // start catch_interfaces_reporter.cpp
  8980. // start catch_reporter_listening.h
  8981. namespace Catch {
  8982. class ListeningReporter : public IStreamingReporter {
  8983. using Reporters = std::vector<IStreamingReporterPtr>;
  8984. Reporters m_listeners;
  8985. IStreamingReporterPtr m_reporter = nullptr;
  8986. ReporterPreferences m_preferences;
  8987. public:
  8988. ListeningReporter();
  8989. void addListener( IStreamingReporterPtr&& listener );
  8990. void addReporter( IStreamingReporterPtr&& reporter );
  8991. public: // IStreamingReporter
  8992. ReporterPreferences getPreferences() const override;
  8993. void noMatchingTestCases( std::string const& spec ) override;
  8994. void reportInvalidArguments(std::string const&arg) override;
  8995. static std::set<Verbosity> getSupportedVerbosities();
  8996. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  8997. void benchmarkPreparing(std::string const& name) override;
  8998. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  8999. void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
  9000. void benchmarkFailed(std::string const&) override;
  9001. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  9002. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  9003. void testGroupStarting( GroupInfo const& groupInfo ) override;
  9004. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  9005. void sectionStarting( SectionInfo const& sectionInfo ) override;
  9006. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  9007. // The return value indicates if the messages buffer should be cleared:
  9008. bool assertionEnded( AssertionStats const& assertionStats ) override;
  9009. void sectionEnded( SectionStats const& sectionStats ) override;
  9010. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  9011. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  9012. void testRunEnded( TestRunStats const& testRunStats ) override;
  9013. void skipTest( TestCaseInfo const& testInfo ) override;
  9014. bool isMulti() const override;
  9015. };
  9016. } // end namespace Catch
  9017. // end catch_reporter_listening.h
  9018. namespace Catch {
  9019. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  9020. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  9021. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  9022. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  9023. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  9024. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  9025. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  9026. GroupInfo::GroupInfo( std::string const& _name,
  9027. std::size_t _groupIndex,
  9028. std::size_t _groupsCount )
  9029. : name( _name ),
  9030. groupIndex( _groupIndex ),
  9031. groupsCounts( _groupsCount )
  9032. {}
  9033. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  9034. std::vector<MessageInfo> const& _infoMessages,
  9035. Totals const& _totals )
  9036. : assertionResult( _assertionResult ),
  9037. infoMessages( _infoMessages ),
  9038. totals( _totals )
  9039. {
  9040. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  9041. if( assertionResult.hasMessage() ) {
  9042. // Copy message into messages list.
  9043. // !TBD This should have been done earlier, somewhere
  9044. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  9045. builder << assertionResult.getMessage();
  9046. builder.m_info.message = builder.m_stream.str();
  9047. infoMessages.push_back( builder.m_info );
  9048. }
  9049. }
  9050. AssertionStats::~AssertionStats() = default;
  9051. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  9052. Counts const& _assertions,
  9053. double _durationInSeconds,
  9054. bool _missingAssertions )
  9055. : sectionInfo( _sectionInfo ),
  9056. assertions( _assertions ),
  9057. durationInSeconds( _durationInSeconds ),
  9058. missingAssertions( _missingAssertions )
  9059. {}
  9060. SectionStats::~SectionStats() = default;
  9061. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  9062. Totals const& _totals,
  9063. std::string const& _stdOut,
  9064. std::string const& _stdErr,
  9065. bool _aborting )
  9066. : testInfo( _testInfo ),
  9067. totals( _totals ),
  9068. stdOut( _stdOut ),
  9069. stdErr( _stdErr ),
  9070. aborting( _aborting )
  9071. {}
  9072. TestCaseStats::~TestCaseStats() = default;
  9073. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  9074. Totals const& _totals,
  9075. bool _aborting )
  9076. : groupInfo( _groupInfo ),
  9077. totals( _totals ),
  9078. aborting( _aborting )
  9079. {}
  9080. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  9081. : groupInfo( _groupInfo ),
  9082. aborting( false )
  9083. {}
  9084. TestGroupStats::~TestGroupStats() = default;
  9085. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  9086. Totals const& _totals,
  9087. bool _aborting )
  9088. : runInfo( _runInfo ),
  9089. totals( _totals ),
  9090. aborting( _aborting )
  9091. {}
  9092. TestRunStats::~TestRunStats() = default;
  9093. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  9094. bool IStreamingReporter::isMulti() const { return false; }
  9095. IReporterFactory::~IReporterFactory() = default;
  9096. IReporterRegistry::~IReporterRegistry() = default;
  9097. } // end namespace Catch
  9098. // end catch_interfaces_reporter.cpp
  9099. // start catch_interfaces_runner.cpp
  9100. namespace Catch {
  9101. IRunner::~IRunner() = default;
  9102. }
  9103. // end catch_interfaces_runner.cpp
  9104. // start catch_interfaces_testcase.cpp
  9105. namespace Catch {
  9106. ITestInvoker::~ITestInvoker() = default;
  9107. ITestCaseRegistry::~ITestCaseRegistry() = default;
  9108. }
  9109. // end catch_interfaces_testcase.cpp
  9110. // start catch_leak_detector.cpp
  9111. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  9112. #include <crtdbg.h>
  9113. namespace Catch {
  9114. LeakDetector::LeakDetector() {
  9115. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  9116. flag |= _CRTDBG_LEAK_CHECK_DF;
  9117. flag |= _CRTDBG_ALLOC_MEM_DF;
  9118. _CrtSetDbgFlag(flag);
  9119. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  9120. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  9121. // Change this to leaking allocation's number to break there
  9122. _CrtSetBreakAlloc(-1);
  9123. }
  9124. }
  9125. #else
  9126. Catch::LeakDetector::LeakDetector() {}
  9127. #endif
  9128. Catch::LeakDetector::~LeakDetector() {
  9129. Catch::cleanUp();
  9130. }
  9131. // end catch_leak_detector.cpp
  9132. // start catch_list.cpp
  9133. // start catch_list.h
  9134. #include <set>
  9135. namespace Catch {
  9136. std::size_t listTests( Config const& config );
  9137. std::size_t listTestsNamesOnly( Config const& config );
  9138. struct TagInfo {
  9139. void add( std::string const& spelling );
  9140. std::string all() const;
  9141. std::set<std::string> spellings;
  9142. std::size_t count = 0;
  9143. };
  9144. std::size_t listTags( Config const& config );
  9145. std::size_t listReporters();
  9146. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  9147. } // end namespace Catch
  9148. // end catch_list.h
  9149. // start catch_text.h
  9150. namespace Catch {
  9151. using namespace clara::TextFlow;
  9152. }
  9153. // end catch_text.h
  9154. #include <limits>
  9155. #include <algorithm>
  9156. #include <iomanip>
  9157. namespace Catch {
  9158. std::size_t listTests( Config const& config ) {
  9159. TestSpec const& testSpec = config.testSpec();
  9160. if( config.hasTestFilters() )
  9161. Catch::cout() << "Matching test cases:\n";
  9162. else {
  9163. Catch::cout() << "All available test cases:\n";
  9164. }
  9165. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9166. for( auto const& testCaseInfo : matchedTestCases ) {
  9167. Colour::Code colour = testCaseInfo.isHidden()
  9168. ? Colour::SecondaryText
  9169. : Colour::None;
  9170. Colour colourGuard( colour );
  9171. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  9172. if( config.verbosity() >= Verbosity::High ) {
  9173. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  9174. std::string description = testCaseInfo.description;
  9175. if( description.empty() )
  9176. description = "(NO DESCRIPTION)";
  9177. Catch::cout() << Column( description ).indent(4) << std::endl;
  9178. }
  9179. if( !testCaseInfo.tags.empty() )
  9180. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  9181. }
  9182. if( !config.hasTestFilters() )
  9183. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  9184. else
  9185. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  9186. return matchedTestCases.size();
  9187. }
  9188. std::size_t listTestsNamesOnly( Config const& config ) {
  9189. TestSpec const& testSpec = config.testSpec();
  9190. std::size_t matchedTests = 0;
  9191. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9192. for( auto const& testCaseInfo : matchedTestCases ) {
  9193. matchedTests++;
  9194. if( startsWith( testCaseInfo.name, '#' ) )
  9195. Catch::cout() << '"' << testCaseInfo.name << '"';
  9196. else
  9197. Catch::cout() << testCaseInfo.name;
  9198. if ( config.verbosity() >= Verbosity::High )
  9199. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  9200. Catch::cout() << std::endl;
  9201. }
  9202. return matchedTests;
  9203. }
  9204. void TagInfo::add( std::string const& spelling ) {
  9205. ++count;
  9206. spellings.insert( spelling );
  9207. }
  9208. std::string TagInfo::all() const {
  9209. size_t size = 0;
  9210. for (auto const& spelling : spellings) {
  9211. // Add 2 for the brackes
  9212. size += spelling.size() + 2;
  9213. }
  9214. std::string out; out.reserve(size);
  9215. for (auto const& spelling : spellings) {
  9216. out += '[';
  9217. out += spelling;
  9218. out += ']';
  9219. }
  9220. return out;
  9221. }
  9222. std::size_t listTags( Config const& config ) {
  9223. TestSpec const& testSpec = config.testSpec();
  9224. if( config.hasTestFilters() )
  9225. Catch::cout() << "Tags for matching test cases:\n";
  9226. else {
  9227. Catch::cout() << "All available tags:\n";
  9228. }
  9229. std::map<std::string, TagInfo> tagCounts;
  9230. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  9231. for( auto const& testCase : matchedTestCases ) {
  9232. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  9233. std::string lcaseTagName = toLower( tagName );
  9234. auto countIt = tagCounts.find( lcaseTagName );
  9235. if( countIt == tagCounts.end() )
  9236. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  9237. countIt->second.add( tagName );
  9238. }
  9239. }
  9240. for( auto const& tagCount : tagCounts ) {
  9241. ReusableStringStream rss;
  9242. rss << " " << std::setw(2) << tagCount.second.count << " ";
  9243. auto str = rss.str();
  9244. auto wrapper = Column( tagCount.second.all() )
  9245. .initialIndent( 0 )
  9246. .indent( str.size() )
  9247. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  9248. Catch::cout() << str << wrapper << '\n';
  9249. }
  9250. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  9251. return tagCounts.size();
  9252. }
  9253. std::size_t listReporters() {
  9254. Catch::cout() << "Available reporters:\n";
  9255. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  9256. std::size_t maxNameLen = 0;
  9257. for( auto const& factoryKvp : factories )
  9258. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  9259. for( auto const& factoryKvp : factories ) {
  9260. Catch::cout()
  9261. << Column( factoryKvp.first + ":" )
  9262. .indent(2)
  9263. .width( 5+maxNameLen )
  9264. + Column( factoryKvp.second->getDescription() )
  9265. .initialIndent(0)
  9266. .indent(2)
  9267. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  9268. << "\n";
  9269. }
  9270. Catch::cout() << std::endl;
  9271. return factories.size();
  9272. }
  9273. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  9274. Option<std::size_t> listedCount;
  9275. getCurrentMutableContext().setConfig( config );
  9276. if( config->listTests() )
  9277. listedCount = listedCount.valueOr(0) + listTests( *config );
  9278. if( config->listTestNamesOnly() )
  9279. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  9280. if( config->listTags() )
  9281. listedCount = listedCount.valueOr(0) + listTags( *config );
  9282. if( config->listReporters() )
  9283. listedCount = listedCount.valueOr(0) + listReporters();
  9284. return listedCount;
  9285. }
  9286. } // end namespace Catch
  9287. // end catch_list.cpp
  9288. // start catch_matchers.cpp
  9289. namespace Catch {
  9290. namespace Matchers {
  9291. namespace Impl {
  9292. std::string MatcherUntypedBase::toString() const {
  9293. if( m_cachedToString.empty() )
  9294. m_cachedToString = describe();
  9295. return m_cachedToString;
  9296. }
  9297. MatcherUntypedBase::~MatcherUntypedBase() = default;
  9298. } // namespace Impl
  9299. } // namespace Matchers
  9300. using namespace Matchers;
  9301. using Matchers::Impl::MatcherBase;
  9302. } // namespace Catch
  9303. // end catch_matchers.cpp
  9304. // start catch_matchers_exception.cpp
  9305. namespace Catch {
  9306. namespace Matchers {
  9307. namespace Exception {
  9308. bool ExceptionMessageMatcher::match(std::exception const& ex) const {
  9309. return ex.what() == m_message;
  9310. }
  9311. std::string ExceptionMessageMatcher::describe() const {
  9312. return "exception message matches \"" + m_message + "\"";
  9313. }
  9314. }
  9315. Exception::ExceptionMessageMatcher Message(std::string const& message) {
  9316. return Exception::ExceptionMessageMatcher(message);
  9317. }
  9318. // namespace Exception
  9319. } // namespace Matchers
  9320. } // namespace Catch
  9321. // end catch_matchers_exception.cpp
  9322. // start catch_matchers_floating.cpp
  9323. // start catch_polyfills.hpp
  9324. namespace Catch {
  9325. bool isnan(float f);
  9326. bool isnan(double d);
  9327. }
  9328. // end catch_polyfills.hpp
  9329. // start catch_to_string.hpp
  9330. #include <string>
  9331. namespace Catch {
  9332. template <typename T>
  9333. std::string to_string(T const& t) {
  9334. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  9335. return std::to_string(t);
  9336. #else
  9337. ReusableStringStream rss;
  9338. rss << t;
  9339. return rss.str();
  9340. #endif
  9341. }
  9342. } // end namespace Catch
  9343. // end catch_to_string.hpp
  9344. #include <algorithm>
  9345. #include <cmath>
  9346. #include <cstdlib>
  9347. #include <cstdint>
  9348. #include <cstring>
  9349. #include <sstream>
  9350. #include <type_traits>
  9351. #include <iomanip>
  9352. #include <limits>
  9353. namespace Catch {
  9354. namespace {
  9355. int32_t convert(float f) {
  9356. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  9357. int32_t i;
  9358. std::memcpy(&i, &f, sizeof(f));
  9359. return i;
  9360. }
  9361. int64_t convert(double d) {
  9362. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  9363. int64_t i;
  9364. std::memcpy(&i, &d, sizeof(d));
  9365. return i;
  9366. }
  9367. template <typename FP>
  9368. bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
  9369. // Comparison with NaN should always be false.
  9370. // This way we can rule it out before getting into the ugly details
  9371. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  9372. return false;
  9373. }
  9374. auto lc = convert(lhs);
  9375. auto rc = convert(rhs);
  9376. if ((lc < 0) != (rc < 0)) {
  9377. // Potentially we can have +0 and -0
  9378. return lhs == rhs;
  9379. }
  9380. // static cast as a workaround for IBM XLC
  9381. auto ulpDiff = std::abs(static_cast<FP>(lc - rc));
  9382. return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
  9383. }
  9384. #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  9385. float nextafter(float x, float y) {
  9386. return ::nextafterf(x, y);
  9387. }
  9388. double nextafter(double x, double y) {
  9389. return ::nextafter(x, y);
  9390. }
  9391. #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
  9392. template <typename FP>
  9393. FP step(FP start, FP direction, uint64_t steps) {
  9394. for (uint64_t i = 0; i < steps; ++i) {
  9395. #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
  9396. start = Catch::nextafter(start, direction);
  9397. #else
  9398. start = std::nextafter(start, direction);
  9399. #endif
  9400. }
  9401. return start;
  9402. }
  9403. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9404. // But without the subtraction to allow for INFINITY in comparison
  9405. bool marginComparison(double lhs, double rhs, double margin) {
  9406. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  9407. }
  9408. template <typename FloatingPoint>
  9409. void write(std::ostream& out, FloatingPoint num) {
  9410. out << std::scientific
  9411. << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
  9412. << num;
  9413. }
  9414. } // end anonymous namespace
  9415. namespace Matchers {
  9416. namespace Floating {
  9417. enum class FloatingPointKind : uint8_t {
  9418. Float,
  9419. Double
  9420. };
  9421. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  9422. :m_target{ target }, m_margin{ margin } {
  9423. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  9424. << " Margin has to be non-negative.");
  9425. }
  9426. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  9427. // But without the subtraction to allow for INFINITY in comparison
  9428. bool WithinAbsMatcher::match(double const& matchee) const {
  9429. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  9430. }
  9431. std::string WithinAbsMatcher::describe() const {
  9432. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  9433. }
  9434. WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
  9435. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  9436. CATCH_ENFORCE(m_type == FloatingPointKind::Double
  9437. || m_ulps < (std::numeric_limits<uint32_t>::max)(),
  9438. "Provided ULP is impossibly large for a float comparison.");
  9439. }
  9440. #if defined(__clang__)
  9441. #pragma clang diagnostic push
  9442. // Clang <3.5 reports on the default branch in the switch below
  9443. #pragma clang diagnostic ignored "-Wunreachable-code"
  9444. #endif
  9445. bool WithinUlpsMatcher::match(double const& matchee) const {
  9446. switch (m_type) {
  9447. case FloatingPointKind::Float:
  9448. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  9449. case FloatingPointKind::Double:
  9450. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  9451. default:
  9452. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  9453. }
  9454. }
  9455. #if defined(__clang__)
  9456. #pragma clang diagnostic pop
  9457. #endif
  9458. std::string WithinUlpsMatcher::describe() const {
  9459. std::stringstream ret;
  9460. ret << "is within " << m_ulps << " ULPs of ";
  9461. if (m_type == FloatingPointKind::Float) {
  9462. write(ret, static_cast<float>(m_target));
  9463. ret << 'f';
  9464. } else {
  9465. write(ret, m_target);
  9466. }
  9467. ret << " ([";
  9468. if (m_type == FloatingPointKind::Double) {
  9469. write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
  9470. ret << ", ";
  9471. write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
  9472. } else {
  9473. // We have to cast INFINITY to float because of MinGW, see #1782
  9474. write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
  9475. ret << ", ";
  9476. write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
  9477. }
  9478. ret << "])";
  9479. return ret.str();
  9480. }
  9481. WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
  9482. m_target(target),
  9483. m_epsilon(epsilon){
  9484. CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
  9485. CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
  9486. }
  9487. bool WithinRelMatcher::match(double const& matchee) const {
  9488. const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
  9489. return marginComparison(matchee, m_target,
  9490. std::isinf(relMargin)? 0 : relMargin);
  9491. }
  9492. std::string WithinRelMatcher::describe() const {
  9493. Catch::ReusableStringStream sstr;
  9494. sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
  9495. return sstr.str();
  9496. }
  9497. }// namespace Floating
  9498. Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
  9499. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  9500. }
  9501. Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
  9502. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  9503. }
  9504. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  9505. return Floating::WithinAbsMatcher(target, margin);
  9506. }
  9507. Floating::WithinRelMatcher WithinRel(double target, double eps) {
  9508. return Floating::WithinRelMatcher(target, eps);
  9509. }
  9510. Floating::WithinRelMatcher WithinRel(double target) {
  9511. return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
  9512. }
  9513. Floating::WithinRelMatcher WithinRel(float target, float eps) {
  9514. return Floating::WithinRelMatcher(target, eps);
  9515. }
  9516. Floating::WithinRelMatcher WithinRel(float target) {
  9517. return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
  9518. }
  9519. } // namespace Matchers
  9520. } // namespace Catch
  9521. // end catch_matchers_floating.cpp
  9522. // start catch_matchers_generic.cpp
  9523. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  9524. if (desc.empty()) {
  9525. return "matches undescribed predicate";
  9526. } else {
  9527. return "matches predicate: \"" + desc + '"';
  9528. }
  9529. }
  9530. // end catch_matchers_generic.cpp
  9531. // start catch_matchers_string.cpp
  9532. #include <regex>
  9533. namespace Catch {
  9534. namespace Matchers {
  9535. namespace StdString {
  9536. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  9537. : m_caseSensitivity( caseSensitivity ),
  9538. m_str( adjustString( str ) )
  9539. {}
  9540. std::string CasedString::adjustString( std::string const& str ) const {
  9541. return m_caseSensitivity == CaseSensitive::No
  9542. ? toLower( str )
  9543. : str;
  9544. }
  9545. std::string CasedString::caseSensitivitySuffix() const {
  9546. return m_caseSensitivity == CaseSensitive::No
  9547. ? " (case insensitive)"
  9548. : std::string();
  9549. }
  9550. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  9551. : m_comparator( comparator ),
  9552. m_operation( operation ) {
  9553. }
  9554. std::string StringMatcherBase::describe() const {
  9555. std::string description;
  9556. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  9557. m_comparator.caseSensitivitySuffix().size());
  9558. description += m_operation;
  9559. description += ": \"";
  9560. description += m_comparator.m_str;
  9561. description += "\"";
  9562. description += m_comparator.caseSensitivitySuffix();
  9563. return description;
  9564. }
  9565. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  9566. bool EqualsMatcher::match( std::string const& source ) const {
  9567. return m_comparator.adjustString( source ) == m_comparator.m_str;
  9568. }
  9569. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  9570. bool ContainsMatcher::match( std::string const& source ) const {
  9571. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  9572. }
  9573. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  9574. bool StartsWithMatcher::match( std::string const& source ) const {
  9575. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9576. }
  9577. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  9578. bool EndsWithMatcher::match( std::string const& source ) const {
  9579. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  9580. }
  9581. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  9582. bool RegexMatcher::match(std::string const& matchee) const {
  9583. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  9584. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  9585. flags |= std::regex::icase;
  9586. }
  9587. auto reg = std::regex(m_regex, flags);
  9588. return std::regex_match(matchee, reg);
  9589. }
  9590. std::string RegexMatcher::describe() const {
  9591. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  9592. }
  9593. } // namespace StdString
  9594. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9595. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  9596. }
  9597. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9598. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  9599. }
  9600. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9601. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9602. }
  9603. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  9604. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  9605. }
  9606. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  9607. return StdString::RegexMatcher(regex, caseSensitivity);
  9608. }
  9609. } // namespace Matchers
  9610. } // namespace Catch
  9611. // end catch_matchers_string.cpp
  9612. // start catch_message.cpp
  9613. // start catch_uncaught_exceptions.h
  9614. namespace Catch {
  9615. bool uncaught_exceptions();
  9616. } // end namespace Catch
  9617. // end catch_uncaught_exceptions.h
  9618. #include <cassert>
  9619. #include <stack>
  9620. namespace Catch {
  9621. MessageInfo::MessageInfo( StringRef const& _macroName,
  9622. SourceLineInfo const& _lineInfo,
  9623. ResultWas::OfType _type )
  9624. : macroName( _macroName ),
  9625. lineInfo( _lineInfo ),
  9626. type( _type ),
  9627. sequence( ++globalCount )
  9628. {}
  9629. bool MessageInfo::operator==( MessageInfo const& other ) const {
  9630. return sequence == other.sequence;
  9631. }
  9632. bool MessageInfo::operator<( MessageInfo const& other ) const {
  9633. return sequence < other.sequence;
  9634. }
  9635. // This may need protecting if threading support is added
  9636. unsigned int MessageInfo::globalCount = 0;
  9637. ////////////////////////////////////////////////////////////////////////////
  9638. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  9639. SourceLineInfo const& lineInfo,
  9640. ResultWas::OfType type )
  9641. :m_info(macroName, lineInfo, type) {}
  9642. ////////////////////////////////////////////////////////////////////////////
  9643. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  9644. : m_info( builder.m_info ), m_moved()
  9645. {
  9646. m_info.message = builder.m_stream.str();
  9647. getResultCapture().pushScopedMessage( m_info );
  9648. }
  9649. ScopedMessage::ScopedMessage( ScopedMessage&& old )
  9650. : m_info( old.m_info ), m_moved()
  9651. {
  9652. old.m_moved = true;
  9653. }
  9654. ScopedMessage::~ScopedMessage() {
  9655. if ( !uncaught_exceptions() && !m_moved ){
  9656. getResultCapture().popScopedMessage(m_info);
  9657. }
  9658. }
  9659. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  9660. auto trimmed = [&] (size_t start, size_t end) {
  9661. while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
  9662. ++start;
  9663. }
  9664. while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
  9665. --end;
  9666. }
  9667. return names.substr(start, end - start + 1);
  9668. };
  9669. auto skipq = [&] (size_t start, char quote) {
  9670. for (auto i = start + 1; i < names.size() ; ++i) {
  9671. if (names[i] == quote)
  9672. return i;
  9673. if (names[i] == '\\')
  9674. ++i;
  9675. }
  9676. CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
  9677. };
  9678. size_t start = 0;
  9679. std::stack<char> openings;
  9680. for (size_t pos = 0; pos < names.size(); ++pos) {
  9681. char c = names[pos];
  9682. switch (c) {
  9683. case '[':
  9684. case '{':
  9685. case '(':
  9686. // It is basically impossible to disambiguate between
  9687. // comparison and start of template args in this context
  9688. // case '<':
  9689. openings.push(c);
  9690. break;
  9691. case ']':
  9692. case '}':
  9693. case ')':
  9694. // case '>':
  9695. openings.pop();
  9696. break;
  9697. case '"':
  9698. case '\'':
  9699. pos = skipq(pos, c);
  9700. break;
  9701. case ',':
  9702. if (start != pos && openings.empty()) {
  9703. m_messages.emplace_back(macroName, lineInfo, resultType);
  9704. m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
  9705. m_messages.back().message += " := ";
  9706. start = pos;
  9707. }
  9708. }
  9709. }
  9710. assert(openings.empty() && "Mismatched openings");
  9711. m_messages.emplace_back(macroName, lineInfo, resultType);
  9712. m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
  9713. m_messages.back().message += " := ";
  9714. }
  9715. Capturer::~Capturer() {
  9716. if ( !uncaught_exceptions() ){
  9717. assert( m_captured == m_messages.size() );
  9718. for( size_t i = 0; i < m_captured; ++i )
  9719. m_resultCapture.popScopedMessage( m_messages[i] );
  9720. }
  9721. }
  9722. void Capturer::captureValue( size_t index, std::string const& value ) {
  9723. assert( index < m_messages.size() );
  9724. m_messages[index].message += value;
  9725. m_resultCapture.pushScopedMessage( m_messages[index] );
  9726. m_captured++;
  9727. }
  9728. } // end namespace Catch
  9729. // end catch_message.cpp
  9730. // start catch_output_redirect.cpp
  9731. // start catch_output_redirect.h
  9732. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9733. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9734. #include <cstdio>
  9735. #include <iosfwd>
  9736. #include <string>
  9737. namespace Catch {
  9738. class RedirectedStream {
  9739. std::ostream& m_originalStream;
  9740. std::ostream& m_redirectionStream;
  9741. std::streambuf* m_prevBuf;
  9742. public:
  9743. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  9744. ~RedirectedStream();
  9745. };
  9746. class RedirectedStdOut {
  9747. ReusableStringStream m_rss;
  9748. RedirectedStream m_cout;
  9749. public:
  9750. RedirectedStdOut();
  9751. auto str() const -> std::string;
  9752. };
  9753. // StdErr has two constituent streams in C++, std::cerr and std::clog
  9754. // This means that we need to redirect 2 streams into 1 to keep proper
  9755. // order of writes
  9756. class RedirectedStdErr {
  9757. ReusableStringStream m_rss;
  9758. RedirectedStream m_cerr;
  9759. RedirectedStream m_clog;
  9760. public:
  9761. RedirectedStdErr();
  9762. auto str() const -> std::string;
  9763. };
  9764. class RedirectedStreams {
  9765. public:
  9766. RedirectedStreams(RedirectedStreams const&) = delete;
  9767. RedirectedStreams& operator=(RedirectedStreams const&) = delete;
  9768. RedirectedStreams(RedirectedStreams&&) = delete;
  9769. RedirectedStreams& operator=(RedirectedStreams&&) = delete;
  9770. RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
  9771. ~RedirectedStreams();
  9772. private:
  9773. std::string& m_redirectedCout;
  9774. std::string& m_redirectedCerr;
  9775. RedirectedStdOut m_redirectedStdOut;
  9776. RedirectedStdErr m_redirectedStdErr;
  9777. };
  9778. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9779. // Windows's implementation of std::tmpfile is terrible (it tries
  9780. // to create a file inside system folder, thus requiring elevated
  9781. // privileges for the binary), so we have to use tmpnam(_s) and
  9782. // create the file ourselves there.
  9783. class TempFile {
  9784. public:
  9785. TempFile(TempFile const&) = delete;
  9786. TempFile& operator=(TempFile const&) = delete;
  9787. TempFile(TempFile&&) = delete;
  9788. TempFile& operator=(TempFile&&) = delete;
  9789. TempFile();
  9790. ~TempFile();
  9791. std::FILE* getFile();
  9792. std::string getContents();
  9793. private:
  9794. std::FILE* m_file = nullptr;
  9795. #if defined(_MSC_VER)
  9796. char m_buffer[L_tmpnam] = { 0 };
  9797. #endif
  9798. };
  9799. class OutputRedirect {
  9800. public:
  9801. OutputRedirect(OutputRedirect const&) = delete;
  9802. OutputRedirect& operator=(OutputRedirect const&) = delete;
  9803. OutputRedirect(OutputRedirect&&) = delete;
  9804. OutputRedirect& operator=(OutputRedirect&&) = delete;
  9805. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  9806. ~OutputRedirect();
  9807. private:
  9808. int m_originalStdout = -1;
  9809. int m_originalStderr = -1;
  9810. TempFile m_stdoutFile;
  9811. TempFile m_stderrFile;
  9812. std::string& m_stdoutDest;
  9813. std::string& m_stderrDest;
  9814. };
  9815. #endif
  9816. } // end namespace Catch
  9817. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  9818. // end catch_output_redirect.h
  9819. #include <cstdio>
  9820. #include <cstring>
  9821. #include <fstream>
  9822. #include <sstream>
  9823. #include <stdexcept>
  9824. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9825. #if defined(_MSC_VER)
  9826. #include <io.h> //_dup and _dup2
  9827. #define dup _dup
  9828. #define dup2 _dup2
  9829. #define fileno _fileno
  9830. #else
  9831. #include <unistd.h> // dup and dup2
  9832. #endif
  9833. #endif
  9834. namespace Catch {
  9835. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  9836. : m_originalStream( originalStream ),
  9837. m_redirectionStream( redirectionStream ),
  9838. m_prevBuf( m_originalStream.rdbuf() )
  9839. {
  9840. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  9841. }
  9842. RedirectedStream::~RedirectedStream() {
  9843. m_originalStream.rdbuf( m_prevBuf );
  9844. }
  9845. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  9846. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  9847. RedirectedStdErr::RedirectedStdErr()
  9848. : m_cerr( Catch::cerr(), m_rss.get() ),
  9849. m_clog( Catch::clog(), m_rss.get() )
  9850. {}
  9851. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  9852. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  9853. : m_redirectedCout(redirectedCout),
  9854. m_redirectedCerr(redirectedCerr)
  9855. {}
  9856. RedirectedStreams::~RedirectedStreams() {
  9857. m_redirectedCout += m_redirectedStdOut.str();
  9858. m_redirectedCerr += m_redirectedStdErr.str();
  9859. }
  9860. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9861. #if defined(_MSC_VER)
  9862. TempFile::TempFile() {
  9863. if (tmpnam_s(m_buffer)) {
  9864. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  9865. }
  9866. if (fopen_s(&m_file, m_buffer, "w+")) {
  9867. char buffer[100];
  9868. if (strerror_s(buffer, errno)) {
  9869. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  9870. }
  9871. CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
  9872. }
  9873. }
  9874. #else
  9875. TempFile::TempFile() {
  9876. m_file = std::tmpfile();
  9877. if (!m_file) {
  9878. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  9879. }
  9880. }
  9881. #endif
  9882. TempFile::~TempFile() {
  9883. // TBD: What to do about errors here?
  9884. std::fclose(m_file);
  9885. // We manually create the file on Windows only, on Linux
  9886. // it will be autodeleted
  9887. #if defined(_MSC_VER)
  9888. std::remove(m_buffer);
  9889. #endif
  9890. }
  9891. FILE* TempFile::getFile() {
  9892. return m_file;
  9893. }
  9894. std::string TempFile::getContents() {
  9895. std::stringstream sstr;
  9896. char buffer[100] = {};
  9897. std::rewind(m_file);
  9898. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  9899. sstr << buffer;
  9900. }
  9901. return sstr.str();
  9902. }
  9903. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  9904. m_originalStdout(dup(1)),
  9905. m_originalStderr(dup(2)),
  9906. m_stdoutDest(stdout_dest),
  9907. m_stderrDest(stderr_dest) {
  9908. dup2(fileno(m_stdoutFile.getFile()), 1);
  9909. dup2(fileno(m_stderrFile.getFile()), 2);
  9910. }
  9911. OutputRedirect::~OutputRedirect() {
  9912. Catch::cout() << std::flush;
  9913. fflush(stdout);
  9914. // Since we support overriding these streams, we flush cerr
  9915. // even though std::cerr is unbuffered
  9916. Catch::cerr() << std::flush;
  9917. Catch::clog() << std::flush;
  9918. fflush(stderr);
  9919. dup2(m_originalStdout, 1);
  9920. dup2(m_originalStderr, 2);
  9921. m_stdoutDest += m_stdoutFile.getContents();
  9922. m_stderrDest += m_stderrFile.getContents();
  9923. }
  9924. #endif // CATCH_CONFIG_NEW_CAPTURE
  9925. } // namespace Catch
  9926. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  9927. #if defined(_MSC_VER)
  9928. #undef dup
  9929. #undef dup2
  9930. #undef fileno
  9931. #endif
  9932. #endif
  9933. // end catch_output_redirect.cpp
  9934. // start catch_polyfills.cpp
  9935. #include <cmath>
  9936. namespace Catch {
  9937. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  9938. bool isnan(float f) {
  9939. return std::isnan(f);
  9940. }
  9941. bool isnan(double d) {
  9942. return std::isnan(d);
  9943. }
  9944. #else
  9945. // For now we only use this for embarcadero
  9946. bool isnan(float f) {
  9947. return std::_isnan(f);
  9948. }
  9949. bool isnan(double d) {
  9950. return std::_isnan(d);
  9951. }
  9952. #endif
  9953. } // end namespace Catch
  9954. // end catch_polyfills.cpp
  9955. // start catch_random_number_generator.cpp
  9956. namespace Catch {
  9957. namespace {
  9958. #if defined(_MSC_VER)
  9959. #pragma warning(push)
  9960. #pragma warning(disable:4146) // we negate uint32 during the rotate
  9961. #endif
  9962. // Safe rotr implementation thanks to John Regehr
  9963. uint32_t rotate_right(uint32_t val, uint32_t count) {
  9964. const uint32_t mask = 31;
  9965. count &= mask;
  9966. return (val >> count) | (val << (-count & mask));
  9967. }
  9968. #if defined(_MSC_VER)
  9969. #pragma warning(pop)
  9970. #endif
  9971. }
  9972. SimplePcg32::SimplePcg32(result_type seed_) {
  9973. seed(seed_);
  9974. }
  9975. void SimplePcg32::seed(result_type seed_) {
  9976. m_state = 0;
  9977. (*this)();
  9978. m_state += seed_;
  9979. (*this)();
  9980. }
  9981. void SimplePcg32::discard(uint64_t skip) {
  9982. // We could implement this to run in O(log n) steps, but this
  9983. // should suffice for our use case.
  9984. for (uint64_t s = 0; s < skip; ++s) {
  9985. static_cast<void>((*this)());
  9986. }
  9987. }
  9988. SimplePcg32::result_type SimplePcg32::operator()() {
  9989. // prepare the output value
  9990. const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
  9991. const auto output = rotate_right(xorshifted, m_state >> 59u);
  9992. // advance state
  9993. m_state = m_state * 6364136223846793005ULL + s_inc;
  9994. return output;
  9995. }
  9996. bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
  9997. return lhs.m_state == rhs.m_state;
  9998. }
  9999. bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
  10000. return lhs.m_state != rhs.m_state;
  10001. }
  10002. }
  10003. // end catch_random_number_generator.cpp
  10004. // start catch_registry_hub.cpp
  10005. // start catch_test_case_registry_impl.h
  10006. #include <vector>
  10007. #include <set>
  10008. #include <algorithm>
  10009. #include <ios>
  10010. namespace Catch {
  10011. class TestCase;
  10012. struct IConfig;
  10013. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  10014. bool isThrowSafe( TestCase const& testCase, IConfig const& config );
  10015. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  10016. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  10017. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  10018. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  10019. class TestRegistry : public ITestCaseRegistry {
  10020. public:
  10021. virtual ~TestRegistry() = default;
  10022. virtual void registerTest( TestCase const& testCase );
  10023. std::vector<TestCase> const& getAllTests() const override;
  10024. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  10025. private:
  10026. std::vector<TestCase> m_functions;
  10027. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  10028. mutable std::vector<TestCase> m_sortedFunctions;
  10029. std::size_t m_unnamedCount = 0;
  10030. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  10031. };
  10032. ///////////////////////////////////////////////////////////////////////////
  10033. class TestInvokerAsFunction : public ITestInvoker {
  10034. void(*m_testAsFunction)();
  10035. public:
  10036. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  10037. void invoke() const override;
  10038. };
  10039. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  10040. ///////////////////////////////////////////////////////////////////////////
  10041. } // end namespace Catch
  10042. // end catch_test_case_registry_impl.h
  10043. // start catch_reporter_registry.h
  10044. #include <map>
  10045. namespace Catch {
  10046. class ReporterRegistry : public IReporterRegistry {
  10047. public:
  10048. ~ReporterRegistry() override;
  10049. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  10050. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  10051. void registerListener( IReporterFactoryPtr const& factory );
  10052. FactoryMap const& getFactories() const override;
  10053. Listeners const& getListeners() const override;
  10054. private:
  10055. FactoryMap m_factories;
  10056. Listeners m_listeners;
  10057. };
  10058. }
  10059. // end catch_reporter_registry.h
  10060. // start catch_tag_alias_registry.h
  10061. // start catch_tag_alias.h
  10062. #include <string>
  10063. namespace Catch {
  10064. struct TagAlias {
  10065. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  10066. std::string tag;
  10067. SourceLineInfo lineInfo;
  10068. };
  10069. } // end namespace Catch
  10070. // end catch_tag_alias.h
  10071. #include <map>
  10072. namespace Catch {
  10073. class TagAliasRegistry : public ITagAliasRegistry {
  10074. public:
  10075. ~TagAliasRegistry() override;
  10076. TagAlias const* find( std::string const& alias ) const override;
  10077. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  10078. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  10079. private:
  10080. std::map<std::string, TagAlias> m_registry;
  10081. };
  10082. } // end namespace Catch
  10083. // end catch_tag_alias_registry.h
  10084. // start catch_startup_exception_registry.h
  10085. #include <vector>
  10086. #include <exception>
  10087. namespace Catch {
  10088. class StartupExceptionRegistry {
  10089. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10090. public:
  10091. void add(std::exception_ptr const& exception) noexcept;
  10092. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  10093. private:
  10094. std::vector<std::exception_ptr> m_exceptions;
  10095. #endif
  10096. };
  10097. } // end namespace Catch
  10098. // end catch_startup_exception_registry.h
  10099. // start catch_singletons.hpp
  10100. namespace Catch {
  10101. struct ISingleton {
  10102. virtual ~ISingleton();
  10103. };
  10104. void addSingleton( ISingleton* singleton );
  10105. void cleanupSingletons();
  10106. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  10107. class Singleton : SingletonImplT, public ISingleton {
  10108. static auto getInternal() -> Singleton* {
  10109. static Singleton* s_instance = nullptr;
  10110. if( !s_instance ) {
  10111. s_instance = new Singleton;
  10112. addSingleton( s_instance );
  10113. }
  10114. return s_instance;
  10115. }
  10116. public:
  10117. static auto get() -> InterfaceT const& {
  10118. return *getInternal();
  10119. }
  10120. static auto getMutable() -> MutableInterfaceT& {
  10121. return *getInternal();
  10122. }
  10123. };
  10124. } // namespace Catch
  10125. // end catch_singletons.hpp
  10126. namespace Catch {
  10127. namespace {
  10128. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  10129. private NonCopyable {
  10130. public: // IRegistryHub
  10131. RegistryHub() = default;
  10132. IReporterRegistry const& getReporterRegistry() const override {
  10133. return m_reporterRegistry;
  10134. }
  10135. ITestCaseRegistry const& getTestCaseRegistry() const override {
  10136. return m_testCaseRegistry;
  10137. }
  10138. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  10139. return m_exceptionTranslatorRegistry;
  10140. }
  10141. ITagAliasRegistry const& getTagAliasRegistry() const override {
  10142. return m_tagAliasRegistry;
  10143. }
  10144. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  10145. return m_exceptionRegistry;
  10146. }
  10147. public: // IMutableRegistryHub
  10148. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  10149. m_reporterRegistry.registerReporter( name, factory );
  10150. }
  10151. void registerListener( IReporterFactoryPtr const& factory ) override {
  10152. m_reporterRegistry.registerListener( factory );
  10153. }
  10154. void registerTest( TestCase const& testInfo ) override {
  10155. m_testCaseRegistry.registerTest( testInfo );
  10156. }
  10157. void registerTranslator( const IExceptionTranslator* translator ) override {
  10158. m_exceptionTranslatorRegistry.registerTranslator( translator );
  10159. }
  10160. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  10161. m_tagAliasRegistry.add( alias, tag, lineInfo );
  10162. }
  10163. void registerStartupException() noexcept override {
  10164. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10165. m_exceptionRegistry.add(std::current_exception());
  10166. #else
  10167. CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  10168. #endif
  10169. }
  10170. IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
  10171. return m_enumValuesRegistry;
  10172. }
  10173. private:
  10174. TestRegistry m_testCaseRegistry;
  10175. ReporterRegistry m_reporterRegistry;
  10176. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  10177. TagAliasRegistry m_tagAliasRegistry;
  10178. StartupExceptionRegistry m_exceptionRegistry;
  10179. Detail::EnumValuesRegistry m_enumValuesRegistry;
  10180. };
  10181. }
  10182. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  10183. IRegistryHub const& getRegistryHub() {
  10184. return RegistryHubSingleton::get();
  10185. }
  10186. IMutableRegistryHub& getMutableRegistryHub() {
  10187. return RegistryHubSingleton::getMutable();
  10188. }
  10189. void cleanUp() {
  10190. cleanupSingletons();
  10191. cleanUpContext();
  10192. }
  10193. std::string translateActiveException() {
  10194. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  10195. }
  10196. } // end namespace Catch
  10197. // end catch_registry_hub.cpp
  10198. // start catch_reporter_registry.cpp
  10199. namespace Catch {
  10200. ReporterRegistry::~ReporterRegistry() = default;
  10201. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  10202. auto it = m_factories.find( name );
  10203. if( it == m_factories.end() )
  10204. return nullptr;
  10205. return it->second->create( ReporterConfig( config ) );
  10206. }
  10207. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  10208. m_factories.emplace(name, factory);
  10209. }
  10210. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  10211. m_listeners.push_back( factory );
  10212. }
  10213. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  10214. return m_factories;
  10215. }
  10216. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  10217. return m_listeners;
  10218. }
  10219. }
  10220. // end catch_reporter_registry.cpp
  10221. // start catch_result_type.cpp
  10222. namespace Catch {
  10223. bool isOk( ResultWas::OfType resultType ) {
  10224. return ( resultType & ResultWas::FailureBit ) == 0;
  10225. }
  10226. bool isJustInfo( int flags ) {
  10227. return flags == ResultWas::Info;
  10228. }
  10229. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  10230. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  10231. }
  10232. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  10233. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  10234. } // end namespace Catch
  10235. // end catch_result_type.cpp
  10236. // start catch_run_context.cpp
  10237. #include <cassert>
  10238. #include <algorithm>
  10239. #include <sstream>
  10240. namespace Catch {
  10241. namespace Generators {
  10242. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  10243. GeneratorBasePtr m_generator;
  10244. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  10245. : TrackerBase( nameAndLocation, ctx, parent )
  10246. {}
  10247. ~GeneratorTracker();
  10248. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  10249. std::shared_ptr<GeneratorTracker> tracker;
  10250. ITracker& currentTracker = ctx.currentTracker();
  10251. // Under specific circumstances, the generator we want
  10252. // to acquire is also the current tracker. If this is
  10253. // the case, we have to avoid looking through current
  10254. // tracker's children, and instead return the current
  10255. // tracker.
  10256. // A case where this check is important is e.g.
  10257. // for (int i = 0; i < 5; ++i) {
  10258. // int n = GENERATE(1, 2);
  10259. // }
  10260. //
  10261. // without it, the code above creates 5 nested generators.
  10262. if (currentTracker.nameAndLocation() == nameAndLocation) {
  10263. auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
  10264. assert(thisTracker);
  10265. assert(thisTracker->isGeneratorTracker());
  10266. tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
  10267. } else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  10268. assert( childTracker );
  10269. assert( childTracker->isGeneratorTracker() );
  10270. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  10271. } else {
  10272. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  10273. currentTracker.addChild( tracker );
  10274. }
  10275. if( !tracker->isComplete() ) {
  10276. tracker->open();
  10277. }
  10278. return *tracker;
  10279. }
  10280. // TrackerBase interface
  10281. bool isGeneratorTracker() const override { return true; }
  10282. auto hasGenerator() const -> bool override {
  10283. return !!m_generator;
  10284. }
  10285. void close() override {
  10286. TrackerBase::close();
  10287. // If a generator has a child (it is followed by a section)
  10288. // and none of its children have started, then we must wait
  10289. // until later to start consuming its values.
  10290. // This catches cases where `GENERATE` is placed between two
  10291. // `SECTION`s.
  10292. // **The check for m_children.empty cannot be removed**.
  10293. // doing so would break `GENERATE` _not_ followed by `SECTION`s.
  10294. const bool should_wait_for_child = [&]() {
  10295. // No children -> nobody to wait for
  10296. if ( m_children.empty() ) {
  10297. return false;
  10298. }
  10299. // If at least one child started executing, don't wait
  10300. if ( std::find_if(
  10301. m_children.begin(),
  10302. m_children.end(),
  10303. []( TestCaseTracking::ITrackerPtr tracker ) {
  10304. return tracker->hasStarted();
  10305. } ) != m_children.end() ) {
  10306. return false;
  10307. }
  10308. // No children have started. We need to check if they _can_
  10309. // start, and thus we should wait for them, or they cannot
  10310. // start (due to filters), and we shouldn't wait for them
  10311. auto* parent = m_parent;
  10312. // This is safe: there is always at least one section
  10313. // tracker in a test case tracking tree
  10314. while ( !parent->isSectionTracker() ) {
  10315. parent = &( parent->parent() );
  10316. }
  10317. assert( parent &&
  10318. "Missing root (test case) level section" );
  10319. auto const& parentSection =
  10320. static_cast<SectionTracker&>( *parent );
  10321. auto const& filters = parentSection.getFilters();
  10322. // No filters -> no restrictions on running sections
  10323. if ( filters.empty() ) {
  10324. return true;
  10325. }
  10326. for ( auto const& child : m_children ) {
  10327. if ( child->isSectionTracker() &&
  10328. std::find( filters.begin(),
  10329. filters.end(),
  10330. static_cast<SectionTracker&>( *child )
  10331. .trimmedName() ) !=
  10332. filters.end() ) {
  10333. return true;
  10334. }
  10335. }
  10336. return false;
  10337. }();
  10338. // This check is a bit tricky, because m_generator->next()
  10339. // has a side-effect, where it consumes generator's current
  10340. // value, but we do not want to invoke the side-effect if
  10341. // this generator is still waiting for any child to start.
  10342. if ( should_wait_for_child ||
  10343. ( m_runState == CompletedSuccessfully &&
  10344. m_generator->next() ) ) {
  10345. m_children.clear();
  10346. m_runState = Executing;
  10347. }
  10348. }
  10349. // IGeneratorTracker interface
  10350. auto getGenerator() const -> GeneratorBasePtr const& override {
  10351. return m_generator;
  10352. }
  10353. void setGenerator( GeneratorBasePtr&& generator ) override {
  10354. m_generator = std::move( generator );
  10355. }
  10356. };
  10357. GeneratorTracker::~GeneratorTracker() {}
  10358. }
  10359. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  10360. : m_runInfo(_config->name()),
  10361. m_context(getCurrentMutableContext()),
  10362. m_config(_config),
  10363. m_reporter(std::move(reporter)),
  10364. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  10365. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  10366. {
  10367. m_context.setRunner(this);
  10368. m_context.setConfig(m_config);
  10369. m_context.setResultCapture(this);
  10370. m_reporter->testRunStarting(m_runInfo);
  10371. }
  10372. RunContext::~RunContext() {
  10373. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  10374. }
  10375. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  10376. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  10377. }
  10378. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  10379. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  10380. }
  10381. Totals RunContext::runTest(TestCase const& testCase) {
  10382. Totals prevTotals = m_totals;
  10383. std::string redirectedCout;
  10384. std::string redirectedCerr;
  10385. auto const& testInfo = testCase.getTestCaseInfo();
  10386. m_reporter->testCaseStarting(testInfo);
  10387. m_activeTestCase = &testCase;
  10388. ITracker& rootTracker = m_trackerContext.startRun();
  10389. assert(rootTracker.isSectionTracker());
  10390. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  10391. do {
  10392. m_trackerContext.startCycle();
  10393. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  10394. runCurrentTest(redirectedCout, redirectedCerr);
  10395. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  10396. Totals deltaTotals = m_totals.delta(prevTotals);
  10397. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  10398. deltaTotals.assertions.failed++;
  10399. deltaTotals.testCases.passed--;
  10400. deltaTotals.testCases.failed++;
  10401. }
  10402. m_totals.testCases += deltaTotals.testCases;
  10403. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10404. deltaTotals,
  10405. redirectedCout,
  10406. redirectedCerr,
  10407. aborting()));
  10408. m_activeTestCase = nullptr;
  10409. m_testCaseTracker = nullptr;
  10410. return deltaTotals;
  10411. }
  10412. IConfigPtr RunContext::config() const {
  10413. return m_config;
  10414. }
  10415. IStreamingReporter& RunContext::reporter() const {
  10416. return *m_reporter;
  10417. }
  10418. void RunContext::assertionEnded(AssertionResult const & result) {
  10419. if (result.getResultType() == ResultWas::Ok) {
  10420. m_totals.assertions.passed++;
  10421. m_lastAssertionPassed = true;
  10422. } else if (!result.isOk()) {
  10423. m_lastAssertionPassed = false;
  10424. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  10425. m_totals.assertions.failedButOk++;
  10426. else
  10427. m_totals.assertions.failed++;
  10428. }
  10429. else {
  10430. m_lastAssertionPassed = true;
  10431. }
  10432. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  10433. // and should be let to clear themselves out.
  10434. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  10435. if (result.getResultType() != ResultWas::Warning)
  10436. m_messageScopes.clear();
  10437. // Reset working state
  10438. resetAssertionInfo();
  10439. m_lastResult = result;
  10440. }
  10441. void RunContext::resetAssertionInfo() {
  10442. m_lastAssertionInfo.macroName = StringRef();
  10443. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  10444. }
  10445. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  10446. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  10447. if (!sectionTracker.isOpen())
  10448. return false;
  10449. m_activeSections.push_back(&sectionTracker);
  10450. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  10451. m_reporter->sectionStarting(sectionInfo);
  10452. assertions = m_totals.assertions;
  10453. return true;
  10454. }
  10455. auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  10456. using namespace Generators;
  10457. GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
  10458. TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
  10459. m_lastAssertionInfo.lineInfo = lineInfo;
  10460. return tracker;
  10461. }
  10462. bool RunContext::testForMissingAssertions(Counts& assertions) {
  10463. if (assertions.total() != 0)
  10464. return false;
  10465. if (!m_config->warnAboutMissingAssertions())
  10466. return false;
  10467. if (m_trackerContext.currentTracker().hasChildren())
  10468. return false;
  10469. m_totals.assertions.failed++;
  10470. assertions.failed++;
  10471. return true;
  10472. }
  10473. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  10474. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  10475. bool missingAssertions = testForMissingAssertions(assertions);
  10476. if (!m_activeSections.empty()) {
  10477. m_activeSections.back()->close();
  10478. m_activeSections.pop_back();
  10479. }
  10480. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  10481. m_messages.clear();
  10482. m_messageScopes.clear();
  10483. }
  10484. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  10485. if (m_unfinishedSections.empty())
  10486. m_activeSections.back()->fail();
  10487. else
  10488. m_activeSections.back()->close();
  10489. m_activeSections.pop_back();
  10490. m_unfinishedSections.push_back(endInfo);
  10491. }
  10492. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  10493. void RunContext::benchmarkPreparing(std::string const& name) {
  10494. m_reporter->benchmarkPreparing(name);
  10495. }
  10496. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  10497. m_reporter->benchmarkStarting( info );
  10498. }
  10499. void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
  10500. m_reporter->benchmarkEnded( stats );
  10501. }
  10502. void RunContext::benchmarkFailed(std::string const & error) {
  10503. m_reporter->benchmarkFailed(error);
  10504. }
  10505. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  10506. void RunContext::pushScopedMessage(MessageInfo const & message) {
  10507. m_messages.push_back(message);
  10508. }
  10509. void RunContext::popScopedMessage(MessageInfo const & message) {
  10510. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  10511. }
  10512. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  10513. m_messageScopes.emplace_back( builder );
  10514. }
  10515. std::string RunContext::getCurrentTestName() const {
  10516. return m_activeTestCase
  10517. ? m_activeTestCase->getTestCaseInfo().name
  10518. : std::string();
  10519. }
  10520. const AssertionResult * RunContext::getLastResult() const {
  10521. return &(*m_lastResult);
  10522. }
  10523. void RunContext::exceptionEarlyReported() {
  10524. m_shouldReportUnexpected = false;
  10525. }
  10526. void RunContext::handleFatalErrorCondition( StringRef message ) {
  10527. // First notify reporter that bad things happened
  10528. m_reporter->fatalErrorEncountered(message);
  10529. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  10530. // Instead, fake a result data.
  10531. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  10532. tempResult.message = static_cast<std::string>(message);
  10533. AssertionResult result(m_lastAssertionInfo, tempResult);
  10534. assertionEnded(result);
  10535. handleUnfinishedSections();
  10536. // Recreate section for test case (as we will lose the one that was in scope)
  10537. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10538. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10539. Counts assertions;
  10540. assertions.failed = 1;
  10541. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  10542. m_reporter->sectionEnded(testCaseSectionStats);
  10543. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  10544. Totals deltaTotals;
  10545. deltaTotals.testCases.failed = 1;
  10546. deltaTotals.assertions.failed = 1;
  10547. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  10548. deltaTotals,
  10549. std::string(),
  10550. std::string(),
  10551. false));
  10552. m_totals.testCases.failed++;
  10553. testGroupEnded(std::string(), m_totals, 1, 1);
  10554. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  10555. }
  10556. bool RunContext::lastAssertionPassed() {
  10557. return m_lastAssertionPassed;
  10558. }
  10559. void RunContext::assertionPassed() {
  10560. m_lastAssertionPassed = true;
  10561. ++m_totals.assertions.passed;
  10562. resetAssertionInfo();
  10563. m_messageScopes.clear();
  10564. }
  10565. bool RunContext::aborting() const {
  10566. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  10567. }
  10568. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  10569. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  10570. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  10571. m_reporter->sectionStarting(testCaseSection);
  10572. Counts prevAssertions = m_totals.assertions;
  10573. double duration = 0;
  10574. m_shouldReportUnexpected = true;
  10575. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  10576. seedRng(*m_config);
  10577. Timer timer;
  10578. CATCH_TRY {
  10579. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  10580. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  10581. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  10582. timer.start();
  10583. invokeActiveTestCase();
  10584. #else
  10585. OutputRedirect r(redirectedCout, redirectedCerr);
  10586. timer.start();
  10587. invokeActiveTestCase();
  10588. #endif
  10589. } else {
  10590. timer.start();
  10591. invokeActiveTestCase();
  10592. }
  10593. duration = timer.getElapsedSeconds();
  10594. } CATCH_CATCH_ANON (TestFailureException&) {
  10595. // This just means the test was aborted due to failure
  10596. } CATCH_CATCH_ALL {
  10597. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  10598. // are reported without translation at the point of origin.
  10599. if( m_shouldReportUnexpected ) {
  10600. AssertionReaction dummyReaction;
  10601. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  10602. }
  10603. }
  10604. Counts assertions = m_totals.assertions - prevAssertions;
  10605. bool missingAssertions = testForMissingAssertions(assertions);
  10606. m_testCaseTracker->close();
  10607. handleUnfinishedSections();
  10608. m_messages.clear();
  10609. m_messageScopes.clear();
  10610. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  10611. m_reporter->sectionEnded(testCaseSectionStats);
  10612. }
  10613. void RunContext::invokeActiveTestCase() {
  10614. FatalConditionHandlerGuard _(&m_fatalConditionhandler);
  10615. m_activeTestCase->invoke();
  10616. }
  10617. void RunContext::handleUnfinishedSections() {
  10618. // If sections ended prematurely due to an exception we stored their
  10619. // infos here so we can tear them down outside the unwind process.
  10620. for (auto it = m_unfinishedSections.rbegin(),
  10621. itEnd = m_unfinishedSections.rend();
  10622. it != itEnd;
  10623. ++it)
  10624. sectionEnded(*it);
  10625. m_unfinishedSections.clear();
  10626. }
  10627. void RunContext::handleExpr(
  10628. AssertionInfo const& info,
  10629. ITransientExpression const& expr,
  10630. AssertionReaction& reaction
  10631. ) {
  10632. m_reporter->assertionStarting( info );
  10633. bool negated = isFalseTest( info.resultDisposition );
  10634. bool result = expr.getResult() != negated;
  10635. if( result ) {
  10636. if (!m_includeSuccessfulResults) {
  10637. assertionPassed();
  10638. }
  10639. else {
  10640. reportExpr(info, ResultWas::Ok, &expr, negated);
  10641. }
  10642. }
  10643. else {
  10644. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  10645. populateReaction( reaction );
  10646. }
  10647. }
  10648. void RunContext::reportExpr(
  10649. AssertionInfo const &info,
  10650. ResultWas::OfType resultType,
  10651. ITransientExpression const *expr,
  10652. bool negated ) {
  10653. m_lastAssertionInfo = info;
  10654. AssertionResultData data( resultType, LazyExpression( negated ) );
  10655. AssertionResult assertionResult{ info, data };
  10656. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  10657. assertionEnded( assertionResult );
  10658. }
  10659. void RunContext::handleMessage(
  10660. AssertionInfo const& info,
  10661. ResultWas::OfType resultType,
  10662. StringRef const& message,
  10663. AssertionReaction& reaction
  10664. ) {
  10665. m_reporter->assertionStarting( info );
  10666. m_lastAssertionInfo = info;
  10667. AssertionResultData data( resultType, LazyExpression( false ) );
  10668. data.message = static_cast<std::string>(message);
  10669. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  10670. assertionEnded( assertionResult );
  10671. if( !assertionResult.isOk() )
  10672. populateReaction( reaction );
  10673. }
  10674. void RunContext::handleUnexpectedExceptionNotThrown(
  10675. AssertionInfo const& info,
  10676. AssertionReaction& reaction
  10677. ) {
  10678. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  10679. }
  10680. void RunContext::handleUnexpectedInflightException(
  10681. AssertionInfo const& info,
  10682. std::string const& message,
  10683. AssertionReaction& reaction
  10684. ) {
  10685. m_lastAssertionInfo = info;
  10686. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10687. data.message = message;
  10688. AssertionResult assertionResult{ info, data };
  10689. assertionEnded( assertionResult );
  10690. populateReaction( reaction );
  10691. }
  10692. void RunContext::populateReaction( AssertionReaction& reaction ) {
  10693. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  10694. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  10695. }
  10696. void RunContext::handleIncomplete(
  10697. AssertionInfo const& info
  10698. ) {
  10699. m_lastAssertionInfo = info;
  10700. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  10701. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  10702. AssertionResult assertionResult{ info, data };
  10703. assertionEnded( assertionResult );
  10704. }
  10705. void RunContext::handleNonExpr(
  10706. AssertionInfo const &info,
  10707. ResultWas::OfType resultType,
  10708. AssertionReaction &reaction
  10709. ) {
  10710. m_lastAssertionInfo = info;
  10711. AssertionResultData data( resultType, LazyExpression( false ) );
  10712. AssertionResult assertionResult{ info, data };
  10713. assertionEnded( assertionResult );
  10714. if( !assertionResult.isOk() )
  10715. populateReaction( reaction );
  10716. }
  10717. IResultCapture& getResultCapture() {
  10718. if (auto* capture = getCurrentContext().getResultCapture())
  10719. return *capture;
  10720. else
  10721. CATCH_INTERNAL_ERROR("No result capture instance");
  10722. }
  10723. void seedRng(IConfig const& config) {
  10724. if (config.rngSeed() != 0) {
  10725. std::srand(config.rngSeed());
  10726. rng().seed(config.rngSeed());
  10727. }
  10728. }
  10729. unsigned int rngSeed() {
  10730. return getCurrentContext().getConfig()->rngSeed();
  10731. }
  10732. }
  10733. // end catch_run_context.cpp
  10734. // start catch_section.cpp
  10735. namespace Catch {
  10736. Section::Section( SectionInfo const& info )
  10737. : m_info( info ),
  10738. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  10739. {
  10740. m_timer.start();
  10741. }
  10742. Section::~Section() {
  10743. if( m_sectionIncluded ) {
  10744. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  10745. if( uncaught_exceptions() )
  10746. getResultCapture().sectionEndedEarly( endInfo );
  10747. else
  10748. getResultCapture().sectionEnded( endInfo );
  10749. }
  10750. }
  10751. // This indicates whether the section should be executed or not
  10752. Section::operator bool() const {
  10753. return m_sectionIncluded;
  10754. }
  10755. } // end namespace Catch
  10756. // end catch_section.cpp
  10757. // start catch_section_info.cpp
  10758. namespace Catch {
  10759. SectionInfo::SectionInfo
  10760. ( SourceLineInfo const& _lineInfo,
  10761. std::string const& _name )
  10762. : name( _name ),
  10763. lineInfo( _lineInfo )
  10764. {}
  10765. } // end namespace Catch
  10766. // end catch_section_info.cpp
  10767. // start catch_session.cpp
  10768. // start catch_session.h
  10769. #include <memory>
  10770. namespace Catch {
  10771. class Session : NonCopyable {
  10772. public:
  10773. Session();
  10774. ~Session() override;
  10775. void showHelp() const;
  10776. void libIdentify();
  10777. int applyCommandLine( int argc, char const * const * argv );
  10778. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10779. int applyCommandLine( int argc, wchar_t const * const * argv );
  10780. #endif
  10781. void useConfigData( ConfigData const& configData );
  10782. template<typename CharT>
  10783. int run(int argc, CharT const * const argv[]) {
  10784. if (m_startupExceptions)
  10785. return 1;
  10786. int returnCode = applyCommandLine(argc, argv);
  10787. if (returnCode == 0)
  10788. returnCode = run();
  10789. return returnCode;
  10790. }
  10791. int run();
  10792. clara::Parser const& cli() const;
  10793. void cli( clara::Parser const& newParser );
  10794. ConfigData& configData();
  10795. Config& config();
  10796. private:
  10797. int runInternal();
  10798. clara::Parser m_cli;
  10799. ConfigData m_configData;
  10800. std::shared_ptr<Config> m_config;
  10801. bool m_startupExceptions = false;
  10802. };
  10803. } // end namespace Catch
  10804. // end catch_session.h
  10805. // start catch_version.h
  10806. #include <iosfwd>
  10807. namespace Catch {
  10808. // Versioning information
  10809. struct Version {
  10810. Version( Version const& ) = delete;
  10811. Version& operator=( Version const& ) = delete;
  10812. Version( unsigned int _majorVersion,
  10813. unsigned int _minorVersion,
  10814. unsigned int _patchNumber,
  10815. char const * const _branchName,
  10816. unsigned int _buildNumber );
  10817. unsigned int const majorVersion;
  10818. unsigned int const minorVersion;
  10819. unsigned int const patchNumber;
  10820. // buildNumber is only used if branchName is not null
  10821. char const * const branchName;
  10822. unsigned int const buildNumber;
  10823. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  10824. };
  10825. Version const& libraryVersion();
  10826. }
  10827. // end catch_version.h
  10828. #include <cstdlib>
  10829. #include <iomanip>
  10830. #include <set>
  10831. #include <iterator>
  10832. namespace Catch {
  10833. namespace {
  10834. const int MaxExitCode = 255;
  10835. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  10836. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  10837. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  10838. return reporter;
  10839. }
  10840. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  10841. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  10842. return createReporter(config->getReporterName(), config);
  10843. }
  10844. // On older platforms, returning std::unique_ptr<ListeningReporter>
  10845. // when the return type is std::unique_ptr<IStreamingReporter>
  10846. // doesn't compile without a std::move call. However, this causes
  10847. // a warning on newer platforms. Thus, we have to work around
  10848. // it a bit and downcast the pointer manually.
  10849. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  10850. auto& multi = static_cast<ListeningReporter&>(*ret);
  10851. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  10852. for (auto const& listener : listeners) {
  10853. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  10854. }
  10855. multi.addReporter(createReporter(config->getReporterName(), config));
  10856. return ret;
  10857. }
  10858. class TestGroup {
  10859. public:
  10860. explicit TestGroup(std::shared_ptr<Config> const& config)
  10861. : m_config{config}
  10862. , m_context{config, makeReporter(config)}
  10863. {
  10864. auto const& allTestCases = getAllTestCasesSorted(*m_config);
  10865. m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
  10866. auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
  10867. if (m_matches.empty() && invalidArgs.empty()) {
  10868. for (auto const& test : allTestCases)
  10869. if (!test.isHidden())
  10870. m_tests.emplace(&test);
  10871. } else {
  10872. for (auto const& match : m_matches)
  10873. m_tests.insert(match.tests.begin(), match.tests.end());
  10874. }
  10875. }
  10876. Totals execute() {
  10877. auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
  10878. Totals totals;
  10879. m_context.testGroupStarting(m_config->name(), 1, 1);
  10880. for (auto const& testCase : m_tests) {
  10881. if (!m_context.aborting())
  10882. totals += m_context.runTest(*testCase);
  10883. else
  10884. m_context.reporter().skipTest(*testCase);
  10885. }
  10886. for (auto const& match : m_matches) {
  10887. if (match.tests.empty()) {
  10888. m_context.reporter().noMatchingTestCases(match.name);
  10889. totals.error = -1;
  10890. }
  10891. }
  10892. if (!invalidArgs.empty()) {
  10893. for (auto const& invalidArg: invalidArgs)
  10894. m_context.reporter().reportInvalidArguments(invalidArg);
  10895. }
  10896. m_context.testGroupEnded(m_config->name(), totals, 1, 1);
  10897. return totals;
  10898. }
  10899. private:
  10900. using Tests = std::set<TestCase const*>;
  10901. std::shared_ptr<Config> m_config;
  10902. RunContext m_context;
  10903. Tests m_tests;
  10904. TestSpec::Matches m_matches;
  10905. };
  10906. void applyFilenamesAsTags(Catch::IConfig const& config) {
  10907. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  10908. for (auto& testCase : tests) {
  10909. auto tags = testCase.tags;
  10910. std::string filename = testCase.lineInfo.file;
  10911. auto lastSlash = filename.find_last_of("\\/");
  10912. if (lastSlash != std::string::npos) {
  10913. filename.erase(0, lastSlash);
  10914. filename[0] = '#';
  10915. }
  10916. else
  10917. {
  10918. filename.insert(0, "#");
  10919. }
  10920. auto lastDot = filename.find_last_of('.');
  10921. if (lastDot != std::string::npos) {
  10922. filename.erase(lastDot);
  10923. }
  10924. tags.push_back(std::move(filename));
  10925. setTags(testCase, tags);
  10926. }
  10927. }
  10928. } // anon namespace
  10929. Session::Session() {
  10930. static bool alreadyInstantiated = false;
  10931. if( alreadyInstantiated ) {
  10932. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  10933. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  10934. }
  10935. // There cannot be exceptions at startup in no-exception mode.
  10936. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  10937. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  10938. if ( !exceptions.empty() ) {
  10939. config();
  10940. getCurrentMutableContext().setConfig(m_config);
  10941. m_startupExceptions = true;
  10942. Colour colourGuard( Colour::Red );
  10943. Catch::cerr() << "Errors occurred during startup!" << '\n';
  10944. // iterate over all exceptions and notify user
  10945. for ( const auto& ex_ptr : exceptions ) {
  10946. try {
  10947. std::rethrow_exception(ex_ptr);
  10948. } catch ( std::exception const& ex ) {
  10949. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  10950. }
  10951. }
  10952. }
  10953. #endif
  10954. alreadyInstantiated = true;
  10955. m_cli = makeCommandLineParser( m_configData );
  10956. }
  10957. Session::~Session() {
  10958. Catch::cleanUp();
  10959. }
  10960. void Session::showHelp() const {
  10961. Catch::cout()
  10962. << "\nCatch v" << libraryVersion() << "\n"
  10963. << m_cli << std::endl
  10964. << "For more detailed usage please see the project docs\n" << std::endl;
  10965. }
  10966. void Session::libIdentify() {
  10967. Catch::cout()
  10968. << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
  10969. << std::left << std::setw(16) << "category: " << "testframework\n"
  10970. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  10971. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  10972. }
  10973. int Session::applyCommandLine( int argc, char const * const * argv ) {
  10974. if( m_startupExceptions )
  10975. return 1;
  10976. auto result = m_cli.parse( clara::Args( argc, argv ) );
  10977. if( !result ) {
  10978. config();
  10979. getCurrentMutableContext().setConfig(m_config);
  10980. Catch::cerr()
  10981. << Colour( Colour::Red )
  10982. << "\nError(s) in input:\n"
  10983. << Column( result.errorMessage() ).indent( 2 )
  10984. << "\n\n";
  10985. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  10986. return MaxExitCode;
  10987. }
  10988. if( m_configData.showHelp )
  10989. showHelp();
  10990. if( m_configData.libIdentify )
  10991. libIdentify();
  10992. m_config.reset();
  10993. return 0;
  10994. }
  10995. #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
  10996. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  10997. char **utf8Argv = new char *[ argc ];
  10998. for ( int i = 0; i < argc; ++i ) {
  10999. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr );
  11000. utf8Argv[ i ] = new char[ bufSize ];
  11001. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr );
  11002. }
  11003. int returnCode = applyCommandLine( argc, utf8Argv );
  11004. for ( int i = 0; i < argc; ++i )
  11005. delete [] utf8Argv[ i ];
  11006. delete [] utf8Argv;
  11007. return returnCode;
  11008. }
  11009. #endif
  11010. void Session::useConfigData( ConfigData const& configData ) {
  11011. m_configData = configData;
  11012. m_config.reset();
  11013. }
  11014. int Session::run() {
  11015. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  11016. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  11017. static_cast<void>(std::getchar());
  11018. }
  11019. int exitCode = runInternal();
  11020. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  11021. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  11022. static_cast<void>(std::getchar());
  11023. }
  11024. return exitCode;
  11025. }
  11026. clara::Parser const& Session::cli() const {
  11027. return m_cli;
  11028. }
  11029. void Session::cli( clara::Parser const& newParser ) {
  11030. m_cli = newParser;
  11031. }
  11032. ConfigData& Session::configData() {
  11033. return m_configData;
  11034. }
  11035. Config& Session::config() {
  11036. if( !m_config )
  11037. m_config = std::make_shared<Config>( m_configData );
  11038. return *m_config;
  11039. }
  11040. int Session::runInternal() {
  11041. if( m_startupExceptions )
  11042. return 1;
  11043. if (m_configData.showHelp || m_configData.libIdentify) {
  11044. return 0;
  11045. }
  11046. CATCH_TRY {
  11047. config(); // Force config to be constructed
  11048. seedRng( *m_config );
  11049. if( m_configData.filenamesAsTags )
  11050. applyFilenamesAsTags( *m_config );
  11051. // Handle list request
  11052. if( Option<std::size_t> listed = list( m_config ) )
  11053. return (std::min) (MaxExitCode, static_cast<int>(*listed));
  11054. TestGroup tests { m_config };
  11055. auto const totals = tests.execute();
  11056. if( m_config->warnAboutNoTests() && totals.error == -1 )
  11057. return 2;
  11058. // Note that on unices only the lower 8 bits are usually used, clamping
  11059. // the return value to 255 prevents false negative when some multiple
  11060. // of 256 tests has failed
  11061. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  11062. }
  11063. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  11064. catch( std::exception& ex ) {
  11065. Catch::cerr() << ex.what() << std::endl;
  11066. return MaxExitCode;
  11067. }
  11068. #endif
  11069. }
  11070. } // end namespace Catch
  11071. // end catch_session.cpp
  11072. // start catch_singletons.cpp
  11073. #include <vector>
  11074. namespace Catch {
  11075. namespace {
  11076. static auto getSingletons() -> std::vector<ISingleton*>*& {
  11077. static std::vector<ISingleton*>* g_singletons = nullptr;
  11078. if( !g_singletons )
  11079. g_singletons = new std::vector<ISingleton*>();
  11080. return g_singletons;
  11081. }
  11082. }
  11083. ISingleton::~ISingleton() {}
  11084. void addSingleton(ISingleton* singleton ) {
  11085. getSingletons()->push_back( singleton );
  11086. }
  11087. void cleanupSingletons() {
  11088. auto& singletons = getSingletons();
  11089. for( auto singleton : *singletons )
  11090. delete singleton;
  11091. delete singletons;
  11092. singletons = nullptr;
  11093. }
  11094. } // namespace Catch
  11095. // end catch_singletons.cpp
  11096. // start catch_startup_exception_registry.cpp
  11097. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  11098. namespace Catch {
  11099. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  11100. CATCH_TRY {
  11101. m_exceptions.push_back(exception);
  11102. } CATCH_CATCH_ALL {
  11103. // If we run out of memory during start-up there's really not a lot more we can do about it
  11104. std::terminate();
  11105. }
  11106. }
  11107. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  11108. return m_exceptions;
  11109. }
  11110. } // end namespace Catch
  11111. #endif
  11112. // end catch_startup_exception_registry.cpp
  11113. // start catch_stream.cpp
  11114. #include <cstdio>
  11115. #include <iostream>
  11116. #include <fstream>
  11117. #include <sstream>
  11118. #include <vector>
  11119. #include <memory>
  11120. namespace Catch {
  11121. Catch::IStream::~IStream() = default;
  11122. namespace Detail { namespace {
  11123. template<typename WriterF, std::size_t bufferSize=256>
  11124. class StreamBufImpl : public std::streambuf {
  11125. char data[bufferSize];
  11126. WriterF m_writer;
  11127. public:
  11128. StreamBufImpl() {
  11129. setp( data, data + sizeof(data) );
  11130. }
  11131. ~StreamBufImpl() noexcept {
  11132. StreamBufImpl::sync();
  11133. }
  11134. private:
  11135. int overflow( int c ) override {
  11136. sync();
  11137. if( c != EOF ) {
  11138. if( pbase() == epptr() )
  11139. m_writer( std::string( 1, static_cast<char>( c ) ) );
  11140. else
  11141. sputc( static_cast<char>( c ) );
  11142. }
  11143. return 0;
  11144. }
  11145. int sync() override {
  11146. if( pbase() != pptr() ) {
  11147. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  11148. setp( pbase(), epptr() );
  11149. }
  11150. return 0;
  11151. }
  11152. };
  11153. ///////////////////////////////////////////////////////////////////////////
  11154. struct OutputDebugWriter {
  11155. void operator()( std::string const&str ) {
  11156. writeToDebugConsole( str );
  11157. }
  11158. };
  11159. ///////////////////////////////////////////////////////////////////////////
  11160. class FileStream : public IStream {
  11161. mutable std::ofstream m_ofs;
  11162. public:
  11163. FileStream( StringRef filename ) {
  11164. m_ofs.open( filename.c_str() );
  11165. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  11166. }
  11167. ~FileStream() override = default;
  11168. public: // IStream
  11169. std::ostream& stream() const override {
  11170. return m_ofs;
  11171. }
  11172. };
  11173. ///////////////////////////////////////////////////////////////////////////
  11174. class CoutStream : public IStream {
  11175. mutable std::ostream m_os;
  11176. public:
  11177. // Store the streambuf from cout up-front because
  11178. // cout may get redirected when running tests
  11179. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  11180. ~CoutStream() override = default;
  11181. public: // IStream
  11182. std::ostream& stream() const override { return m_os; }
  11183. };
  11184. ///////////////////////////////////////////////////////////////////////////
  11185. class DebugOutStream : public IStream {
  11186. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  11187. mutable std::ostream m_os;
  11188. public:
  11189. DebugOutStream()
  11190. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  11191. m_os( m_streamBuf.get() )
  11192. {}
  11193. ~DebugOutStream() override = default;
  11194. public: // IStream
  11195. std::ostream& stream() const override { return m_os; }
  11196. };
  11197. }} // namespace anon::detail
  11198. ///////////////////////////////////////////////////////////////////////////
  11199. auto makeStream( StringRef const &filename ) -> IStream const* {
  11200. if( filename.empty() )
  11201. return new Detail::CoutStream();
  11202. else if( filename[0] == '%' ) {
  11203. if( filename == "%debug" )
  11204. return new Detail::DebugOutStream();
  11205. else
  11206. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  11207. }
  11208. else
  11209. return new Detail::FileStream( filename );
  11210. }
  11211. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  11212. struct StringStreams {
  11213. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  11214. std::vector<std::size_t> m_unused;
  11215. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  11216. auto add() -> std::size_t {
  11217. if( m_unused.empty() ) {
  11218. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  11219. return m_streams.size()-1;
  11220. }
  11221. else {
  11222. auto index = m_unused.back();
  11223. m_unused.pop_back();
  11224. return index;
  11225. }
  11226. }
  11227. void release( std::size_t index ) {
  11228. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  11229. m_unused.push_back(index);
  11230. }
  11231. };
  11232. ReusableStringStream::ReusableStringStream()
  11233. : m_index( Singleton<StringStreams>::getMutable().add() ),
  11234. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  11235. {}
  11236. ReusableStringStream::~ReusableStringStream() {
  11237. static_cast<std::ostringstream*>( m_oss )->str("");
  11238. m_oss->clear();
  11239. Singleton<StringStreams>::getMutable().release( m_index );
  11240. }
  11241. auto ReusableStringStream::str() const -> std::string {
  11242. return static_cast<std::ostringstream*>( m_oss )->str();
  11243. }
  11244. ///////////////////////////////////////////////////////////////////////////
  11245. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  11246. std::ostream& cout() { return std::cout; }
  11247. std::ostream& cerr() { return std::cerr; }
  11248. std::ostream& clog() { return std::clog; }
  11249. #endif
  11250. }
  11251. // end catch_stream.cpp
  11252. // start catch_string_manip.cpp
  11253. #include <algorithm>
  11254. #include <ostream>
  11255. #include <cstring>
  11256. #include <cctype>
  11257. #include <vector>
  11258. namespace Catch {
  11259. namespace {
  11260. char toLowerCh(char c) {
  11261. return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
  11262. }
  11263. }
  11264. bool startsWith( std::string const& s, std::string const& prefix ) {
  11265. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  11266. }
  11267. bool startsWith( std::string const& s, char prefix ) {
  11268. return !s.empty() && s[0] == prefix;
  11269. }
  11270. bool endsWith( std::string const& s, std::string const& suffix ) {
  11271. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  11272. }
  11273. bool endsWith( std::string const& s, char suffix ) {
  11274. return !s.empty() && s[s.size()-1] == suffix;
  11275. }
  11276. bool contains( std::string const& s, std::string const& infix ) {
  11277. return s.find( infix ) != std::string::npos;
  11278. }
  11279. void toLowerInPlace( std::string& s ) {
  11280. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  11281. }
  11282. std::string toLower( std::string const& s ) {
  11283. std::string lc = s;
  11284. toLowerInPlace( lc );
  11285. return lc;
  11286. }
  11287. std::string trim( std::string const& str ) {
  11288. static char const* whitespaceChars = "\n\r\t ";
  11289. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  11290. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  11291. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  11292. }
  11293. StringRef trim(StringRef ref) {
  11294. const auto is_ws = [](char c) {
  11295. return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  11296. };
  11297. size_t real_begin = 0;
  11298. while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
  11299. size_t real_end = ref.size();
  11300. while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
  11301. return ref.substr(real_begin, real_end - real_begin);
  11302. }
  11303. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  11304. bool replaced = false;
  11305. std::size_t i = str.find( replaceThis );
  11306. while( i != std::string::npos ) {
  11307. replaced = true;
  11308. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  11309. if( i < str.size()-withThis.size() )
  11310. i = str.find( replaceThis, i+withThis.size() );
  11311. else
  11312. i = std::string::npos;
  11313. }
  11314. return replaced;
  11315. }
  11316. std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
  11317. std::vector<StringRef> subStrings;
  11318. std::size_t start = 0;
  11319. for(std::size_t pos = 0; pos < str.size(); ++pos ) {
  11320. if( str[pos] == delimiter ) {
  11321. if( pos - start > 1 )
  11322. subStrings.push_back( str.substr( start, pos-start ) );
  11323. start = pos+1;
  11324. }
  11325. }
  11326. if( start < str.size() )
  11327. subStrings.push_back( str.substr( start, str.size()-start ) );
  11328. return subStrings;
  11329. }
  11330. pluralise::pluralise( std::size_t count, std::string const& label )
  11331. : m_count( count ),
  11332. m_label( label )
  11333. {}
  11334. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  11335. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  11336. if( pluraliser.m_count != 1 )
  11337. os << 's';
  11338. return os;
  11339. }
  11340. }
  11341. // end catch_string_manip.cpp
  11342. // start catch_stringref.cpp
  11343. #include <algorithm>
  11344. #include <ostream>
  11345. #include <cstring>
  11346. #include <cstdint>
  11347. namespace Catch {
  11348. StringRef::StringRef( char const* rawChars ) noexcept
  11349. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  11350. {}
  11351. auto StringRef::c_str() const -> char const* {
  11352. CATCH_ENFORCE(isNullTerminated(), "Called StringRef::c_str() on a non-null-terminated instance");
  11353. return m_start;
  11354. }
  11355. auto StringRef::data() const noexcept -> char const* {
  11356. return m_start;
  11357. }
  11358. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  11359. if (start < m_size) {
  11360. return StringRef(m_start + start, (std::min)(m_size - start, size));
  11361. } else {
  11362. return StringRef();
  11363. }
  11364. }
  11365. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  11366. return m_size == other.m_size
  11367. && (std::memcmp( m_start, other.m_start, m_size ) == 0);
  11368. }
  11369. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  11370. return os.write(str.data(), str.size());
  11371. }
  11372. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  11373. lhs.append(rhs.data(), rhs.size());
  11374. return lhs;
  11375. }
  11376. } // namespace Catch
  11377. // end catch_stringref.cpp
  11378. // start catch_tag_alias.cpp
  11379. namespace Catch {
  11380. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  11381. }
  11382. // end catch_tag_alias.cpp
  11383. // start catch_tag_alias_autoregistrar.cpp
  11384. namespace Catch {
  11385. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  11386. CATCH_TRY {
  11387. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  11388. } CATCH_CATCH_ALL {
  11389. // Do not throw when constructing global objects, instead register the exception to be processed later
  11390. getMutableRegistryHub().registerStartupException();
  11391. }
  11392. }
  11393. }
  11394. // end catch_tag_alias_autoregistrar.cpp
  11395. // start catch_tag_alias_registry.cpp
  11396. #include <sstream>
  11397. namespace Catch {
  11398. TagAliasRegistry::~TagAliasRegistry() {}
  11399. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  11400. auto it = m_registry.find( alias );
  11401. if( it != m_registry.end() )
  11402. return &(it->second);
  11403. else
  11404. return nullptr;
  11405. }
  11406. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  11407. std::string expandedTestSpec = unexpandedTestSpec;
  11408. for( auto const& registryKvp : m_registry ) {
  11409. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  11410. if( pos != std::string::npos ) {
  11411. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  11412. registryKvp.second.tag +
  11413. expandedTestSpec.substr( pos + registryKvp.first.size() );
  11414. }
  11415. }
  11416. return expandedTestSpec;
  11417. }
  11418. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  11419. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  11420. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  11421. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  11422. "error: tag alias, '" << alias << "' already registered.\n"
  11423. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  11424. << "\tRedefined at: " << lineInfo );
  11425. }
  11426. ITagAliasRegistry::~ITagAliasRegistry() {}
  11427. ITagAliasRegistry const& ITagAliasRegistry::get() {
  11428. return getRegistryHub().getTagAliasRegistry();
  11429. }
  11430. } // end namespace Catch
  11431. // end catch_tag_alias_registry.cpp
  11432. // start catch_test_case_info.cpp
  11433. #include <cctype>
  11434. #include <exception>
  11435. #include <algorithm>
  11436. #include <sstream>
  11437. namespace Catch {
  11438. namespace {
  11439. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  11440. if( startsWith( tag, '.' ) ||
  11441. tag == "!hide" )
  11442. return TestCaseInfo::IsHidden;
  11443. else if( tag == "!throws" )
  11444. return TestCaseInfo::Throws;
  11445. else if( tag == "!shouldfail" )
  11446. return TestCaseInfo::ShouldFail;
  11447. else if( tag == "!mayfail" )
  11448. return TestCaseInfo::MayFail;
  11449. else if( tag == "!nonportable" )
  11450. return TestCaseInfo::NonPortable;
  11451. else if( tag == "!benchmark" )
  11452. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  11453. else
  11454. return TestCaseInfo::None;
  11455. }
  11456. bool isReservedTag( std::string const& tag ) {
  11457. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  11458. }
  11459. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  11460. CATCH_ENFORCE( !isReservedTag(tag),
  11461. "Tag name: [" << tag << "] is not allowed.\n"
  11462. << "Tag names starting with non alphanumeric characters are reserved\n"
  11463. << _lineInfo );
  11464. }
  11465. }
  11466. TestCase makeTestCase( ITestInvoker* _testCase,
  11467. std::string const& _className,
  11468. NameAndTags const& nameAndTags,
  11469. SourceLineInfo const& _lineInfo )
  11470. {
  11471. bool isHidden = false;
  11472. // Parse out tags
  11473. std::vector<std::string> tags;
  11474. std::string desc, tag;
  11475. bool inTag = false;
  11476. for (char c : nameAndTags.tags) {
  11477. if( !inTag ) {
  11478. if( c == '[' )
  11479. inTag = true;
  11480. else
  11481. desc += c;
  11482. }
  11483. else {
  11484. if( c == ']' ) {
  11485. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  11486. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  11487. isHidden = true;
  11488. else if( prop == TestCaseInfo::None )
  11489. enforceNotReservedTag( tag, _lineInfo );
  11490. // Merged hide tags like `[.approvals]` should be added as
  11491. // `[.][approvals]`. The `[.]` is added at later point, so
  11492. // we only strip the prefix
  11493. if (startsWith(tag, '.') && tag.size() > 1) {
  11494. tag.erase(0, 1);
  11495. }
  11496. tags.push_back( tag );
  11497. tag.clear();
  11498. inTag = false;
  11499. }
  11500. else
  11501. tag += c;
  11502. }
  11503. }
  11504. if( isHidden ) {
  11505. // Add all "hidden" tags to make them behave identically
  11506. tags.insert( tags.end(), { ".", "!hide" } );
  11507. }
  11508. TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo );
  11509. return TestCase( _testCase, std::move(info) );
  11510. }
  11511. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  11512. std::sort(begin(tags), end(tags));
  11513. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  11514. testCaseInfo.lcaseTags.clear();
  11515. for( auto const& tag : tags ) {
  11516. std::string lcaseTag = toLower( tag );
  11517. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  11518. testCaseInfo.lcaseTags.push_back( lcaseTag );
  11519. }
  11520. testCaseInfo.tags = std::move(tags);
  11521. }
  11522. TestCaseInfo::TestCaseInfo( std::string const& _name,
  11523. std::string const& _className,
  11524. std::string const& _description,
  11525. std::vector<std::string> const& _tags,
  11526. SourceLineInfo const& _lineInfo )
  11527. : name( _name ),
  11528. className( _className ),
  11529. description( _description ),
  11530. lineInfo( _lineInfo ),
  11531. properties( None )
  11532. {
  11533. setTags( *this, _tags );
  11534. }
  11535. bool TestCaseInfo::isHidden() const {
  11536. return ( properties & IsHidden ) != 0;
  11537. }
  11538. bool TestCaseInfo::throws() const {
  11539. return ( properties & Throws ) != 0;
  11540. }
  11541. bool TestCaseInfo::okToFail() const {
  11542. return ( properties & (ShouldFail | MayFail ) ) != 0;
  11543. }
  11544. bool TestCaseInfo::expectedToFail() const {
  11545. return ( properties & (ShouldFail ) ) != 0;
  11546. }
  11547. std::string TestCaseInfo::tagsAsString() const {
  11548. std::string ret;
  11549. // '[' and ']' per tag
  11550. std::size_t full_size = 2 * tags.size();
  11551. for (const auto& tag : tags) {
  11552. full_size += tag.size();
  11553. }
  11554. ret.reserve(full_size);
  11555. for (const auto& tag : tags) {
  11556. ret.push_back('[');
  11557. ret.append(tag);
  11558. ret.push_back(']');
  11559. }
  11560. return ret;
  11561. }
  11562. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  11563. TestCase TestCase::withName( std::string const& _newName ) const {
  11564. TestCase other( *this );
  11565. other.name = _newName;
  11566. return other;
  11567. }
  11568. void TestCase::invoke() const {
  11569. test->invoke();
  11570. }
  11571. bool TestCase::operator == ( TestCase const& other ) const {
  11572. return test.get() == other.test.get() &&
  11573. name == other.name &&
  11574. className == other.className;
  11575. }
  11576. bool TestCase::operator < ( TestCase const& other ) const {
  11577. return name < other.name;
  11578. }
  11579. TestCaseInfo const& TestCase::getTestCaseInfo() const
  11580. {
  11581. return *this;
  11582. }
  11583. } // end namespace Catch
  11584. // end catch_test_case_info.cpp
  11585. // start catch_test_case_registry_impl.cpp
  11586. #include <algorithm>
  11587. #include <sstream>
  11588. namespace Catch {
  11589. namespace {
  11590. struct TestHasher {
  11591. using hash_t = uint64_t;
  11592. explicit TestHasher( hash_t hashSuffix ):
  11593. m_hashSuffix{ hashSuffix } {}
  11594. uint32_t operator()( TestCase const& t ) const {
  11595. // FNV-1a hash with multiplication fold.
  11596. const hash_t prime = 1099511628211u;
  11597. hash_t hash = 14695981039346656037u;
  11598. for ( const char c : t.name ) {
  11599. hash ^= c;
  11600. hash *= prime;
  11601. }
  11602. hash ^= m_hashSuffix;
  11603. hash *= prime;
  11604. const uint32_t low{ static_cast<uint32_t>( hash ) };
  11605. const uint32_t high{ static_cast<uint32_t>( hash >> 32 ) };
  11606. return low * high;
  11607. }
  11608. private:
  11609. hash_t m_hashSuffix;
  11610. };
  11611. } // end unnamed namespace
  11612. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  11613. switch( config.runOrder() ) {
  11614. case RunTests::InDeclarationOrder:
  11615. // already in declaration order
  11616. break;
  11617. case RunTests::InLexicographicalOrder: {
  11618. std::vector<TestCase> sorted = unsortedTestCases;
  11619. std::sort( sorted.begin(), sorted.end() );
  11620. return sorted;
  11621. }
  11622. case RunTests::InRandomOrder: {
  11623. seedRng( config );
  11624. TestHasher h{ config.rngSeed() };
  11625. using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
  11626. std::vector<hashedTest> indexed_tests;
  11627. indexed_tests.reserve( unsortedTestCases.size() );
  11628. for (auto const& testCase : unsortedTestCases) {
  11629. indexed_tests.emplace_back(h(testCase), &testCase);
  11630. }
  11631. std::sort(indexed_tests.begin(), indexed_tests.end(),
  11632. [](hashedTest const& lhs, hashedTest const& rhs) {
  11633. if (lhs.first == rhs.first) {
  11634. return lhs.second->name < rhs.second->name;
  11635. }
  11636. return lhs.first < rhs.first;
  11637. });
  11638. std::vector<TestCase> sorted;
  11639. sorted.reserve( indexed_tests.size() );
  11640. for (auto const& hashed : indexed_tests) {
  11641. sorted.emplace_back(*hashed.second);
  11642. }
  11643. return sorted;
  11644. }
  11645. }
  11646. return unsortedTestCases;
  11647. }
  11648. bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
  11649. return !testCase.throws() || config.allowThrows();
  11650. }
  11651. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  11652. return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
  11653. }
  11654. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  11655. std::set<TestCase> seenFunctions;
  11656. for( auto const& function : functions ) {
  11657. auto prev = seenFunctions.insert( function );
  11658. CATCH_ENFORCE( prev.second,
  11659. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  11660. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  11661. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  11662. }
  11663. }
  11664. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  11665. std::vector<TestCase> filtered;
  11666. filtered.reserve( testCases.size() );
  11667. for (auto const& testCase : testCases) {
  11668. if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
  11669. (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
  11670. filtered.push_back(testCase);
  11671. }
  11672. }
  11673. return filtered;
  11674. }
  11675. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  11676. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  11677. }
  11678. void TestRegistry::registerTest( TestCase const& testCase ) {
  11679. std::string name = testCase.getTestCaseInfo().name;
  11680. if( name.empty() ) {
  11681. ReusableStringStream rss;
  11682. rss << "Anonymous test case " << ++m_unnamedCount;
  11683. return registerTest( testCase.withName( rss.str() ) );
  11684. }
  11685. m_functions.push_back( testCase );
  11686. }
  11687. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  11688. return m_functions;
  11689. }
  11690. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  11691. if( m_sortedFunctions.empty() )
  11692. enforceNoDuplicateTestCases( m_functions );
  11693. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  11694. m_sortedFunctions = sortTests( config, m_functions );
  11695. m_currentSortOrder = config.runOrder();
  11696. }
  11697. return m_sortedFunctions;
  11698. }
  11699. ///////////////////////////////////////////////////////////////////////////
  11700. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  11701. void TestInvokerAsFunction::invoke() const {
  11702. m_testAsFunction();
  11703. }
  11704. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  11705. std::string className(classOrQualifiedMethodName);
  11706. if( startsWith( className, '&' ) )
  11707. {
  11708. std::size_t lastColons = className.rfind( "::" );
  11709. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  11710. if( penultimateColons == std::string::npos )
  11711. penultimateColons = 1;
  11712. className = className.substr( penultimateColons, lastColons-penultimateColons );
  11713. }
  11714. return className;
  11715. }
  11716. } // end namespace Catch
  11717. // end catch_test_case_registry_impl.cpp
  11718. // start catch_test_case_tracker.cpp
  11719. #include <algorithm>
  11720. #include <cassert>
  11721. #include <stdexcept>
  11722. #include <memory>
  11723. #include <sstream>
  11724. #if defined(__clang__)
  11725. # pragma clang diagnostic push
  11726. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  11727. #endif
  11728. namespace Catch {
  11729. namespace TestCaseTracking {
  11730. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  11731. : name( _name ),
  11732. location( _location )
  11733. {}
  11734. ITracker::~ITracker() = default;
  11735. ITracker& TrackerContext::startRun() {
  11736. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  11737. m_currentTracker = nullptr;
  11738. m_runState = Executing;
  11739. return *m_rootTracker;
  11740. }
  11741. void TrackerContext::endRun() {
  11742. m_rootTracker.reset();
  11743. m_currentTracker = nullptr;
  11744. m_runState = NotStarted;
  11745. }
  11746. void TrackerContext::startCycle() {
  11747. m_currentTracker = m_rootTracker.get();
  11748. m_runState = Executing;
  11749. }
  11750. void TrackerContext::completeCycle() {
  11751. m_runState = CompletedCycle;
  11752. }
  11753. bool TrackerContext::completedCycle() const {
  11754. return m_runState == CompletedCycle;
  11755. }
  11756. ITracker& TrackerContext::currentTracker() {
  11757. return *m_currentTracker;
  11758. }
  11759. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  11760. m_currentTracker = tracker;
  11761. }
  11762. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
  11763. ITracker(nameAndLocation),
  11764. m_ctx( ctx ),
  11765. m_parent( parent )
  11766. {}
  11767. bool TrackerBase::isComplete() const {
  11768. return m_runState == CompletedSuccessfully || m_runState == Failed;
  11769. }
  11770. bool TrackerBase::isSuccessfullyCompleted() const {
  11771. return m_runState == CompletedSuccessfully;
  11772. }
  11773. bool TrackerBase::isOpen() const {
  11774. return m_runState != NotStarted && !isComplete();
  11775. }
  11776. bool TrackerBase::hasChildren() const {
  11777. return !m_children.empty();
  11778. }
  11779. void TrackerBase::addChild( ITrackerPtr const& child ) {
  11780. m_children.push_back( child );
  11781. }
  11782. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  11783. auto it = std::find_if( m_children.begin(), m_children.end(),
  11784. [&nameAndLocation]( ITrackerPtr const& tracker ){
  11785. return
  11786. tracker->nameAndLocation().location == nameAndLocation.location &&
  11787. tracker->nameAndLocation().name == nameAndLocation.name;
  11788. } );
  11789. return( it != m_children.end() )
  11790. ? *it
  11791. : nullptr;
  11792. }
  11793. ITracker& TrackerBase::parent() {
  11794. assert( m_parent ); // Should always be non-null except for root
  11795. return *m_parent;
  11796. }
  11797. void TrackerBase::openChild() {
  11798. if( m_runState != ExecutingChildren ) {
  11799. m_runState = ExecutingChildren;
  11800. if( m_parent )
  11801. m_parent->openChild();
  11802. }
  11803. }
  11804. bool TrackerBase::isSectionTracker() const { return false; }
  11805. bool TrackerBase::isGeneratorTracker() const { return false; }
  11806. void TrackerBase::open() {
  11807. m_runState = Executing;
  11808. moveToThis();
  11809. if( m_parent )
  11810. m_parent->openChild();
  11811. }
  11812. void TrackerBase::close() {
  11813. // Close any still open children (e.g. generators)
  11814. while( &m_ctx.currentTracker() != this )
  11815. m_ctx.currentTracker().close();
  11816. switch( m_runState ) {
  11817. case NeedsAnotherRun:
  11818. break;
  11819. case Executing:
  11820. m_runState = CompletedSuccessfully;
  11821. break;
  11822. case ExecutingChildren:
  11823. if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
  11824. m_runState = CompletedSuccessfully;
  11825. break;
  11826. case NotStarted:
  11827. case CompletedSuccessfully:
  11828. case Failed:
  11829. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  11830. default:
  11831. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  11832. }
  11833. moveToParent();
  11834. m_ctx.completeCycle();
  11835. }
  11836. void TrackerBase::fail() {
  11837. m_runState = Failed;
  11838. if( m_parent )
  11839. m_parent->markAsNeedingAnotherRun();
  11840. moveToParent();
  11841. m_ctx.completeCycle();
  11842. }
  11843. void TrackerBase::markAsNeedingAnotherRun() {
  11844. m_runState = NeedsAnotherRun;
  11845. }
  11846. void TrackerBase::moveToParent() {
  11847. assert( m_parent );
  11848. m_ctx.setCurrentTracker( m_parent );
  11849. }
  11850. void TrackerBase::moveToThis() {
  11851. m_ctx.setCurrentTracker( this );
  11852. }
  11853. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  11854. : TrackerBase( nameAndLocation, ctx, parent ),
  11855. m_trimmed_name(trim(nameAndLocation.name))
  11856. {
  11857. if( parent ) {
  11858. while( !parent->isSectionTracker() )
  11859. parent = &parent->parent();
  11860. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  11861. addNextFilters( parentSection.m_filters );
  11862. }
  11863. }
  11864. bool SectionTracker::isComplete() const {
  11865. bool complete = true;
  11866. if (m_filters.empty()
  11867. || m_filters[0] == ""
  11868. || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
  11869. complete = TrackerBase::isComplete();
  11870. }
  11871. return complete;
  11872. }
  11873. bool SectionTracker::isSectionTracker() const { return true; }
  11874. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  11875. std::shared_ptr<SectionTracker> section;
  11876. ITracker& currentTracker = ctx.currentTracker();
  11877. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  11878. assert( childTracker );
  11879. assert( childTracker->isSectionTracker() );
  11880. section = std::static_pointer_cast<SectionTracker>( childTracker );
  11881. }
  11882. else {
  11883. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  11884. currentTracker.addChild( section );
  11885. }
  11886. if( !ctx.completedCycle() )
  11887. section->tryOpen();
  11888. return *section;
  11889. }
  11890. void SectionTracker::tryOpen() {
  11891. if( !isComplete() )
  11892. open();
  11893. }
  11894. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  11895. if( !filters.empty() ) {
  11896. m_filters.reserve( m_filters.size() + filters.size() + 2 );
  11897. m_filters.emplace_back(""); // Root - should never be consulted
  11898. m_filters.emplace_back(""); // Test Case - not a section filter
  11899. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  11900. }
  11901. }
  11902. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  11903. if( filters.size() > 1 )
  11904. m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
  11905. }
  11906. std::vector<std::string> const& SectionTracker::getFilters() const {
  11907. return m_filters;
  11908. }
  11909. std::string const& SectionTracker::trimmedName() const {
  11910. return m_trimmed_name;
  11911. }
  11912. } // namespace TestCaseTracking
  11913. using TestCaseTracking::ITracker;
  11914. using TestCaseTracking::TrackerContext;
  11915. using TestCaseTracking::SectionTracker;
  11916. } // namespace Catch
  11917. #if defined(__clang__)
  11918. # pragma clang diagnostic pop
  11919. #endif
  11920. // end catch_test_case_tracker.cpp
  11921. // start catch_test_registry.cpp
  11922. namespace Catch {
  11923. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  11924. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  11925. }
  11926. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  11927. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  11928. CATCH_TRY {
  11929. getMutableRegistryHub()
  11930. .registerTest(
  11931. makeTestCase(
  11932. invoker,
  11933. extractClassName( classOrMethod ),
  11934. nameAndTags,
  11935. lineInfo));
  11936. } CATCH_CATCH_ALL {
  11937. // Do not throw when constructing global objects, instead register the exception to be processed later
  11938. getMutableRegistryHub().registerStartupException();
  11939. }
  11940. }
  11941. AutoReg::~AutoReg() = default;
  11942. }
  11943. // end catch_test_registry.cpp
  11944. // start catch_test_spec.cpp
  11945. #include <algorithm>
  11946. #include <string>
  11947. #include <vector>
  11948. #include <memory>
  11949. namespace Catch {
  11950. TestSpec::Pattern::Pattern( std::string const& name )
  11951. : m_name( name )
  11952. {}
  11953. TestSpec::Pattern::~Pattern() = default;
  11954. std::string const& TestSpec::Pattern::name() const {
  11955. return m_name;
  11956. }
  11957. TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
  11958. : Pattern( filterString )
  11959. , m_wildcardPattern( toLower( name ), CaseSensitive::No )
  11960. {}
  11961. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  11962. return m_wildcardPattern.matches( testCase.name );
  11963. }
  11964. TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
  11965. : Pattern( filterString )
  11966. , m_tag( toLower( tag ) )
  11967. {}
  11968. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  11969. return std::find(begin(testCase.lcaseTags),
  11970. end(testCase.lcaseTags),
  11971. m_tag) != end(testCase.lcaseTags);
  11972. }
  11973. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
  11974. : Pattern( underlyingPattern->name() )
  11975. , m_underlyingPattern( underlyingPattern )
  11976. {}
  11977. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
  11978. return !m_underlyingPattern->matches( testCase );
  11979. }
  11980. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  11981. return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
  11982. }
  11983. std::string TestSpec::Filter::name() const {
  11984. std::string name;
  11985. for( auto const& p : m_patterns )
  11986. name += p->name();
  11987. return name;
  11988. }
  11989. bool TestSpec::hasFilters() const {
  11990. return !m_filters.empty();
  11991. }
  11992. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  11993. return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
  11994. }
  11995. TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
  11996. {
  11997. Matches matches( m_filters.size() );
  11998. std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
  11999. std::vector<TestCase const*> currentMatches;
  12000. for( auto const& test : testCases )
  12001. if( isThrowSafe( test, config ) && filter.matches( test ) )
  12002. currentMatches.emplace_back( &test );
  12003. return FilterMatch{ filter.name(), currentMatches };
  12004. } );
  12005. return matches;
  12006. }
  12007. const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const{
  12008. return (m_invalidArgs);
  12009. }
  12010. }
  12011. // end catch_test_spec.cpp
  12012. // start catch_test_spec_parser.cpp
  12013. namespace Catch {
  12014. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  12015. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  12016. m_mode = None;
  12017. m_exclusion = false;
  12018. m_arg = m_tagAliases->expandAliases( arg );
  12019. m_escapeChars.clear();
  12020. m_substring.reserve(m_arg.size());
  12021. m_patternName.reserve(m_arg.size());
  12022. m_realPatternPos = 0;
  12023. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  12024. //if visitChar fails
  12025. if( !visitChar( m_arg[m_pos] ) ){
  12026. m_testSpec.m_invalidArgs.push_back(arg);
  12027. break;
  12028. }
  12029. endMode();
  12030. return *this;
  12031. }
  12032. TestSpec TestSpecParser::testSpec() {
  12033. addFilter();
  12034. return m_testSpec;
  12035. }
  12036. bool TestSpecParser::visitChar( char c ) {
  12037. if( (m_mode != EscapedName) && (c == '\\') ) {
  12038. escape();
  12039. addCharToPattern(c);
  12040. return true;
  12041. }else if((m_mode != EscapedName) && (c == ',') ) {
  12042. return separate();
  12043. }
  12044. switch( m_mode ) {
  12045. case None:
  12046. if( processNoneChar( c ) )
  12047. return true;
  12048. break;
  12049. case Name:
  12050. processNameChar( c );
  12051. break;
  12052. case EscapedName:
  12053. endMode();
  12054. addCharToPattern(c);
  12055. return true;
  12056. default:
  12057. case Tag:
  12058. case QuotedName:
  12059. if( processOtherChar( c ) )
  12060. return true;
  12061. break;
  12062. }
  12063. m_substring += c;
  12064. if( !isControlChar( c ) ) {
  12065. m_patternName += c;
  12066. m_realPatternPos++;
  12067. }
  12068. return true;
  12069. }
  12070. // Two of the processing methods return true to signal the caller to return
  12071. // without adding the given character to the current pattern strings
  12072. bool TestSpecParser::processNoneChar( char c ) {
  12073. switch( c ) {
  12074. case ' ':
  12075. return true;
  12076. case '~':
  12077. m_exclusion = true;
  12078. return false;
  12079. case '[':
  12080. startNewMode( Tag );
  12081. return false;
  12082. case '"':
  12083. startNewMode( QuotedName );
  12084. return false;
  12085. default:
  12086. startNewMode( Name );
  12087. return false;
  12088. }
  12089. }
  12090. void TestSpecParser::processNameChar( char c ) {
  12091. if( c == '[' ) {
  12092. if( m_substring == "exclude:" )
  12093. m_exclusion = true;
  12094. else
  12095. endMode();
  12096. startNewMode( Tag );
  12097. }
  12098. }
  12099. bool TestSpecParser::processOtherChar( char c ) {
  12100. if( !isControlChar( c ) )
  12101. return false;
  12102. m_substring += c;
  12103. endMode();
  12104. return true;
  12105. }
  12106. void TestSpecParser::startNewMode( Mode mode ) {
  12107. m_mode = mode;
  12108. }
  12109. void TestSpecParser::endMode() {
  12110. switch( m_mode ) {
  12111. case Name:
  12112. case QuotedName:
  12113. return addNamePattern();
  12114. case Tag:
  12115. return addTagPattern();
  12116. case EscapedName:
  12117. revertBackToLastMode();
  12118. return;
  12119. case None:
  12120. default:
  12121. return startNewMode( None );
  12122. }
  12123. }
  12124. void TestSpecParser::escape() {
  12125. saveLastMode();
  12126. m_mode = EscapedName;
  12127. m_escapeChars.push_back(m_realPatternPos);
  12128. }
  12129. bool TestSpecParser::isControlChar( char c ) const {
  12130. switch( m_mode ) {
  12131. default:
  12132. return false;
  12133. case None:
  12134. return c == '~';
  12135. case Name:
  12136. return c == '[';
  12137. case EscapedName:
  12138. return true;
  12139. case QuotedName:
  12140. return c == '"';
  12141. case Tag:
  12142. return c == '[' || c == ']';
  12143. }
  12144. }
  12145. void TestSpecParser::addFilter() {
  12146. if( !m_currentFilter.m_patterns.empty() ) {
  12147. m_testSpec.m_filters.push_back( m_currentFilter );
  12148. m_currentFilter = TestSpec::Filter();
  12149. }
  12150. }
  12151. void TestSpecParser::saveLastMode() {
  12152. lastMode = m_mode;
  12153. }
  12154. void TestSpecParser::revertBackToLastMode() {
  12155. m_mode = lastMode;
  12156. }
  12157. bool TestSpecParser::separate() {
  12158. if( (m_mode==QuotedName) || (m_mode==Tag) ){
  12159. //invalid argument, signal failure to previous scope.
  12160. m_mode = None;
  12161. m_pos = m_arg.size();
  12162. m_substring.clear();
  12163. m_patternName.clear();
  12164. m_realPatternPos = 0;
  12165. return false;
  12166. }
  12167. endMode();
  12168. addFilter();
  12169. return true; //success
  12170. }
  12171. std::string TestSpecParser::preprocessPattern() {
  12172. std::string token = m_patternName;
  12173. for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
  12174. token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
  12175. m_escapeChars.clear();
  12176. if (startsWith(token, "exclude:")) {
  12177. m_exclusion = true;
  12178. token = token.substr(8);
  12179. }
  12180. m_patternName.clear();
  12181. m_realPatternPos = 0;
  12182. return token;
  12183. }
  12184. void TestSpecParser::addNamePattern() {
  12185. auto token = preprocessPattern();
  12186. if (!token.empty()) {
  12187. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
  12188. if (m_exclusion)
  12189. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12190. m_currentFilter.m_patterns.push_back(pattern);
  12191. }
  12192. m_substring.clear();
  12193. m_exclusion = false;
  12194. m_mode = None;
  12195. }
  12196. void TestSpecParser::addTagPattern() {
  12197. auto token = preprocessPattern();
  12198. if (!token.empty()) {
  12199. // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
  12200. // we have to create a separate hide tag and shorten the real one
  12201. if (token.size() > 1 && token[0] == '.') {
  12202. token.erase(token.begin());
  12203. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring);
  12204. if (m_exclusion) {
  12205. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12206. }
  12207. m_currentFilter.m_patterns.push_back(pattern);
  12208. }
  12209. TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
  12210. if (m_exclusion) {
  12211. pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
  12212. }
  12213. m_currentFilter.m_patterns.push_back(pattern);
  12214. }
  12215. m_substring.clear();
  12216. m_exclusion = false;
  12217. m_mode = None;
  12218. }
  12219. TestSpec parseTestSpec( std::string const& arg ) {
  12220. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  12221. }
  12222. } // namespace Catch
  12223. // end catch_test_spec_parser.cpp
  12224. // start catch_timer.cpp
  12225. #include <chrono>
  12226. static const uint64_t nanosecondsInSecond = 1000000000;
  12227. namespace Catch {
  12228. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  12229. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  12230. }
  12231. namespace {
  12232. auto estimateClockResolution() -> uint64_t {
  12233. uint64_t sum = 0;
  12234. static const uint64_t iterations = 1000000;
  12235. auto startTime = getCurrentNanosecondsSinceEpoch();
  12236. for( std::size_t i = 0; i < iterations; ++i ) {
  12237. uint64_t ticks;
  12238. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  12239. do {
  12240. ticks = getCurrentNanosecondsSinceEpoch();
  12241. } while( ticks == baseTicks );
  12242. auto delta = ticks - baseTicks;
  12243. sum += delta;
  12244. // If we have been calibrating for over 3 seconds -- the clock
  12245. // is terrible and we should move on.
  12246. // TBD: How to signal that the measured resolution is probably wrong?
  12247. if (ticks > startTime + 3 * nanosecondsInSecond) {
  12248. return sum / ( i + 1u );
  12249. }
  12250. }
  12251. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  12252. // - and potentially do more iterations if there's a high variance.
  12253. return sum/iterations;
  12254. }
  12255. }
  12256. auto getEstimatedClockResolution() -> uint64_t {
  12257. static auto s_resolution = estimateClockResolution();
  12258. return s_resolution;
  12259. }
  12260. void Timer::start() {
  12261. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  12262. }
  12263. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  12264. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  12265. }
  12266. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  12267. return getElapsedNanoseconds()/1000;
  12268. }
  12269. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  12270. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  12271. }
  12272. auto Timer::getElapsedSeconds() const -> double {
  12273. return getElapsedMicroseconds()/1000000.0;
  12274. }
  12275. } // namespace Catch
  12276. // end catch_timer.cpp
  12277. // start catch_tostring.cpp
  12278. #if defined(__clang__)
  12279. # pragma clang diagnostic push
  12280. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  12281. # pragma clang diagnostic ignored "-Wglobal-constructors"
  12282. #endif
  12283. // Enable specific decls locally
  12284. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  12285. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  12286. #endif
  12287. #include <cmath>
  12288. #include <iomanip>
  12289. namespace Catch {
  12290. namespace Detail {
  12291. const std::string unprintableString = "{?}";
  12292. namespace {
  12293. const int hexThreshold = 255;
  12294. struct Endianness {
  12295. enum Arch { Big, Little };
  12296. static Arch which() {
  12297. int one = 1;
  12298. // If the lowest byte we read is non-zero, we can assume
  12299. // that little endian format is used.
  12300. auto value = *reinterpret_cast<char*>(&one);
  12301. return value ? Little : Big;
  12302. }
  12303. };
  12304. }
  12305. std::string rawMemoryToString( const void *object, std::size_t size ) {
  12306. // Reverse order for little endian architectures
  12307. int i = 0, end = static_cast<int>( size ), inc = 1;
  12308. if( Endianness::which() == Endianness::Little ) {
  12309. i = end-1;
  12310. end = inc = -1;
  12311. }
  12312. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  12313. ReusableStringStream rss;
  12314. rss << "0x" << std::setfill('0') << std::hex;
  12315. for( ; i != end; i += inc )
  12316. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  12317. return rss.str();
  12318. }
  12319. }
  12320. template<typename T>
  12321. std::string fpToString( T value, int precision ) {
  12322. if (Catch::isnan(value)) {
  12323. return "nan";
  12324. }
  12325. ReusableStringStream rss;
  12326. rss << std::setprecision( precision )
  12327. << std::fixed
  12328. << value;
  12329. std::string d = rss.str();
  12330. std::size_t i = d.find_last_not_of( '0' );
  12331. if( i != std::string::npos && i != d.size()-1 ) {
  12332. if( d[i] == '.' )
  12333. i++;
  12334. d = d.substr( 0, i+1 );
  12335. }
  12336. return d;
  12337. }
  12338. //// ======================================================= ////
  12339. //
  12340. // Out-of-line defs for full specialization of StringMaker
  12341. //
  12342. //// ======================================================= ////
  12343. std::string StringMaker<std::string>::convert(const std::string& str) {
  12344. if (!getCurrentContext().getConfig()->showInvisibles()) {
  12345. return '"' + str + '"';
  12346. }
  12347. std::string s("\"");
  12348. for (char c : str) {
  12349. switch (c) {
  12350. case '\n':
  12351. s.append("\\n");
  12352. break;
  12353. case '\t':
  12354. s.append("\\t");
  12355. break;
  12356. default:
  12357. s.push_back(c);
  12358. break;
  12359. }
  12360. }
  12361. s.append("\"");
  12362. return s;
  12363. }
  12364. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  12365. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  12366. return ::Catch::Detail::stringify(std::string{ str });
  12367. }
  12368. #endif
  12369. std::string StringMaker<char const*>::convert(char const* str) {
  12370. if (str) {
  12371. return ::Catch::Detail::stringify(std::string{ str });
  12372. } else {
  12373. return{ "{null string}" };
  12374. }
  12375. }
  12376. std::string StringMaker<char*>::convert(char* str) {
  12377. if (str) {
  12378. return ::Catch::Detail::stringify(std::string{ str });
  12379. } else {
  12380. return{ "{null string}" };
  12381. }
  12382. }
  12383. #ifdef CATCH_CONFIG_WCHAR
  12384. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  12385. std::string s;
  12386. s.reserve(wstr.size());
  12387. for (auto c : wstr) {
  12388. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  12389. }
  12390. return ::Catch::Detail::stringify(s);
  12391. }
  12392. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  12393. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  12394. return StringMaker<std::wstring>::convert(std::wstring(str));
  12395. }
  12396. # endif
  12397. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  12398. if (str) {
  12399. return ::Catch::Detail::stringify(std::wstring{ str });
  12400. } else {
  12401. return{ "{null string}" };
  12402. }
  12403. }
  12404. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  12405. if (str) {
  12406. return ::Catch::Detail::stringify(std::wstring{ str });
  12407. } else {
  12408. return{ "{null string}" };
  12409. }
  12410. }
  12411. #endif
  12412. #if defined(CATCH_CONFIG_CPP17_BYTE)
  12413. #include <cstddef>
  12414. std::string StringMaker<std::byte>::convert(std::byte value) {
  12415. return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
  12416. }
  12417. #endif // defined(CATCH_CONFIG_CPP17_BYTE)
  12418. std::string StringMaker<int>::convert(int value) {
  12419. return ::Catch::Detail::stringify(static_cast<long long>(value));
  12420. }
  12421. std::string StringMaker<long>::convert(long value) {
  12422. return ::Catch::Detail::stringify(static_cast<long long>(value));
  12423. }
  12424. std::string StringMaker<long long>::convert(long long value) {
  12425. ReusableStringStream rss;
  12426. rss << value;
  12427. if (value > Detail::hexThreshold) {
  12428. rss << " (0x" << std::hex << value << ')';
  12429. }
  12430. return rss.str();
  12431. }
  12432. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  12433. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  12434. }
  12435. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  12436. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  12437. }
  12438. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  12439. ReusableStringStream rss;
  12440. rss << value;
  12441. if (value > Detail::hexThreshold) {
  12442. rss << " (0x" << std::hex << value << ')';
  12443. }
  12444. return rss.str();
  12445. }
  12446. std::string StringMaker<bool>::convert(bool b) {
  12447. return b ? "true" : "false";
  12448. }
  12449. std::string StringMaker<signed char>::convert(signed char value) {
  12450. if (value == '\r') {
  12451. return "'\\r'";
  12452. } else if (value == '\f') {
  12453. return "'\\f'";
  12454. } else if (value == '\n') {
  12455. return "'\\n'";
  12456. } else if (value == '\t') {
  12457. return "'\\t'";
  12458. } else if ('\0' <= value && value < ' ') {
  12459. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  12460. } else {
  12461. char chstr[] = "' '";
  12462. chstr[1] = value;
  12463. return chstr;
  12464. }
  12465. }
  12466. std::string StringMaker<char>::convert(char c) {
  12467. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  12468. }
  12469. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  12470. return ::Catch::Detail::stringify(static_cast<char>(c));
  12471. }
  12472. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  12473. return "nullptr";
  12474. }
  12475. int StringMaker<float>::precision = 5;
  12476. std::string StringMaker<float>::convert(float value) {
  12477. return fpToString(value, precision) + 'f';
  12478. }
  12479. int StringMaker<double>::precision = 10;
  12480. std::string StringMaker<double>::convert(double value) {
  12481. return fpToString(value, precision);
  12482. }
  12483. std::string ratio_string<std::atto>::symbol() { return "a"; }
  12484. std::string ratio_string<std::femto>::symbol() { return "f"; }
  12485. std::string ratio_string<std::pico>::symbol() { return "p"; }
  12486. std::string ratio_string<std::nano>::symbol() { return "n"; }
  12487. std::string ratio_string<std::micro>::symbol() { return "u"; }
  12488. std::string ratio_string<std::milli>::symbol() { return "m"; }
  12489. } // end namespace Catch
  12490. #if defined(__clang__)
  12491. # pragma clang diagnostic pop
  12492. #endif
  12493. // end catch_tostring.cpp
  12494. // start catch_totals.cpp
  12495. namespace Catch {
  12496. Counts Counts::operator - ( Counts const& other ) const {
  12497. Counts diff;
  12498. diff.passed = passed - other.passed;
  12499. diff.failed = failed - other.failed;
  12500. diff.failedButOk = failedButOk - other.failedButOk;
  12501. return diff;
  12502. }
  12503. Counts& Counts::operator += ( Counts const& other ) {
  12504. passed += other.passed;
  12505. failed += other.failed;
  12506. failedButOk += other.failedButOk;
  12507. return *this;
  12508. }
  12509. std::size_t Counts::total() const {
  12510. return passed + failed + failedButOk;
  12511. }
  12512. bool Counts::allPassed() const {
  12513. return failed == 0 && failedButOk == 0;
  12514. }
  12515. bool Counts::allOk() const {
  12516. return failed == 0;
  12517. }
  12518. Totals Totals::operator - ( Totals const& other ) const {
  12519. Totals diff;
  12520. diff.assertions = assertions - other.assertions;
  12521. diff.testCases = testCases - other.testCases;
  12522. return diff;
  12523. }
  12524. Totals& Totals::operator += ( Totals const& other ) {
  12525. assertions += other.assertions;
  12526. testCases += other.testCases;
  12527. return *this;
  12528. }
  12529. Totals Totals::delta( Totals const& prevTotals ) const {
  12530. Totals diff = *this - prevTotals;
  12531. if( diff.assertions.failed > 0 )
  12532. ++diff.testCases.failed;
  12533. else if( diff.assertions.failedButOk > 0 )
  12534. ++diff.testCases.failedButOk;
  12535. else
  12536. ++diff.testCases.passed;
  12537. return diff;
  12538. }
  12539. }
  12540. // end catch_totals.cpp
  12541. // start catch_uncaught_exceptions.cpp
  12542. // start catch_config_uncaught_exceptions.hpp
  12543. // Copyright Catch2 Authors
  12544. // Distributed under the Boost Software License, Version 1.0.
  12545. // (See accompanying file LICENSE_1_0.txt or copy at
  12546. // https://www.boost.org/LICENSE_1_0.txt)
  12547. // SPDX-License-Identifier: BSL-1.0
  12548. #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12549. #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12550. #if defined(_MSC_VER)
  12551. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  12552. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12553. # endif
  12554. #endif
  12555. #include <exception>
  12556. #if defined(__cpp_lib_uncaught_exceptions) \
  12557. && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12558. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12559. #endif // __cpp_lib_uncaught_exceptions
  12560. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
  12561. && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
  12562. && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12563. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  12564. #endif
  12565. #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
  12566. // end catch_config_uncaught_exceptions.hpp
  12567. #include <exception>
  12568. namespace Catch {
  12569. bool uncaught_exceptions() {
  12570. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  12571. return false;
  12572. #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  12573. return std::uncaught_exceptions() > 0;
  12574. #else
  12575. return std::uncaught_exception();
  12576. #endif
  12577. }
  12578. } // end namespace Catch
  12579. // end catch_uncaught_exceptions.cpp
  12580. // start catch_version.cpp
  12581. #include <ostream>
  12582. namespace Catch {
  12583. Version::Version
  12584. ( unsigned int _majorVersion,
  12585. unsigned int _minorVersion,
  12586. unsigned int _patchNumber,
  12587. char const * const _branchName,
  12588. unsigned int _buildNumber )
  12589. : majorVersion( _majorVersion ),
  12590. minorVersion( _minorVersion ),
  12591. patchNumber( _patchNumber ),
  12592. branchName( _branchName ),
  12593. buildNumber( _buildNumber )
  12594. {}
  12595. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  12596. os << version.majorVersion << '.'
  12597. << version.minorVersion << '.'
  12598. << version.patchNumber;
  12599. // branchName is never null -> 0th char is \0 if it is empty
  12600. if (version.branchName[0]) {
  12601. os << '-' << version.branchName
  12602. << '.' << version.buildNumber;
  12603. }
  12604. return os;
  12605. }
  12606. Version const& libraryVersion() {
  12607. static Version version( 2, 13, 10, "", 0 );
  12608. return version;
  12609. }
  12610. }
  12611. // end catch_version.cpp
  12612. // start catch_wildcard_pattern.cpp
  12613. namespace Catch {
  12614. WildcardPattern::WildcardPattern( std::string const& pattern,
  12615. CaseSensitive::Choice caseSensitivity )
  12616. : m_caseSensitivity( caseSensitivity ),
  12617. m_pattern( normaliseString( pattern ) )
  12618. {
  12619. if( startsWith( m_pattern, '*' ) ) {
  12620. m_pattern = m_pattern.substr( 1 );
  12621. m_wildcard = WildcardAtStart;
  12622. }
  12623. if( endsWith( m_pattern, '*' ) ) {
  12624. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  12625. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  12626. }
  12627. }
  12628. bool WildcardPattern::matches( std::string const& str ) const {
  12629. switch( m_wildcard ) {
  12630. case NoWildcard:
  12631. return m_pattern == normaliseString( str );
  12632. case WildcardAtStart:
  12633. return endsWith( normaliseString( str ), m_pattern );
  12634. case WildcardAtEnd:
  12635. return startsWith( normaliseString( str ), m_pattern );
  12636. case WildcardAtBothEnds:
  12637. return contains( normaliseString( str ), m_pattern );
  12638. default:
  12639. CATCH_INTERNAL_ERROR( "Unknown enum" );
  12640. }
  12641. }
  12642. std::string WildcardPattern::normaliseString( std::string const& str ) const {
  12643. return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
  12644. }
  12645. }
  12646. // end catch_wildcard_pattern.cpp
  12647. // start catch_xmlwriter.cpp
  12648. #include <iomanip>
  12649. #include <type_traits>
  12650. namespace Catch {
  12651. namespace {
  12652. size_t trailingBytes(unsigned char c) {
  12653. if ((c & 0xE0) == 0xC0) {
  12654. return 2;
  12655. }
  12656. if ((c & 0xF0) == 0xE0) {
  12657. return 3;
  12658. }
  12659. if ((c & 0xF8) == 0xF0) {
  12660. return 4;
  12661. }
  12662. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12663. }
  12664. uint32_t headerValue(unsigned char c) {
  12665. if ((c & 0xE0) == 0xC0) {
  12666. return c & 0x1F;
  12667. }
  12668. if ((c & 0xF0) == 0xE0) {
  12669. return c & 0x0F;
  12670. }
  12671. if ((c & 0xF8) == 0xF0) {
  12672. return c & 0x07;
  12673. }
  12674. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  12675. }
  12676. void hexEscapeChar(std::ostream& os, unsigned char c) {
  12677. std::ios_base::fmtflags f(os.flags());
  12678. os << "\\x"
  12679. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  12680. << static_cast<int>(c);
  12681. os.flags(f);
  12682. }
  12683. bool shouldNewline(XmlFormatting fmt) {
  12684. return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));
  12685. }
  12686. bool shouldIndent(XmlFormatting fmt) {
  12687. return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));
  12688. }
  12689. } // anonymous namespace
  12690. XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
  12691. return static_cast<XmlFormatting>(
  12692. static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
  12693. static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
  12694. );
  12695. }
  12696. XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
  12697. return static_cast<XmlFormatting>(
  12698. static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
  12699. static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
  12700. );
  12701. }
  12702. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  12703. : m_str( str ),
  12704. m_forWhat( forWhat )
  12705. {}
  12706. void XmlEncode::encodeTo( std::ostream& os ) const {
  12707. // Apostrophe escaping not necessary if we always use " to write attributes
  12708. // (see: http://www.w3.org/TR/xml/#syntax)
  12709. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  12710. unsigned char c = m_str[idx];
  12711. switch (c) {
  12712. case '<': os << "&lt;"; break;
  12713. case '&': os << "&amp;"; break;
  12714. case '>':
  12715. // See: http://www.w3.org/TR/xml/#syntax
  12716. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  12717. os << "&gt;";
  12718. else
  12719. os << c;
  12720. break;
  12721. case '\"':
  12722. if (m_forWhat == ForAttributes)
  12723. os << "&quot;";
  12724. else
  12725. os << c;
  12726. break;
  12727. default:
  12728. // Check for control characters and invalid utf-8
  12729. // Escape control characters in standard ascii
  12730. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  12731. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  12732. hexEscapeChar(os, c);
  12733. break;
  12734. }
  12735. // Plain ASCII: Write it to stream
  12736. if (c < 0x7F) {
  12737. os << c;
  12738. break;
  12739. }
  12740. // UTF-8 territory
  12741. // Check if the encoding is valid and if it is not, hex escape bytes.
  12742. // Important: We do not check the exact decoded values for validity, only the encoding format
  12743. // First check that this bytes is a valid lead byte:
  12744. // This means that it is not encoded as 1111 1XXX
  12745. // Or as 10XX XXXX
  12746. if (c < 0xC0 ||
  12747. c >= 0xF8) {
  12748. hexEscapeChar(os, c);
  12749. break;
  12750. }
  12751. auto encBytes = trailingBytes(c);
  12752. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  12753. if (idx + encBytes - 1 >= m_str.size()) {
  12754. hexEscapeChar(os, c);
  12755. break;
  12756. }
  12757. // The header is valid, check data
  12758. // The next encBytes bytes must together be a valid utf-8
  12759. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  12760. bool valid = true;
  12761. uint32_t value = headerValue(c);
  12762. for (std::size_t n = 1; n < encBytes; ++n) {
  12763. unsigned char nc = m_str[idx + n];
  12764. valid &= ((nc & 0xC0) == 0x80);
  12765. value = (value << 6) | (nc & 0x3F);
  12766. }
  12767. if (
  12768. // Wrong bit pattern of following bytes
  12769. (!valid) ||
  12770. // Overlong encodings
  12771. (value < 0x80) ||
  12772. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  12773. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  12774. // Encoded value out of range
  12775. (value >= 0x110000)
  12776. ) {
  12777. hexEscapeChar(os, c);
  12778. break;
  12779. }
  12780. // If we got here, this is in fact a valid(ish) utf-8 sequence
  12781. for (std::size_t n = 0; n < encBytes; ++n) {
  12782. os << m_str[idx + n];
  12783. }
  12784. idx += encBytes - 1;
  12785. break;
  12786. }
  12787. }
  12788. }
  12789. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  12790. xmlEncode.encodeTo( os );
  12791. return os;
  12792. }
  12793. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
  12794. : m_writer( writer ),
  12795. m_fmt(fmt)
  12796. {}
  12797. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  12798. : m_writer( other.m_writer ),
  12799. m_fmt(other.m_fmt)
  12800. {
  12801. other.m_writer = nullptr;
  12802. other.m_fmt = XmlFormatting::None;
  12803. }
  12804. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  12805. if ( m_writer ) {
  12806. m_writer->endElement();
  12807. }
  12808. m_writer = other.m_writer;
  12809. other.m_writer = nullptr;
  12810. m_fmt = other.m_fmt;
  12811. other.m_fmt = XmlFormatting::None;
  12812. return *this;
  12813. }
  12814. XmlWriter::ScopedElement::~ScopedElement() {
  12815. if (m_writer) {
  12816. m_writer->endElement(m_fmt);
  12817. }
  12818. }
  12819. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, XmlFormatting fmt ) {
  12820. m_writer->writeText( text, fmt );
  12821. return *this;
  12822. }
  12823. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  12824. {
  12825. writeDeclaration();
  12826. }
  12827. XmlWriter::~XmlWriter() {
  12828. while (!m_tags.empty()) {
  12829. endElement();
  12830. }
  12831. newlineIfNecessary();
  12832. }
  12833. XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {
  12834. ensureTagClosed();
  12835. newlineIfNecessary();
  12836. if (shouldIndent(fmt)) {
  12837. m_os << m_indent;
  12838. m_indent += " ";
  12839. }
  12840. m_os << '<' << name;
  12841. m_tags.push_back( name );
  12842. m_tagIsOpen = true;
  12843. applyFormatting(fmt);
  12844. return *this;
  12845. }
  12846. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {
  12847. ScopedElement scoped( this, fmt );
  12848. startElement( name, fmt );
  12849. return scoped;
  12850. }
  12851. XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
  12852. m_indent = m_indent.substr(0, m_indent.size() - 2);
  12853. if( m_tagIsOpen ) {
  12854. m_os << "/>";
  12855. m_tagIsOpen = false;
  12856. } else {
  12857. newlineIfNecessary();
  12858. if (shouldIndent(fmt)) {
  12859. m_os << m_indent;
  12860. }
  12861. m_os << "</" << m_tags.back() << ">";
  12862. }
  12863. m_os << std::flush;
  12864. applyFormatting(fmt);
  12865. m_tags.pop_back();
  12866. return *this;
  12867. }
  12868. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  12869. if( !name.empty() && !attribute.empty() )
  12870. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  12871. return *this;
  12872. }
  12873. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  12874. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  12875. return *this;
  12876. }
  12877. XmlWriter& XmlWriter::writeText( std::string const& text, XmlFormatting fmt) {
  12878. if( !text.empty() ){
  12879. bool tagWasOpen = m_tagIsOpen;
  12880. ensureTagClosed();
  12881. if (tagWasOpen && shouldIndent(fmt)) {
  12882. m_os << m_indent;
  12883. }
  12884. m_os << XmlEncode( text );
  12885. applyFormatting(fmt);
  12886. }
  12887. return *this;
  12888. }
  12889. XmlWriter& XmlWriter::writeComment( std::string const& text, XmlFormatting fmt) {
  12890. ensureTagClosed();
  12891. if (shouldIndent(fmt)) {
  12892. m_os << m_indent;
  12893. }
  12894. m_os << "<!--" << text << "-->";
  12895. applyFormatting(fmt);
  12896. return *this;
  12897. }
  12898. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  12899. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  12900. }
  12901. XmlWriter& XmlWriter::writeBlankLine() {
  12902. ensureTagClosed();
  12903. m_os << '\n';
  12904. return *this;
  12905. }
  12906. void XmlWriter::ensureTagClosed() {
  12907. if( m_tagIsOpen ) {
  12908. m_os << '>' << std::flush;
  12909. newlineIfNecessary();
  12910. m_tagIsOpen = false;
  12911. }
  12912. }
  12913. void XmlWriter::applyFormatting(XmlFormatting fmt) {
  12914. m_needsNewline = shouldNewline(fmt);
  12915. }
  12916. void XmlWriter::writeDeclaration() {
  12917. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  12918. }
  12919. void XmlWriter::newlineIfNecessary() {
  12920. if( m_needsNewline ) {
  12921. m_os << std::endl;
  12922. m_needsNewline = false;
  12923. }
  12924. }
  12925. }
  12926. // end catch_xmlwriter.cpp
  12927. // start catch_reporter_bases.cpp
  12928. #include <cstring>
  12929. #include <cfloat>
  12930. #include <cstdio>
  12931. #include <cassert>
  12932. #include <memory>
  12933. namespace Catch {
  12934. void prepareExpandedExpression(AssertionResult& result) {
  12935. result.getExpandedExpression();
  12936. }
  12937. // Because formatting using c++ streams is stateful, drop down to C is required
  12938. // Alternatively we could use stringstream, but its performance is... not good.
  12939. std::string getFormattedDuration( double duration ) {
  12940. // Max exponent + 1 is required to represent the whole part
  12941. // + 1 for decimal point
  12942. // + 3 for the 3 decimal places
  12943. // + 1 for null terminator
  12944. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  12945. char buffer[maxDoubleSize];
  12946. // Save previous errno, to prevent sprintf from overwriting it
  12947. ErrnoGuard guard;
  12948. #ifdef _MSC_VER
  12949. sprintf_s(buffer, "%.3f", duration);
  12950. #else
  12951. std::sprintf(buffer, "%.3f", duration);
  12952. #endif
  12953. return std::string(buffer);
  12954. }
  12955. bool shouldShowDuration( IConfig const& config, double duration ) {
  12956. if ( config.showDurations() == ShowDurations::Always ) {
  12957. return true;
  12958. }
  12959. if ( config.showDurations() == ShowDurations::Never ) {
  12960. return false;
  12961. }
  12962. const double min = config.minDuration();
  12963. return min >= 0 && duration >= min;
  12964. }
  12965. std::string serializeFilters( std::vector<std::string> const& container ) {
  12966. ReusableStringStream oss;
  12967. bool first = true;
  12968. for (auto&& filter : container)
  12969. {
  12970. if (!first)
  12971. oss << ' ';
  12972. else
  12973. first = false;
  12974. oss << filter;
  12975. }
  12976. return oss.str();
  12977. }
  12978. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  12979. :StreamingReporterBase(_config) {}
  12980. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  12981. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  12982. }
  12983. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  12984. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  12985. return false;
  12986. }
  12987. } // end namespace Catch
  12988. // end catch_reporter_bases.cpp
  12989. // start catch_reporter_compact.cpp
  12990. namespace {
  12991. #ifdef CATCH_PLATFORM_MAC
  12992. const char* failedString() { return "FAILED"; }
  12993. const char* passedString() { return "PASSED"; }
  12994. #else
  12995. const char* failedString() { return "failed"; }
  12996. const char* passedString() { return "passed"; }
  12997. #endif
  12998. // Colour::LightGrey
  12999. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  13000. std::string bothOrAll( std::size_t count ) {
  13001. return count == 1 ? std::string() :
  13002. count == 2 ? "both " : "all " ;
  13003. }
  13004. } // anon namespace
  13005. namespace Catch {
  13006. namespace {
  13007. // Colour, message variants:
  13008. // - white: No tests ran.
  13009. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  13010. // - white: Passed [both/all] N test cases (no assertions).
  13011. // - red: Failed N tests cases, failed M assertions.
  13012. // - green: Passed [both/all] N tests cases with M assertions.
  13013. void printTotals(std::ostream& out, const Totals& totals) {
  13014. if (totals.testCases.total() == 0) {
  13015. out << "No tests ran.";
  13016. } else if (totals.testCases.failed == totals.testCases.total()) {
  13017. Colour colour(Colour::ResultError);
  13018. const std::string qualify_assertions_failed =
  13019. totals.assertions.failed == totals.assertions.total() ?
  13020. bothOrAll(totals.assertions.failed) : std::string();
  13021. out <<
  13022. "Failed " << bothOrAll(totals.testCases.failed)
  13023. << pluralise(totals.testCases.failed, "test case") << ", "
  13024. "failed " << qualify_assertions_failed <<
  13025. pluralise(totals.assertions.failed, "assertion") << '.';
  13026. } else if (totals.assertions.total() == 0) {
  13027. out <<
  13028. "Passed " << bothOrAll(totals.testCases.total())
  13029. << pluralise(totals.testCases.total(), "test case")
  13030. << " (no assertions).";
  13031. } else if (totals.assertions.failed) {
  13032. Colour colour(Colour::ResultError);
  13033. out <<
  13034. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  13035. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  13036. } else {
  13037. Colour colour(Colour::ResultSuccess);
  13038. out <<
  13039. "Passed " << bothOrAll(totals.testCases.passed)
  13040. << pluralise(totals.testCases.passed, "test case") <<
  13041. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  13042. }
  13043. }
  13044. // Implementation of CompactReporter formatting
  13045. class AssertionPrinter {
  13046. public:
  13047. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  13048. AssertionPrinter(AssertionPrinter const&) = delete;
  13049. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  13050. : stream(_stream)
  13051. , result(_stats.assertionResult)
  13052. , messages(_stats.infoMessages)
  13053. , itMessage(_stats.infoMessages.begin())
  13054. , printInfoMessages(_printInfoMessages) {}
  13055. void print() {
  13056. printSourceInfo();
  13057. itMessage = messages.begin();
  13058. switch (result.getResultType()) {
  13059. case ResultWas::Ok:
  13060. printResultType(Colour::ResultSuccess, passedString());
  13061. printOriginalExpression();
  13062. printReconstructedExpression();
  13063. if (!result.hasExpression())
  13064. printRemainingMessages(Colour::None);
  13065. else
  13066. printRemainingMessages();
  13067. break;
  13068. case ResultWas::ExpressionFailed:
  13069. if (result.isOk())
  13070. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  13071. else
  13072. printResultType(Colour::Error, failedString());
  13073. printOriginalExpression();
  13074. printReconstructedExpression();
  13075. printRemainingMessages();
  13076. break;
  13077. case ResultWas::ThrewException:
  13078. printResultType(Colour::Error, failedString());
  13079. printIssue("unexpected exception with message:");
  13080. printMessage();
  13081. printExpressionWas();
  13082. printRemainingMessages();
  13083. break;
  13084. case ResultWas::FatalErrorCondition:
  13085. printResultType(Colour::Error, failedString());
  13086. printIssue("fatal error condition with message:");
  13087. printMessage();
  13088. printExpressionWas();
  13089. printRemainingMessages();
  13090. break;
  13091. case ResultWas::DidntThrowException:
  13092. printResultType(Colour::Error, failedString());
  13093. printIssue("expected exception, got none");
  13094. printExpressionWas();
  13095. printRemainingMessages();
  13096. break;
  13097. case ResultWas::Info:
  13098. printResultType(Colour::None, "info");
  13099. printMessage();
  13100. printRemainingMessages();
  13101. break;
  13102. case ResultWas::Warning:
  13103. printResultType(Colour::None, "warning");
  13104. printMessage();
  13105. printRemainingMessages();
  13106. break;
  13107. case ResultWas::ExplicitFailure:
  13108. printResultType(Colour::Error, failedString());
  13109. printIssue("explicitly");
  13110. printRemainingMessages(Colour::None);
  13111. break;
  13112. // These cases are here to prevent compiler warnings
  13113. case ResultWas::Unknown:
  13114. case ResultWas::FailureBit:
  13115. case ResultWas::Exception:
  13116. printResultType(Colour::Error, "** internal error **");
  13117. break;
  13118. }
  13119. }
  13120. private:
  13121. void printSourceInfo() const {
  13122. Colour colourGuard(Colour::FileName);
  13123. stream << result.getSourceInfo() << ':';
  13124. }
  13125. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  13126. if (!passOrFail.empty()) {
  13127. {
  13128. Colour colourGuard(colour);
  13129. stream << ' ' << passOrFail;
  13130. }
  13131. stream << ':';
  13132. }
  13133. }
  13134. void printIssue(std::string const& issue) const {
  13135. stream << ' ' << issue;
  13136. }
  13137. void printExpressionWas() {
  13138. if (result.hasExpression()) {
  13139. stream << ';';
  13140. {
  13141. Colour colour(dimColour());
  13142. stream << " expression was:";
  13143. }
  13144. printOriginalExpression();
  13145. }
  13146. }
  13147. void printOriginalExpression() const {
  13148. if (result.hasExpression()) {
  13149. stream << ' ' << result.getExpression();
  13150. }
  13151. }
  13152. void printReconstructedExpression() const {
  13153. if (result.hasExpandedExpression()) {
  13154. {
  13155. Colour colour(dimColour());
  13156. stream << " for: ";
  13157. }
  13158. stream << result.getExpandedExpression();
  13159. }
  13160. }
  13161. void printMessage() {
  13162. if (itMessage != messages.end()) {
  13163. stream << " '" << itMessage->message << '\'';
  13164. ++itMessage;
  13165. }
  13166. }
  13167. void printRemainingMessages(Colour::Code colour = dimColour()) {
  13168. if (itMessage == messages.end())
  13169. return;
  13170. const auto itEnd = messages.cend();
  13171. const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  13172. {
  13173. Colour colourGuard(colour);
  13174. stream << " with " << pluralise(N, "message") << ':';
  13175. }
  13176. while (itMessage != itEnd) {
  13177. // If this assertion is a warning ignore any INFO messages
  13178. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  13179. printMessage();
  13180. if (itMessage != itEnd) {
  13181. Colour colourGuard(dimColour());
  13182. stream << " and";
  13183. }
  13184. continue;
  13185. }
  13186. ++itMessage;
  13187. }
  13188. }
  13189. private:
  13190. std::ostream& stream;
  13191. AssertionResult const& result;
  13192. std::vector<MessageInfo> messages;
  13193. std::vector<MessageInfo>::const_iterator itMessage;
  13194. bool printInfoMessages;
  13195. };
  13196. } // anon namespace
  13197. std::string CompactReporter::getDescription() {
  13198. return "Reports test results on a single line, suitable for IDEs";
  13199. }
  13200. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  13201. stream << "No test cases matched '" << spec << '\'' << std::endl;
  13202. }
  13203. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  13204. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  13205. AssertionResult const& result = _assertionStats.assertionResult;
  13206. bool printInfoMessages = true;
  13207. // Drop out if result was successful and we're not printing those
  13208. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  13209. if( result.getResultType() != ResultWas::Warning )
  13210. return false;
  13211. printInfoMessages = false;
  13212. }
  13213. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  13214. printer.print();
  13215. stream << std::endl;
  13216. return true;
  13217. }
  13218. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  13219. double dur = _sectionStats.durationInSeconds;
  13220. if ( shouldShowDuration( *m_config, dur ) ) {
  13221. stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  13222. }
  13223. }
  13224. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  13225. printTotals( stream, _testRunStats.totals );
  13226. stream << '\n' << std::endl;
  13227. StreamingReporterBase::testRunEnded( _testRunStats );
  13228. }
  13229. CompactReporter::~CompactReporter() {}
  13230. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  13231. } // end namespace Catch
  13232. // end catch_reporter_compact.cpp
  13233. // start catch_reporter_console.cpp
  13234. #include <cfloat>
  13235. #include <cstdio>
  13236. #if defined(_MSC_VER)
  13237. #pragma warning(push)
  13238. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  13239. // Note that 4062 (not all labels are handled and default is missing) is enabled
  13240. #endif
  13241. #if defined(__clang__)
  13242. # pragma clang diagnostic push
  13243. // For simplicity, benchmarking-only helpers are always enabled
  13244. # pragma clang diagnostic ignored "-Wunused-function"
  13245. #endif
  13246. namespace Catch {
  13247. namespace {
  13248. // Formatter impl for ConsoleReporter
  13249. class ConsoleAssertionPrinter {
  13250. public:
  13251. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  13252. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  13253. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  13254. : stream(_stream),
  13255. stats(_stats),
  13256. result(_stats.assertionResult),
  13257. colour(Colour::None),
  13258. message(result.getMessage()),
  13259. messages(_stats.infoMessages),
  13260. printInfoMessages(_printInfoMessages) {
  13261. switch (result.getResultType()) {
  13262. case ResultWas::Ok:
  13263. colour = Colour::Success;
  13264. passOrFail = "PASSED";
  13265. //if( result.hasMessage() )
  13266. if (_stats.infoMessages.size() == 1)
  13267. messageLabel = "with message";
  13268. if (_stats.infoMessages.size() > 1)
  13269. messageLabel = "with messages";
  13270. break;
  13271. case ResultWas::ExpressionFailed:
  13272. if (result.isOk()) {
  13273. colour = Colour::Success;
  13274. passOrFail = "FAILED - but was ok";
  13275. } else {
  13276. colour = Colour::Error;
  13277. passOrFail = "FAILED";
  13278. }
  13279. if (_stats.infoMessages.size() == 1)
  13280. messageLabel = "with message";
  13281. if (_stats.infoMessages.size() > 1)
  13282. messageLabel = "with messages";
  13283. break;
  13284. case ResultWas::ThrewException:
  13285. colour = Colour::Error;
  13286. passOrFail = "FAILED";
  13287. messageLabel = "due to unexpected exception with ";
  13288. if (_stats.infoMessages.size() == 1)
  13289. messageLabel += "message";
  13290. if (_stats.infoMessages.size() > 1)
  13291. messageLabel += "messages";
  13292. break;
  13293. case ResultWas::FatalErrorCondition:
  13294. colour = Colour::Error;
  13295. passOrFail = "FAILED";
  13296. messageLabel = "due to a fatal error condition";
  13297. break;
  13298. case ResultWas::DidntThrowException:
  13299. colour = Colour::Error;
  13300. passOrFail = "FAILED";
  13301. messageLabel = "because no exception was thrown where one was expected";
  13302. break;
  13303. case ResultWas::Info:
  13304. messageLabel = "info";
  13305. break;
  13306. case ResultWas::Warning:
  13307. messageLabel = "warning";
  13308. break;
  13309. case ResultWas::ExplicitFailure:
  13310. passOrFail = "FAILED";
  13311. colour = Colour::Error;
  13312. if (_stats.infoMessages.size() == 1)
  13313. messageLabel = "explicitly with message";
  13314. if (_stats.infoMessages.size() > 1)
  13315. messageLabel = "explicitly with messages";
  13316. break;
  13317. // These cases are here to prevent compiler warnings
  13318. case ResultWas::Unknown:
  13319. case ResultWas::FailureBit:
  13320. case ResultWas::Exception:
  13321. passOrFail = "** internal error **";
  13322. colour = Colour::Error;
  13323. break;
  13324. }
  13325. }
  13326. void print() const {
  13327. printSourceInfo();
  13328. if (stats.totals.assertions.total() > 0) {
  13329. printResultType();
  13330. printOriginalExpression();
  13331. printReconstructedExpression();
  13332. } else {
  13333. stream << '\n';
  13334. }
  13335. printMessage();
  13336. }
  13337. private:
  13338. void printResultType() const {
  13339. if (!passOrFail.empty()) {
  13340. Colour colourGuard(colour);
  13341. stream << passOrFail << ":\n";
  13342. }
  13343. }
  13344. void printOriginalExpression() const {
  13345. if (result.hasExpression()) {
  13346. Colour colourGuard(Colour::OriginalExpression);
  13347. stream << " ";
  13348. stream << result.getExpressionInMacro();
  13349. stream << '\n';
  13350. }
  13351. }
  13352. void printReconstructedExpression() const {
  13353. if (result.hasExpandedExpression()) {
  13354. stream << "with expansion:\n";
  13355. Colour colourGuard(Colour::ReconstructedExpression);
  13356. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  13357. }
  13358. }
  13359. void printMessage() const {
  13360. if (!messageLabel.empty())
  13361. stream << messageLabel << ':' << '\n';
  13362. for (auto const& msg : messages) {
  13363. // If this assertion is a warning ignore any INFO messages
  13364. if (printInfoMessages || msg.type != ResultWas::Info)
  13365. stream << Column(msg.message).indent(2) << '\n';
  13366. }
  13367. }
  13368. void printSourceInfo() const {
  13369. Colour colourGuard(Colour::FileName);
  13370. stream << result.getSourceInfo() << ": ";
  13371. }
  13372. std::ostream& stream;
  13373. AssertionStats const& stats;
  13374. AssertionResult const& result;
  13375. Colour::Code colour;
  13376. std::string passOrFail;
  13377. std::string messageLabel;
  13378. std::string message;
  13379. std::vector<MessageInfo> messages;
  13380. bool printInfoMessages;
  13381. };
  13382. std::size_t makeRatio(std::size_t number, std::size_t total) {
  13383. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  13384. return (ratio == 0 && number > 0) ? 1 : ratio;
  13385. }
  13386. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  13387. if (i > j && i > k)
  13388. return i;
  13389. else if (j > k)
  13390. return j;
  13391. else
  13392. return k;
  13393. }
  13394. struct ColumnInfo {
  13395. enum Justification { Left, Right };
  13396. std::string name;
  13397. int width;
  13398. Justification justification;
  13399. };
  13400. struct ColumnBreak {};
  13401. struct RowBreak {};
  13402. class Duration {
  13403. enum class Unit {
  13404. Auto,
  13405. Nanoseconds,
  13406. Microseconds,
  13407. Milliseconds,
  13408. Seconds,
  13409. Minutes
  13410. };
  13411. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  13412. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  13413. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  13414. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  13415. double m_inNanoseconds;
  13416. Unit m_units;
  13417. public:
  13418. explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
  13419. : m_inNanoseconds(inNanoseconds),
  13420. m_units(units) {
  13421. if (m_units == Unit::Auto) {
  13422. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  13423. m_units = Unit::Nanoseconds;
  13424. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  13425. m_units = Unit::Microseconds;
  13426. else if (m_inNanoseconds < s_nanosecondsInASecond)
  13427. m_units = Unit::Milliseconds;
  13428. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  13429. m_units = Unit::Seconds;
  13430. else
  13431. m_units = Unit::Minutes;
  13432. }
  13433. }
  13434. auto value() const -> double {
  13435. switch (m_units) {
  13436. case Unit::Microseconds:
  13437. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  13438. case Unit::Milliseconds:
  13439. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  13440. case Unit::Seconds:
  13441. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  13442. case Unit::Minutes:
  13443. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  13444. default:
  13445. return m_inNanoseconds;
  13446. }
  13447. }
  13448. auto unitsAsString() const -> std::string {
  13449. switch (m_units) {
  13450. case Unit::Nanoseconds:
  13451. return "ns";
  13452. case Unit::Microseconds:
  13453. return "us";
  13454. case Unit::Milliseconds:
  13455. return "ms";
  13456. case Unit::Seconds:
  13457. return "s";
  13458. case Unit::Minutes:
  13459. return "m";
  13460. default:
  13461. return "** internal error **";
  13462. }
  13463. }
  13464. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  13465. return os << duration.value() << ' ' << duration.unitsAsString();
  13466. }
  13467. };
  13468. } // end anon namespace
  13469. class TablePrinter {
  13470. std::ostream& m_os;
  13471. std::vector<ColumnInfo> m_columnInfos;
  13472. std::ostringstream m_oss;
  13473. int m_currentColumn = -1;
  13474. bool m_isOpen = false;
  13475. public:
  13476. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  13477. : m_os( os ),
  13478. m_columnInfos( std::move( columnInfos ) ) {}
  13479. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  13480. return m_columnInfos;
  13481. }
  13482. void open() {
  13483. if (!m_isOpen) {
  13484. m_isOpen = true;
  13485. *this << RowBreak();
  13486. Columns headerCols;
  13487. Spacer spacer(2);
  13488. for (auto const& info : m_columnInfos) {
  13489. headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
  13490. headerCols += spacer;
  13491. }
  13492. m_os << headerCols << '\n';
  13493. m_os << Catch::getLineOfChars<'-'>() << '\n';
  13494. }
  13495. }
  13496. void close() {
  13497. if (m_isOpen) {
  13498. *this << RowBreak();
  13499. m_os << std::endl;
  13500. m_isOpen = false;
  13501. }
  13502. }
  13503. template<typename T>
  13504. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  13505. tp.m_oss << value;
  13506. return tp;
  13507. }
  13508. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  13509. auto colStr = tp.m_oss.str();
  13510. const auto strSize = colStr.size();
  13511. tp.m_oss.str("");
  13512. tp.open();
  13513. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  13514. tp.m_currentColumn = -1;
  13515. tp.m_os << '\n';
  13516. }
  13517. tp.m_currentColumn++;
  13518. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  13519. auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
  13520. ? std::string(colInfo.width - (strSize + 1), ' ')
  13521. : std::string();
  13522. if (colInfo.justification == ColumnInfo::Left)
  13523. tp.m_os << colStr << padding << ' ';
  13524. else
  13525. tp.m_os << padding << colStr << ' ';
  13526. return tp;
  13527. }
  13528. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  13529. if (tp.m_currentColumn > 0) {
  13530. tp.m_os << '\n';
  13531. tp.m_currentColumn = -1;
  13532. }
  13533. return tp;
  13534. }
  13535. };
  13536. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  13537. : StreamingReporterBase(config),
  13538. m_tablePrinter(new TablePrinter(config.stream(),
  13539. [&config]() -> std::vector<ColumnInfo> {
  13540. if (config.fullConfig()->benchmarkNoAnalysis())
  13541. {
  13542. return{
  13543. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
  13544. { " samples", 14, ColumnInfo::Right },
  13545. { " iterations", 14, ColumnInfo::Right },
  13546. { " mean", 14, ColumnInfo::Right }
  13547. };
  13548. }
  13549. else
  13550. {
  13551. return{
  13552. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
  13553. { "samples mean std dev", 14, ColumnInfo::Right },
  13554. { "iterations low mean low std dev", 14, ColumnInfo::Right },
  13555. { "estimated high mean high std dev", 14, ColumnInfo::Right }
  13556. };
  13557. }
  13558. }())) {}
  13559. ConsoleReporter::~ConsoleReporter() = default;
  13560. std::string ConsoleReporter::getDescription() {
  13561. return "Reports test results as plain lines of text";
  13562. }
  13563. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  13564. stream << "No test cases matched '" << spec << '\'' << std::endl;
  13565. }
  13566. void ConsoleReporter::reportInvalidArguments(std::string const&arg){
  13567. stream << "Invalid Filter: " << arg << std::endl;
  13568. }
  13569. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  13570. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  13571. AssertionResult const& result = _assertionStats.assertionResult;
  13572. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  13573. // Drop out if result was successful but we're not printing them.
  13574. if (!includeResults && result.getResultType() != ResultWas::Warning)
  13575. return false;
  13576. lazyPrint();
  13577. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  13578. printer.print();
  13579. stream << std::endl;
  13580. return true;
  13581. }
  13582. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  13583. m_tablePrinter->close();
  13584. m_headerPrinted = false;
  13585. StreamingReporterBase::sectionStarting(_sectionInfo);
  13586. }
  13587. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  13588. m_tablePrinter->close();
  13589. if (_sectionStats.missingAssertions) {
  13590. lazyPrint();
  13591. Colour colour(Colour::ResultError);
  13592. if (m_sectionStack.size() > 1)
  13593. stream << "\nNo assertions in section";
  13594. else
  13595. stream << "\nNo assertions in test case";
  13596. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  13597. }
  13598. double dur = _sectionStats.durationInSeconds;
  13599. if (shouldShowDuration(*m_config, dur)) {
  13600. stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  13601. }
  13602. if (m_headerPrinted) {
  13603. m_headerPrinted = false;
  13604. }
  13605. StreamingReporterBase::sectionEnded(_sectionStats);
  13606. }
  13607. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  13608. void ConsoleReporter::benchmarkPreparing(std::string const& name) {
  13609. lazyPrintWithoutClosingBenchmarkTable();
  13610. auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
  13611. bool firstLine = true;
  13612. for (auto line : nameCol) {
  13613. if (!firstLine)
  13614. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  13615. else
  13616. firstLine = false;
  13617. (*m_tablePrinter) << line << ColumnBreak();
  13618. }
  13619. }
  13620. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  13621. (*m_tablePrinter) << info.samples << ColumnBreak()
  13622. << info.iterations << ColumnBreak();
  13623. if (!m_config->benchmarkNoAnalysis())
  13624. (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
  13625. }
  13626. void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
  13627. if (m_config->benchmarkNoAnalysis())
  13628. {
  13629. (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
  13630. }
  13631. else
  13632. {
  13633. (*m_tablePrinter) << ColumnBreak()
  13634. << Duration(stats.mean.point.count()) << ColumnBreak()
  13635. << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
  13636. << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
  13637. << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
  13638. << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
  13639. << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
  13640. }
  13641. }
  13642. void ConsoleReporter::benchmarkFailed(std::string const& error) {
  13643. Colour colour(Colour::Red);
  13644. (*m_tablePrinter)
  13645. << "Benchmark failed (" << error << ')'
  13646. << ColumnBreak() << RowBreak();
  13647. }
  13648. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  13649. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  13650. m_tablePrinter->close();
  13651. StreamingReporterBase::testCaseEnded(_testCaseStats);
  13652. m_headerPrinted = false;
  13653. }
  13654. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  13655. if (currentGroupInfo.used) {
  13656. printSummaryDivider();
  13657. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  13658. printTotals(_testGroupStats.totals);
  13659. stream << '\n' << std::endl;
  13660. }
  13661. StreamingReporterBase::testGroupEnded(_testGroupStats);
  13662. }
  13663. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  13664. printTotalsDivider(_testRunStats.totals);
  13665. printTotals(_testRunStats.totals);
  13666. stream << std::endl;
  13667. StreamingReporterBase::testRunEnded(_testRunStats);
  13668. }
  13669. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  13670. StreamingReporterBase::testRunStarting(_testInfo);
  13671. printTestFilters();
  13672. }
  13673. void ConsoleReporter::lazyPrint() {
  13674. m_tablePrinter->close();
  13675. lazyPrintWithoutClosingBenchmarkTable();
  13676. }
  13677. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  13678. if (!currentTestRunInfo.used)
  13679. lazyPrintRunInfo();
  13680. if (!currentGroupInfo.used)
  13681. lazyPrintGroupInfo();
  13682. if (!m_headerPrinted) {
  13683. printTestCaseAndSectionHeader();
  13684. m_headerPrinted = true;
  13685. }
  13686. }
  13687. void ConsoleReporter::lazyPrintRunInfo() {
  13688. stream << '\n' << getLineOfChars<'~'>() << '\n';
  13689. Colour colour(Colour::SecondaryText);
  13690. stream << currentTestRunInfo->name
  13691. << " is a Catch v" << libraryVersion() << " host application.\n"
  13692. << "Run with -? for options\n\n";
  13693. if (m_config->rngSeed() != 0)
  13694. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  13695. currentTestRunInfo.used = true;
  13696. }
  13697. void ConsoleReporter::lazyPrintGroupInfo() {
  13698. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  13699. printClosedHeader("Group: " + currentGroupInfo->name);
  13700. currentGroupInfo.used = true;
  13701. }
  13702. }
  13703. void ConsoleReporter::printTestCaseAndSectionHeader() {
  13704. assert(!m_sectionStack.empty());
  13705. printOpenHeader(currentTestCaseInfo->name);
  13706. if (m_sectionStack.size() > 1) {
  13707. Colour colourGuard(Colour::Headers);
  13708. auto
  13709. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  13710. itEnd = m_sectionStack.end();
  13711. for (; it != itEnd; ++it)
  13712. printHeaderString(it->name, 2);
  13713. }
  13714. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  13715. stream << getLineOfChars<'-'>() << '\n';
  13716. Colour colourGuard(Colour::FileName);
  13717. stream << lineInfo << '\n';
  13718. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  13719. }
  13720. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  13721. printOpenHeader(_name);
  13722. stream << getLineOfChars<'.'>() << '\n';
  13723. }
  13724. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  13725. stream << getLineOfChars<'-'>() << '\n';
  13726. {
  13727. Colour colourGuard(Colour::Headers);
  13728. printHeaderString(_name);
  13729. }
  13730. }
  13731. // if string has a : in first line will set indent to follow it on
  13732. // subsequent lines
  13733. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  13734. std::size_t i = _string.find(": ");
  13735. if (i != std::string::npos)
  13736. i += 2;
  13737. else
  13738. i = 0;
  13739. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  13740. }
  13741. struct SummaryColumn {
  13742. SummaryColumn( std::string _label, Colour::Code _colour )
  13743. : label( std::move( _label ) ),
  13744. colour( _colour ) {}
  13745. SummaryColumn addRow( std::size_t count ) {
  13746. ReusableStringStream rss;
  13747. rss << count;
  13748. std::string row = rss.str();
  13749. for (auto& oldRow : rows) {
  13750. while (oldRow.size() < row.size())
  13751. oldRow = ' ' + oldRow;
  13752. while (oldRow.size() > row.size())
  13753. row = ' ' + row;
  13754. }
  13755. rows.push_back(row);
  13756. return *this;
  13757. }
  13758. std::string label;
  13759. Colour::Code colour;
  13760. std::vector<std::string> rows;
  13761. };
  13762. void ConsoleReporter::printTotals( Totals const& totals ) {
  13763. if (totals.testCases.total() == 0) {
  13764. stream << Colour(Colour::Warning) << "No tests ran\n";
  13765. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  13766. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  13767. stream << " ("
  13768. << pluralise(totals.assertions.passed, "assertion") << " in "
  13769. << pluralise(totals.testCases.passed, "test case") << ')'
  13770. << '\n';
  13771. } else {
  13772. std::vector<SummaryColumn> columns;
  13773. columns.push_back(SummaryColumn("", Colour::None)
  13774. .addRow(totals.testCases.total())
  13775. .addRow(totals.assertions.total()));
  13776. columns.push_back(SummaryColumn("passed", Colour::Success)
  13777. .addRow(totals.testCases.passed)
  13778. .addRow(totals.assertions.passed));
  13779. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  13780. .addRow(totals.testCases.failed)
  13781. .addRow(totals.assertions.failed));
  13782. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  13783. .addRow(totals.testCases.failedButOk)
  13784. .addRow(totals.assertions.failedButOk));
  13785. printSummaryRow("test cases", columns, 0);
  13786. printSummaryRow("assertions", columns, 1);
  13787. }
  13788. }
  13789. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  13790. for (auto col : cols) {
  13791. std::string value = col.rows[row];
  13792. if (col.label.empty()) {
  13793. stream << label << ": ";
  13794. if (value != "0")
  13795. stream << value;
  13796. else
  13797. stream << Colour(Colour::Warning) << "- none -";
  13798. } else if (value != "0") {
  13799. stream << Colour(Colour::LightGrey) << " | ";
  13800. stream << Colour(col.colour)
  13801. << value << ' ' << col.label;
  13802. }
  13803. }
  13804. stream << '\n';
  13805. }
  13806. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  13807. if (totals.testCases.total() > 0) {
  13808. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  13809. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  13810. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  13811. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13812. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  13813. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  13814. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  13815. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  13816. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  13817. if (totals.testCases.allPassed())
  13818. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  13819. else
  13820. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  13821. } else {
  13822. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  13823. }
  13824. stream << '\n';
  13825. }
  13826. void ConsoleReporter::printSummaryDivider() {
  13827. stream << getLineOfChars<'-'>() << '\n';
  13828. }
  13829. void ConsoleReporter::printTestFilters() {
  13830. if (m_config->testSpec().hasFilters()) {
  13831. Colour guard(Colour::BrightYellow);
  13832. stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
  13833. }
  13834. }
  13835. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  13836. } // end namespace Catch
  13837. #if defined(_MSC_VER)
  13838. #pragma warning(pop)
  13839. #endif
  13840. #if defined(__clang__)
  13841. # pragma clang diagnostic pop
  13842. #endif
  13843. // end catch_reporter_console.cpp
  13844. // start catch_reporter_junit.cpp
  13845. #include <cassert>
  13846. #include <sstream>
  13847. #include <ctime>
  13848. #include <algorithm>
  13849. #include <iomanip>
  13850. namespace Catch {
  13851. namespace {
  13852. std::string getCurrentTimestamp() {
  13853. // Beware, this is not reentrant because of backward compatibility issues
  13854. // Also, UTC only, again because of backward compatibility (%z is C++11)
  13855. time_t rawtime;
  13856. std::time(&rawtime);
  13857. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  13858. #ifdef _MSC_VER
  13859. std::tm timeInfo = {};
  13860. gmtime_s(&timeInfo, &rawtime);
  13861. #else
  13862. std::tm* timeInfo;
  13863. timeInfo = std::gmtime(&rawtime);
  13864. #endif
  13865. char timeStamp[timeStampSize];
  13866. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  13867. #ifdef _MSC_VER
  13868. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  13869. #else
  13870. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  13871. #endif
  13872. return std::string(timeStamp, timeStampSize-1);
  13873. }
  13874. std::string fileNameTag(const std::vector<std::string> &tags) {
  13875. auto it = std::find_if(begin(tags),
  13876. end(tags),
  13877. [] (std::string const& tag) {return tag.front() == '#'; });
  13878. if (it != tags.end())
  13879. return it->substr(1);
  13880. return std::string();
  13881. }
  13882. // Formats the duration in seconds to 3 decimal places.
  13883. // This is done because some genius defined Maven Surefire schema
  13884. // in a way that only accepts 3 decimal places, and tools like
  13885. // Jenkins use that schema for validation JUnit reporter output.
  13886. std::string formatDuration( double seconds ) {
  13887. ReusableStringStream rss;
  13888. rss << std::fixed << std::setprecision( 3 ) << seconds;
  13889. return rss.str();
  13890. }
  13891. } // anonymous namespace
  13892. JunitReporter::JunitReporter( ReporterConfig const& _config )
  13893. : CumulativeReporterBase( _config ),
  13894. xml( _config.stream() )
  13895. {
  13896. m_reporterPrefs.shouldRedirectStdOut = true;
  13897. m_reporterPrefs.shouldReportAllAssertions = true;
  13898. }
  13899. JunitReporter::~JunitReporter() {}
  13900. std::string JunitReporter::getDescription() {
  13901. return "Reports test results in an XML format that looks like Ant's junitreport target";
  13902. }
  13903. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  13904. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  13905. CumulativeReporterBase::testRunStarting( runInfo );
  13906. xml.startElement( "testsuites" );
  13907. }
  13908. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  13909. suiteTimer.start();
  13910. stdOutForSuite.clear();
  13911. stdErrForSuite.clear();
  13912. unexpectedExceptions = 0;
  13913. CumulativeReporterBase::testGroupStarting( groupInfo );
  13914. }
  13915. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  13916. m_okToFail = testCaseInfo.okToFail();
  13917. }
  13918. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  13919. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  13920. unexpectedExceptions++;
  13921. return CumulativeReporterBase::assertionEnded( assertionStats );
  13922. }
  13923. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  13924. stdOutForSuite += testCaseStats.stdOut;
  13925. stdErrForSuite += testCaseStats.stdErr;
  13926. CumulativeReporterBase::testCaseEnded( testCaseStats );
  13927. }
  13928. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  13929. double suiteTime = suiteTimer.getElapsedSeconds();
  13930. CumulativeReporterBase::testGroupEnded( testGroupStats );
  13931. writeGroup( *m_testGroups.back(), suiteTime );
  13932. }
  13933. void JunitReporter::testRunEndedCumulative() {
  13934. xml.endElement();
  13935. }
  13936. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  13937. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  13938. TestGroupStats const& stats = groupNode.value;
  13939. xml.writeAttribute( "name", stats.groupInfo.name );
  13940. xml.writeAttribute( "errors", unexpectedExceptions );
  13941. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  13942. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  13943. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  13944. if( m_config->showDurations() == ShowDurations::Never )
  13945. xml.writeAttribute( "time", "" );
  13946. else
  13947. xml.writeAttribute( "time", formatDuration( suiteTime ) );
  13948. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  13949. // Write properties if there are any
  13950. if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
  13951. auto properties = xml.scopedElement("properties");
  13952. if (m_config->hasTestFilters()) {
  13953. xml.scopedElement("property")
  13954. .writeAttribute("name", "filters")
  13955. .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
  13956. }
  13957. if (m_config->rngSeed() != 0) {
  13958. xml.scopedElement("property")
  13959. .writeAttribute("name", "random-seed")
  13960. .writeAttribute("value", m_config->rngSeed());
  13961. }
  13962. }
  13963. // Write test cases
  13964. for( auto const& child : groupNode.children )
  13965. writeTestCase( *child );
  13966. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
  13967. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
  13968. }
  13969. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  13970. TestCaseStats const& stats = testCaseNode.value;
  13971. // All test cases have exactly one section - which represents the
  13972. // test case itself. That section may have 0-n nested sections
  13973. assert( testCaseNode.children.size() == 1 );
  13974. SectionNode const& rootSection = *testCaseNode.children.front();
  13975. std::string className = stats.testInfo.className;
  13976. if( className.empty() ) {
  13977. className = fileNameTag(stats.testInfo.tags);
  13978. if ( className.empty() )
  13979. className = "global";
  13980. }
  13981. if ( !m_config->name().empty() )
  13982. className = m_config->name() + "." + className;
  13983. writeSection( className, "", rootSection, stats.testInfo.okToFail() );
  13984. }
  13985. void JunitReporter::writeSection( std::string const& className,
  13986. std::string const& rootName,
  13987. SectionNode const& sectionNode,
  13988. bool testOkToFail) {
  13989. std::string name = trim( sectionNode.stats.sectionInfo.name );
  13990. if( !rootName.empty() )
  13991. name = rootName + '/' + name;
  13992. if( !sectionNode.assertions.empty() ||
  13993. !sectionNode.stdOut.empty() ||
  13994. !sectionNode.stdErr.empty() ) {
  13995. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  13996. if( className.empty() ) {
  13997. xml.writeAttribute( "classname", name );
  13998. xml.writeAttribute( "name", "root" );
  13999. }
  14000. else {
  14001. xml.writeAttribute( "classname", className );
  14002. xml.writeAttribute( "name", name );
  14003. }
  14004. xml.writeAttribute( "time", formatDuration( sectionNode.stats.durationInSeconds ) );
  14005. // This is not ideal, but it should be enough to mimic gtest's
  14006. // junit output.
  14007. // Ideally the JUnit reporter would also handle `skipTest`
  14008. // events and write those out appropriately.
  14009. xml.writeAttribute( "status", "run" );
  14010. if (sectionNode.stats.assertions.failedButOk) {
  14011. xml.scopedElement("skipped")
  14012. .writeAttribute("message", "TEST_CASE tagged with !mayfail");
  14013. }
  14014. writeAssertions( sectionNode );
  14015. if( !sectionNode.stdOut.empty() )
  14016. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
  14017. if( !sectionNode.stdErr.empty() )
  14018. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
  14019. }
  14020. for( auto const& childNode : sectionNode.childSections )
  14021. if( className.empty() )
  14022. writeSection( name, "", *childNode, testOkToFail );
  14023. else
  14024. writeSection( className, name, *childNode, testOkToFail );
  14025. }
  14026. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  14027. for( auto const& assertion : sectionNode.assertions )
  14028. writeAssertion( assertion );
  14029. }
  14030. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  14031. AssertionResult const& result = stats.assertionResult;
  14032. if( !result.isOk() ) {
  14033. std::string elementName;
  14034. switch( result.getResultType() ) {
  14035. case ResultWas::ThrewException:
  14036. case ResultWas::FatalErrorCondition:
  14037. elementName = "error";
  14038. break;
  14039. case ResultWas::ExplicitFailure:
  14040. case ResultWas::ExpressionFailed:
  14041. case ResultWas::DidntThrowException:
  14042. elementName = "failure";
  14043. break;
  14044. // We should never see these here:
  14045. case ResultWas::Info:
  14046. case ResultWas::Warning:
  14047. case ResultWas::Ok:
  14048. case ResultWas::Unknown:
  14049. case ResultWas::FailureBit:
  14050. case ResultWas::Exception:
  14051. elementName = "internalError";
  14052. break;
  14053. }
  14054. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  14055. xml.writeAttribute( "message", result.getExpression() );
  14056. xml.writeAttribute( "type", result.getTestMacroName() );
  14057. ReusableStringStream rss;
  14058. if (stats.totals.assertions.total() > 0) {
  14059. rss << "FAILED" << ":\n";
  14060. if (result.hasExpression()) {
  14061. rss << " ";
  14062. rss << result.getExpressionInMacro();
  14063. rss << '\n';
  14064. }
  14065. if (result.hasExpandedExpression()) {
  14066. rss << "with expansion:\n";
  14067. rss << Column(result.getExpandedExpression()).indent(2) << '\n';
  14068. }
  14069. } else {
  14070. rss << '\n';
  14071. }
  14072. if( !result.getMessage().empty() )
  14073. rss << result.getMessage() << '\n';
  14074. for( auto const& msg : stats.infoMessages )
  14075. if( msg.type == ResultWas::Info )
  14076. rss << msg.message << '\n';
  14077. rss << "at " << result.getSourceInfo();
  14078. xml.writeText( rss.str(), XmlFormatting::Newline );
  14079. }
  14080. }
  14081. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  14082. } // end namespace Catch
  14083. // end catch_reporter_junit.cpp
  14084. // start catch_reporter_listening.cpp
  14085. #include <cassert>
  14086. namespace Catch {
  14087. ListeningReporter::ListeningReporter() {
  14088. // We will assume that listeners will always want all assertions
  14089. m_preferences.shouldReportAllAssertions = true;
  14090. }
  14091. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  14092. m_listeners.push_back( std::move( listener ) );
  14093. }
  14094. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  14095. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  14096. m_reporter = std::move( reporter );
  14097. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  14098. }
  14099. ReporterPreferences ListeningReporter::getPreferences() const {
  14100. return m_preferences;
  14101. }
  14102. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  14103. return std::set<Verbosity>{ };
  14104. }
  14105. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  14106. for ( auto const& listener : m_listeners ) {
  14107. listener->noMatchingTestCases( spec );
  14108. }
  14109. m_reporter->noMatchingTestCases( spec );
  14110. }
  14111. void ListeningReporter::reportInvalidArguments(std::string const&arg){
  14112. for ( auto const& listener : m_listeners ) {
  14113. listener->reportInvalidArguments( arg );
  14114. }
  14115. m_reporter->reportInvalidArguments( arg );
  14116. }
  14117. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14118. void ListeningReporter::benchmarkPreparing( std::string const& name ) {
  14119. for (auto const& listener : m_listeners) {
  14120. listener->benchmarkPreparing(name);
  14121. }
  14122. m_reporter->benchmarkPreparing(name);
  14123. }
  14124. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  14125. for ( auto const& listener : m_listeners ) {
  14126. listener->benchmarkStarting( benchmarkInfo );
  14127. }
  14128. m_reporter->benchmarkStarting( benchmarkInfo );
  14129. }
  14130. void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
  14131. for ( auto const& listener : m_listeners ) {
  14132. listener->benchmarkEnded( benchmarkStats );
  14133. }
  14134. m_reporter->benchmarkEnded( benchmarkStats );
  14135. }
  14136. void ListeningReporter::benchmarkFailed( std::string const& error ) {
  14137. for (auto const& listener : m_listeners) {
  14138. listener->benchmarkFailed(error);
  14139. }
  14140. m_reporter->benchmarkFailed(error);
  14141. }
  14142. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14143. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  14144. for ( auto const& listener : m_listeners ) {
  14145. listener->testRunStarting( testRunInfo );
  14146. }
  14147. m_reporter->testRunStarting( testRunInfo );
  14148. }
  14149. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  14150. for ( auto const& listener : m_listeners ) {
  14151. listener->testGroupStarting( groupInfo );
  14152. }
  14153. m_reporter->testGroupStarting( groupInfo );
  14154. }
  14155. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  14156. for ( auto const& listener : m_listeners ) {
  14157. listener->testCaseStarting( testInfo );
  14158. }
  14159. m_reporter->testCaseStarting( testInfo );
  14160. }
  14161. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  14162. for ( auto const& listener : m_listeners ) {
  14163. listener->sectionStarting( sectionInfo );
  14164. }
  14165. m_reporter->sectionStarting( sectionInfo );
  14166. }
  14167. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  14168. for ( auto const& listener : m_listeners ) {
  14169. listener->assertionStarting( assertionInfo );
  14170. }
  14171. m_reporter->assertionStarting( assertionInfo );
  14172. }
  14173. // The return value indicates if the messages buffer should be cleared:
  14174. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  14175. for( auto const& listener : m_listeners ) {
  14176. static_cast<void>( listener->assertionEnded( assertionStats ) );
  14177. }
  14178. return m_reporter->assertionEnded( assertionStats );
  14179. }
  14180. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  14181. for ( auto const& listener : m_listeners ) {
  14182. listener->sectionEnded( sectionStats );
  14183. }
  14184. m_reporter->sectionEnded( sectionStats );
  14185. }
  14186. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  14187. for ( auto const& listener : m_listeners ) {
  14188. listener->testCaseEnded( testCaseStats );
  14189. }
  14190. m_reporter->testCaseEnded( testCaseStats );
  14191. }
  14192. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  14193. for ( auto const& listener : m_listeners ) {
  14194. listener->testGroupEnded( testGroupStats );
  14195. }
  14196. m_reporter->testGroupEnded( testGroupStats );
  14197. }
  14198. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  14199. for ( auto const& listener : m_listeners ) {
  14200. listener->testRunEnded( testRunStats );
  14201. }
  14202. m_reporter->testRunEnded( testRunStats );
  14203. }
  14204. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  14205. for ( auto const& listener : m_listeners ) {
  14206. listener->skipTest( testInfo );
  14207. }
  14208. m_reporter->skipTest( testInfo );
  14209. }
  14210. bool ListeningReporter::isMulti() const {
  14211. return true;
  14212. }
  14213. } // end namespace Catch
  14214. // end catch_reporter_listening.cpp
  14215. // start catch_reporter_xml.cpp
  14216. #if defined(_MSC_VER)
  14217. #pragma warning(push)
  14218. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  14219. // Note that 4062 (not all labels are handled
  14220. // and default is missing) is enabled
  14221. #endif
  14222. namespace Catch {
  14223. XmlReporter::XmlReporter( ReporterConfig const& _config )
  14224. : StreamingReporterBase( _config ),
  14225. m_xml(_config.stream())
  14226. {
  14227. m_reporterPrefs.shouldRedirectStdOut = true;
  14228. m_reporterPrefs.shouldReportAllAssertions = true;
  14229. }
  14230. XmlReporter::~XmlReporter() = default;
  14231. std::string XmlReporter::getDescription() {
  14232. return "Reports test results as an XML document";
  14233. }
  14234. std::string XmlReporter::getStylesheetRef() const {
  14235. return std::string();
  14236. }
  14237. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  14238. m_xml
  14239. .writeAttribute( "filename", sourceInfo.file )
  14240. .writeAttribute( "line", sourceInfo.line );
  14241. }
  14242. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  14243. StreamingReporterBase::noMatchingTestCases( s );
  14244. }
  14245. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  14246. StreamingReporterBase::testRunStarting( testInfo );
  14247. std::string stylesheetRef = getStylesheetRef();
  14248. if( !stylesheetRef.empty() )
  14249. m_xml.writeStylesheetRef( stylesheetRef );
  14250. m_xml.startElement( "Catch" );
  14251. if( !m_config->name().empty() )
  14252. m_xml.writeAttribute( "name", m_config->name() );
  14253. if (m_config->testSpec().hasFilters())
  14254. m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
  14255. if( m_config->rngSeed() != 0 )
  14256. m_xml.scopedElement( "Randomness" )
  14257. .writeAttribute( "seed", m_config->rngSeed() );
  14258. }
  14259. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  14260. StreamingReporterBase::testGroupStarting( groupInfo );
  14261. m_xml.startElement( "Group" )
  14262. .writeAttribute( "name", groupInfo.name );
  14263. }
  14264. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  14265. StreamingReporterBase::testCaseStarting(testInfo);
  14266. m_xml.startElement( "TestCase" )
  14267. .writeAttribute( "name", trim( testInfo.name ) )
  14268. .writeAttribute( "description", testInfo.description )
  14269. .writeAttribute( "tags", testInfo.tagsAsString() );
  14270. writeSourceInfo( testInfo.lineInfo );
  14271. if ( m_config->showDurations() == ShowDurations::Always )
  14272. m_testCaseTimer.start();
  14273. m_xml.ensureTagClosed();
  14274. }
  14275. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  14276. StreamingReporterBase::sectionStarting( sectionInfo );
  14277. if( m_sectionDepth++ > 0 ) {
  14278. m_xml.startElement( "Section" )
  14279. .writeAttribute( "name", trim( sectionInfo.name ) );
  14280. writeSourceInfo( sectionInfo.lineInfo );
  14281. m_xml.ensureTagClosed();
  14282. }
  14283. }
  14284. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  14285. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  14286. AssertionResult const& result = assertionStats.assertionResult;
  14287. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  14288. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  14289. // Print any info messages in <Info> tags.
  14290. for( auto const& msg : assertionStats.infoMessages ) {
  14291. if( msg.type == ResultWas::Info && includeResults ) {
  14292. m_xml.scopedElement( "Info" )
  14293. .writeText( msg.message );
  14294. } else if ( msg.type == ResultWas::Warning ) {
  14295. m_xml.scopedElement( "Warning" )
  14296. .writeText( msg.message );
  14297. }
  14298. }
  14299. }
  14300. // Drop out if result was successful but we're not printing them.
  14301. if( !includeResults && result.getResultType() != ResultWas::Warning )
  14302. return true;
  14303. // Print the expression if there is one.
  14304. if( result.hasExpression() ) {
  14305. m_xml.startElement( "Expression" )
  14306. .writeAttribute( "success", result.succeeded() )
  14307. .writeAttribute( "type", result.getTestMacroName() );
  14308. writeSourceInfo( result.getSourceInfo() );
  14309. m_xml.scopedElement( "Original" )
  14310. .writeText( result.getExpression() );
  14311. m_xml.scopedElement( "Expanded" )
  14312. .writeText( result.getExpandedExpression() );
  14313. }
  14314. // And... Print a result applicable to each result type.
  14315. switch( result.getResultType() ) {
  14316. case ResultWas::ThrewException:
  14317. m_xml.startElement( "Exception" );
  14318. writeSourceInfo( result.getSourceInfo() );
  14319. m_xml.writeText( result.getMessage() );
  14320. m_xml.endElement();
  14321. break;
  14322. case ResultWas::FatalErrorCondition:
  14323. m_xml.startElement( "FatalErrorCondition" );
  14324. writeSourceInfo( result.getSourceInfo() );
  14325. m_xml.writeText( result.getMessage() );
  14326. m_xml.endElement();
  14327. break;
  14328. case ResultWas::Info:
  14329. m_xml.scopedElement( "Info" )
  14330. .writeText( result.getMessage() );
  14331. break;
  14332. case ResultWas::Warning:
  14333. // Warning will already have been written
  14334. break;
  14335. case ResultWas::ExplicitFailure:
  14336. m_xml.startElement( "Failure" );
  14337. writeSourceInfo( result.getSourceInfo() );
  14338. m_xml.writeText( result.getMessage() );
  14339. m_xml.endElement();
  14340. break;
  14341. default:
  14342. break;
  14343. }
  14344. if( result.hasExpression() )
  14345. m_xml.endElement();
  14346. return true;
  14347. }
  14348. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  14349. StreamingReporterBase::sectionEnded( sectionStats );
  14350. if( --m_sectionDepth > 0 ) {
  14351. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  14352. e.writeAttribute( "successes", sectionStats.assertions.passed );
  14353. e.writeAttribute( "failures", sectionStats.assertions.failed );
  14354. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  14355. if ( m_config->showDurations() == ShowDurations::Always )
  14356. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  14357. m_xml.endElement();
  14358. }
  14359. }
  14360. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  14361. StreamingReporterBase::testCaseEnded( testCaseStats );
  14362. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  14363. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  14364. if ( m_config->showDurations() == ShowDurations::Always )
  14365. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  14366. if( !testCaseStats.stdOut.empty() )
  14367. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
  14368. if( !testCaseStats.stdErr.empty() )
  14369. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
  14370. m_xml.endElement();
  14371. }
  14372. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  14373. StreamingReporterBase::testGroupEnded( testGroupStats );
  14374. // TODO: Check testGroupStats.aborting and act accordingly.
  14375. m_xml.scopedElement( "OverallResults" )
  14376. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  14377. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  14378. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  14379. m_xml.scopedElement( "OverallResultsCases")
  14380. .writeAttribute( "successes", testGroupStats.totals.testCases.passed )
  14381. .writeAttribute( "failures", testGroupStats.totals.testCases.failed )
  14382. .writeAttribute( "expectedFailures", testGroupStats.totals.testCases.failedButOk );
  14383. m_xml.endElement();
  14384. }
  14385. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  14386. StreamingReporterBase::testRunEnded( testRunStats );
  14387. m_xml.scopedElement( "OverallResults" )
  14388. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  14389. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  14390. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  14391. m_xml.scopedElement( "OverallResultsCases")
  14392. .writeAttribute( "successes", testRunStats.totals.testCases.passed )
  14393. .writeAttribute( "failures", testRunStats.totals.testCases.failed )
  14394. .writeAttribute( "expectedFailures", testRunStats.totals.testCases.failedButOk );
  14395. m_xml.endElement();
  14396. }
  14397. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14398. void XmlReporter::benchmarkPreparing(std::string const& name) {
  14399. m_xml.startElement("BenchmarkResults")
  14400. .writeAttribute("name", name);
  14401. }
  14402. void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
  14403. m_xml.writeAttribute("samples", info.samples)
  14404. .writeAttribute("resamples", info.resamples)
  14405. .writeAttribute("iterations", info.iterations)
  14406. .writeAttribute("clockResolution", info.clockResolution)
  14407. .writeAttribute("estimatedDuration", info.estimatedDuration)
  14408. .writeComment("All values in nano seconds");
  14409. }
  14410. void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
  14411. m_xml.startElement("mean")
  14412. .writeAttribute("value", benchmarkStats.mean.point.count())
  14413. .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
  14414. .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
  14415. .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
  14416. m_xml.endElement();
  14417. m_xml.startElement("standardDeviation")
  14418. .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
  14419. .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
  14420. .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
  14421. .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
  14422. m_xml.endElement();
  14423. m_xml.startElement("outliers")
  14424. .writeAttribute("variance", benchmarkStats.outlierVariance)
  14425. .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
  14426. .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
  14427. .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
  14428. .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
  14429. m_xml.endElement();
  14430. m_xml.endElement();
  14431. }
  14432. void XmlReporter::benchmarkFailed(std::string const &error) {
  14433. m_xml.scopedElement("failed").
  14434. writeAttribute("message", error);
  14435. m_xml.endElement();
  14436. }
  14437. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14438. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  14439. } // end namespace Catch
  14440. #if defined(_MSC_VER)
  14441. #pragma warning(pop)
  14442. #endif
  14443. // end catch_reporter_xml.cpp
  14444. namespace Catch {
  14445. LeakDetector leakDetector;
  14446. }
  14447. #ifdef __clang__
  14448. #pragma clang diagnostic pop
  14449. #endif
  14450. // end catch_impl.hpp
  14451. #endif
  14452. #ifdef CATCH_CONFIG_MAIN
  14453. // start catch_default_main.hpp
  14454. #ifndef __OBJC__
  14455. #ifndef CATCH_INTERNAL_CDECL
  14456. #ifdef _MSC_VER
  14457. #define CATCH_INTERNAL_CDECL __cdecl
  14458. #else
  14459. #define CATCH_INTERNAL_CDECL
  14460. #endif
  14461. #endif
  14462. #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  14463. // Standard C/C++ Win32 Unicode wmain entry point
  14464. extern "C" int CATCH_INTERNAL_CDECL wmain (int argc, wchar_t * argv[], wchar_t * []) {
  14465. #else
  14466. // Standard C/C++ main entry point
  14467. int CATCH_INTERNAL_CDECL main (int argc, char * argv[]) {
  14468. #endif
  14469. return Catch::Session().run( argc, argv );
  14470. }
  14471. #else // __OBJC__
  14472. // Objective-C entry point
  14473. int main (int argc, char * const argv[]) {
  14474. #if !CATCH_ARC_ENABLED
  14475. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  14476. #endif
  14477. Catch::registerTestMethods();
  14478. int result = Catch::Session().run( argc, (char**)argv );
  14479. #if !CATCH_ARC_ENABLED
  14480. [pool drain];
  14481. #endif
  14482. return result;
  14483. }
  14484. #endif // __OBJC__
  14485. // end catch_default_main.hpp
  14486. #endif
  14487. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  14488. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  14489. # undef CLARA_CONFIG_MAIN
  14490. #endif
  14491. #if !defined(CATCH_CONFIG_DISABLE)
  14492. //////
  14493. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  14494. #ifdef CATCH_CONFIG_PREFIX_ALL
  14495. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14496. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14497. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14498. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  14499. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  14500. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14501. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  14502. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  14503. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14504. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14505. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14506. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14507. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14508. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  14509. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14510. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  14511. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14512. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14513. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14514. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14515. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14516. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14517. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  14518. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  14519. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14520. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  14521. #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
  14522. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  14523. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  14524. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  14525. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14526. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  14527. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  14528. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  14529. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  14530. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14531. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14532. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14533. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  14534. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14535. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14536. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  14537. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14538. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14539. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  14540. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  14541. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14542. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14543. #else
  14544. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  14545. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  14546. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14547. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14548. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  14549. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  14550. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14551. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14552. #endif
  14553. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  14554. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  14555. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  14556. #else
  14557. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  14558. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  14559. #endif
  14560. // "BDD-style" convenience wrappers
  14561. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  14562. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  14563. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  14564. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  14565. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  14566. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  14567. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  14568. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  14569. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14570. #define CATCH_BENCHMARK(...) \
  14571. INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
  14572. #define CATCH_BENCHMARK_ADVANCED(name) \
  14573. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name)
  14574. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14575. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  14576. #else
  14577. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14578. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14579. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14580. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  14581. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  14582. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14583. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  14584. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14585. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14586. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14587. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  14588. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14589. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14590. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  14591. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14592. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  14593. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14594. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14595. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  14596. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14597. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14598. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14599. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  14600. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  14601. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14602. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  14603. #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
  14604. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  14605. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  14606. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  14607. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14608. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  14609. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  14610. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  14611. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  14612. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  14613. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14614. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  14615. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  14616. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14617. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14618. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
  14619. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14620. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14621. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  14622. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
  14623. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14624. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
  14625. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
  14626. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14627. #else
  14628. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  14629. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
  14630. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14631. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14632. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  14633. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
  14634. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14635. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
  14636. #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
  14637. #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  14638. #endif
  14639. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  14640. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  14641. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  14642. #else
  14643. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  14644. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  14645. #endif
  14646. #endif
  14647. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  14648. // "BDD-style" convenience wrappers
  14649. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  14650. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  14651. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  14652. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  14653. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  14654. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  14655. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  14656. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  14657. #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
  14658. #define BENCHMARK(...) \
  14659. INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
  14660. #define BENCHMARK_ADVANCED(name) \
  14661. INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name)
  14662. #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
  14663. using Catch::Detail::Approx;
  14664. #else // CATCH_CONFIG_DISABLE
  14665. //////
  14666. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  14667. #ifdef CATCH_CONFIG_PREFIX_ALL
  14668. #define CATCH_REQUIRE( ... ) (void)(0)
  14669. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  14670. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  14671. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  14672. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  14673. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14674. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14675. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  14676. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  14677. #define CATCH_CHECK( ... ) (void)(0)
  14678. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  14679. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  14680. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  14681. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  14682. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  14683. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  14684. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  14685. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14686. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14687. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14688. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  14689. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14690. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  14691. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  14692. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14693. #define CATCH_INFO( msg ) (void)(0)
  14694. #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
  14695. #define CATCH_WARN( msg ) (void)(0)
  14696. #define CATCH_CAPTURE( msg ) (void)(0)
  14697. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14698. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14699. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  14700. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  14701. #define CATCH_SECTION( ... )
  14702. #define CATCH_DYNAMIC_SECTION( ... )
  14703. #define CATCH_FAIL( ... ) (void)(0)
  14704. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  14705. #define CATCH_SUCCEED( ... ) (void)(0)
  14706. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14707. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14708. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14709. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14710. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14711. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14712. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14713. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14714. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14715. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14716. #else
  14717. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14718. #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14719. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14720. #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14721. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14722. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14723. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14724. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14725. #endif
  14726. // "BDD-style" convenience wrappers
  14727. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14728. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), className )
  14729. #define CATCH_GIVEN( desc )
  14730. #define CATCH_AND_GIVEN( desc )
  14731. #define CATCH_WHEN( desc )
  14732. #define CATCH_AND_WHEN( desc )
  14733. #define CATCH_THEN( desc )
  14734. #define CATCH_AND_THEN( desc )
  14735. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  14736. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14737. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  14738. #else
  14739. #define REQUIRE( ... ) (void)(0)
  14740. #define REQUIRE_FALSE( ... ) (void)(0)
  14741. #define REQUIRE_THROWS( ... ) (void)(0)
  14742. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  14743. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  14744. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14745. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14746. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14747. #define REQUIRE_NOTHROW( ... ) (void)(0)
  14748. #define CHECK( ... ) (void)(0)
  14749. #define CHECK_FALSE( ... ) (void)(0)
  14750. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  14751. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  14752. #define CHECK_NOFAIL( ... ) (void)(0)
  14753. #define CHECK_THROWS( ... ) (void)(0)
  14754. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  14755. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  14756. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14757. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  14758. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14759. #define CHECK_NOTHROW( ... ) (void)(0)
  14760. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  14761. #define CHECK_THAT( arg, matcher ) (void)(0)
  14762. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  14763. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  14764. #define INFO( msg ) (void)(0)
  14765. #define UNSCOPED_INFO( msg ) (void)(0)
  14766. #define WARN( msg ) (void)(0)
  14767. #define CAPTURE( ... ) (void)(0)
  14768. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14769. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14770. #define METHOD_AS_TEST_CASE( method, ... )
  14771. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  14772. #define SECTION( ... )
  14773. #define DYNAMIC_SECTION( ... )
  14774. #define FAIL( ... ) (void)(0)
  14775. #define FAIL_CHECK( ... ) (void)(0)
  14776. #define SUCCEED( ... ) (void)(0)
  14777. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
  14778. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  14779. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
  14780. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
  14781. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
  14782. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
  14783. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14784. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14785. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14786. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14787. #else
  14788. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
  14789. #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
  14790. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14791. #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
  14792. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14793. #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  14794. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14795. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  14796. #endif
  14797. #define STATIC_REQUIRE( ... ) (void)(0)
  14798. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  14799. #endif
  14800. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  14801. // "BDD-style" convenience wrappers
  14802. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ) )
  14803. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), className )
  14804. #define GIVEN( desc )
  14805. #define AND_GIVEN( desc )
  14806. #define WHEN( desc )
  14807. #define AND_WHEN( desc )
  14808. #define THEN( desc )
  14809. #define AND_THEN( desc )
  14810. using Catch::Detail::Approx;
  14811. #endif
  14812. #endif // ! CATCH_CONFIG_IMPL_ONLY
  14813. // start catch_reenable_warnings.h
  14814. #ifdef __clang__
  14815. # ifdef __ICC // icpc defines the __clang__ macro
  14816. # pragma warning(pop)
  14817. # else
  14818. # pragma clang diagnostic pop
  14819. # endif
  14820. #elif defined __GNUC__
  14821. # pragma GCC diagnostic pop
  14822. #endif
  14823. // end catch_reenable_warnings.h
  14824. // end catch.hpp
  14825. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED